xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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   switch (Result.getResultKind()) {
376   case LookupResult::NotFound:
377   case LookupResult::NotFoundInCurrentInstantiation:
378     if (CorrectedII) {
379       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
380                                AllowDeducedTemplate);
381       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
382                                               S, SS, CCC, CTK_ErrorRecovery);
383       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
384       TemplateTy Template;
385       bool MemberOfUnknownSpecialization;
386       UnqualifiedId TemplateName;
387       TemplateName.setIdentifier(NewII, NameLoc);
388       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
389       CXXScopeSpec NewSS, *NewSSPtr = SS;
390       if (SS && NNS) {
391         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
392         NewSSPtr = &NewSS;
393       }
394       if (Correction && (NNS || NewII != &II) &&
395           // Ignore a correction to a template type as the to-be-corrected
396           // identifier is not a template (typo correction for template names
397           // is handled elsewhere).
398           !(getLangOpts().CPlusPlus && NewSSPtr &&
399             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
400                            Template, MemberOfUnknownSpecialization))) {
401         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
402                                     isClassName, HasTrailingDot, ObjectTypePtr,
403                                     IsCtorOrDtorName,
404                                     WantNontrivialTypeSourceInfo,
405                                     IsClassTemplateDeductionContext);
406         if (Ty) {
407           diagnoseTypo(Correction,
408                        PDiag(diag::err_unknown_type_or_class_name_suggest)
409                          << Result.getLookupName() << isClassName);
410           if (SS && NNS)
411             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
412           *CorrectedII = NewII;
413           return Ty;
414         }
415       }
416     }
417     // If typo correction failed or was not performed, fall through
418     LLVM_FALLTHROUGH;
419   case LookupResult::FoundOverloaded:
420   case LookupResult::FoundUnresolvedValue:
421     Result.suppressDiagnostics();
422     return nullptr;
423 
424   case LookupResult::Ambiguous:
425     // Recover from type-hiding ambiguities by hiding the type.  We'll
426     // do the lookup again when looking for an object, and we can
427     // diagnose the error then.  If we don't do this, then the error
428     // about hiding the type will be immediately followed by an error
429     // that only makes sense if the identifier was treated like a type.
430     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
431       Result.suppressDiagnostics();
432       return nullptr;
433     }
434 
435     // Look to see if we have a type anywhere in the list of results.
436     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
437          Res != ResEnd; ++Res) {
438       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
439       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
440               RealRes) ||
441           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
442         if (!IIDecl ||
443             // Make the selection of the recovery decl deterministic.
444             RealRes->getLocation() < IIDecl->getLocation())
445           IIDecl = RealRes;
446       }
447     }
448 
449     if (!IIDecl) {
450       // None of the entities we found is a type, so there is no way
451       // to even assume that the result is a type. In this case, don't
452       // complain about the ambiguity. The parser will either try to
453       // perform this lookup again (e.g., as an object name), which
454       // will produce the ambiguity, or will complain that it expected
455       // a type name.
456       Result.suppressDiagnostics();
457       return nullptr;
458     }
459 
460     // We found a type within the ambiguous lookup; diagnose the
461     // ambiguity and then return that type. This might be the right
462     // answer, or it might not be, but it suppresses any attempt to
463     // perform the name lookup again.
464     break;
465 
466   case LookupResult::Found:
467     IIDecl = Result.getFoundDecl();
468     break;
469   }
470 
471   assert(IIDecl && "Didn't find decl");
472 
473   QualType T;
474   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
475     // C++ [class.qual]p2: A lookup that would find the injected-class-name
476     // instead names the constructors of the class, except when naming a class.
477     // This is ill-formed when we're not actually forming a ctor or dtor name.
478     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
479     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
480     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
481         FoundRD->isInjectedClassName() &&
482         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
483       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
484           << &II << /*Type*/1;
485 
486     DiagnoseUseOfDecl(IIDecl, NameLoc);
487 
488     T = Context.getTypeDeclType(TD);
489     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
490   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
491     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
492     if (!HasTrailingDot)
493       T = Context.getObjCInterfaceType(IDecl);
494   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(UD, NameLoc);
496     // Recover with 'int'
497     T = Context.IntTy;
498   } else if (AllowDeducedTemplate) {
499     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
500       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
501                                                        QualType(), false);
502   }
503 
504   if (T.isNull()) {
505     // If it's not plausibly a type, suppress diagnostics.
506     Result.suppressDiagnostics();
507     return nullptr;
508   }
509 
510   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
511   // constructor or destructor name (in such a case, the scope specifier
512   // will be attached to the enclosing Expr or Decl node).
513   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
514       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
515     if (WantNontrivialTypeSourceInfo) {
516       // Construct a type with type-source information.
517       TypeLocBuilder Builder;
518       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
519 
520       T = getElaboratedType(ETK_None, *SS, T);
521       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
522       ElabTL.setElaboratedKeywordLoc(SourceLocation());
523       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
524       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
525     } else {
526       T = getElaboratedType(ETK_None, *SS, T);
527     }
528   }
529 
530   return ParsedType::make(T);
531 }
532 
533 // Builds a fake NNS for the given decl context.
534 static NestedNameSpecifier *
535 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
536   for (;; DC = DC->getLookupParent()) {
537     DC = DC->getPrimaryContext();
538     auto *ND = dyn_cast<NamespaceDecl>(DC);
539     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
540       return NestedNameSpecifier::Create(Context, nullptr, ND);
541     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
542       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
543                                          RD->getTypeForDecl());
544     else if (isa<TranslationUnitDecl>(DC))
545       return NestedNameSpecifier::GlobalSpecifier(Context);
546   }
547   llvm_unreachable("something isn't in TU scope?");
548 }
549 
550 /// Find the parent class with dependent bases of the innermost enclosing method
551 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
552 /// up allowing unqualified dependent type names at class-level, which MSVC
553 /// correctly rejects.
554 static const CXXRecordDecl *
555 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
556   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
557     DC = DC->getPrimaryContext();
558     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
559       if (MD->getParent()->hasAnyDependentBases())
560         return MD->getParent();
561   }
562   return nullptr;
563 }
564 
565 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
566                                           SourceLocation NameLoc,
567                                           bool IsTemplateTypeArg) {
568   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
569 
570   NestedNameSpecifier *NNS = nullptr;
571   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
572     // If we weren't able to parse a default template argument, delay lookup
573     // until instantiation time by making a non-dependent DependentTypeName. We
574     // pretend we saw a NestedNameSpecifier referring to the current scope, and
575     // lookup is retried.
576     // FIXME: This hurts our diagnostic quality, since we get errors like "no
577     // type named 'Foo' in 'current_namespace'" when the user didn't write any
578     // name specifiers.
579     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
580     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
581   } else if (const CXXRecordDecl *RD =
582                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
583     // Build a DependentNameType that will perform lookup into RD at
584     // instantiation time.
585     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
586                                       RD->getTypeForDecl());
587 
588     // Diagnose that this identifier was undeclared, and retry the lookup during
589     // template instantiation.
590     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
591                                                                       << RD;
592   } else {
593     // This is not a situation that we should recover from.
594     return ParsedType();
595   }
596 
597   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
598 
599   // Build type location information.  We synthesized the qualifier, so we have
600   // to build a fake NestedNameSpecifierLoc.
601   NestedNameSpecifierLocBuilder NNSLocBuilder;
602   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
603   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
604 
605   TypeLocBuilder Builder;
606   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
607   DepTL.setNameLoc(NameLoc);
608   DepTL.setElaboratedKeywordLoc(SourceLocation());
609   DepTL.setQualifierLoc(QualifierLoc);
610   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
611 }
612 
613 /// isTagName() - This method is called *for error recovery purposes only*
614 /// to determine if the specified name is a valid tag name ("struct foo").  If
615 /// so, this returns the TST for the tag corresponding to it (TST_enum,
616 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
617 /// cases in C where the user forgot to specify the tag.
618 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
619   // Do a tag name lookup in this scope.
620   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
621   LookupName(R, S, false);
622   R.suppressDiagnostics();
623   if (R.getResultKind() == LookupResult::Found)
624     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
625       switch (TD->getTagKind()) {
626       case TTK_Struct: return DeclSpec::TST_struct;
627       case TTK_Interface: return DeclSpec::TST_interface;
628       case TTK_Union:  return DeclSpec::TST_union;
629       case TTK_Class:  return DeclSpec::TST_class;
630       case TTK_Enum:   return DeclSpec::TST_enum;
631       }
632     }
633 
634   return DeclSpec::TST_unspecified;
635 }
636 
637 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
638 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
639 /// then downgrade the missing typename error to a warning.
640 /// This is needed for MSVC compatibility; Example:
641 /// @code
642 /// template<class T> class A {
643 /// public:
644 ///   typedef int TYPE;
645 /// };
646 /// template<class T> class B : public A<T> {
647 /// public:
648 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
649 /// };
650 /// @endcode
651 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
652   if (CurContext->isRecord()) {
653     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
654       return true;
655 
656     const Type *Ty = SS->getScopeRep()->getAsType();
657 
658     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
659     for (const auto &Base : RD->bases())
660       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
661         return true;
662     return S->isFunctionPrototypeScope();
663   }
664   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
665 }
666 
667 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
668                                    SourceLocation IILoc,
669                                    Scope *S,
670                                    CXXScopeSpec *SS,
671                                    ParsedType &SuggestedType,
672                                    bool IsTemplateName) {
673   // Don't report typename errors for editor placeholders.
674   if (II->isEditorPlaceholder())
675     return;
676   // We don't have anything to suggest (yet).
677   SuggestedType = nullptr;
678 
679   // There may have been a typo in the name of the type. Look up typo
680   // results, in case we have something that we can suggest.
681   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
682                            /*AllowTemplates=*/IsTemplateName,
683                            /*AllowNonTemplates=*/!IsTemplateName);
684   if (TypoCorrection Corrected =
685           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
686                       CCC, CTK_ErrorRecovery)) {
687     // FIXME: Support error recovery for the template-name case.
688     bool CanRecover = !IsTemplateName;
689     if (Corrected.isKeyword()) {
690       // We corrected to a keyword.
691       diagnoseTypo(Corrected,
692                    PDiag(IsTemplateName ? diag::err_no_template_suggest
693                                         : diag::err_unknown_typename_suggest)
694                        << II);
695       II = Corrected.getCorrectionAsIdentifierInfo();
696     } else {
697       // We found a similarly-named type or interface; suggest that.
698       if (!SS || !SS->isSet()) {
699         diagnoseTypo(Corrected,
700                      PDiag(IsTemplateName ? diag::err_no_template_suggest
701                                           : diag::err_unknown_typename_suggest)
702                          << II, CanRecover);
703       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
704         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
705         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
706                                 II->getName().equals(CorrectedStr);
707         diagnoseTypo(Corrected,
708                      PDiag(IsTemplateName
709                                ? diag::err_no_member_template_suggest
710                                : diag::err_unknown_nested_typename_suggest)
711                          << II << DC << DroppedSpecifier << SS->getRange(),
712                      CanRecover);
713       } else {
714         llvm_unreachable("could not have corrected a typo here");
715       }
716 
717       if (!CanRecover)
718         return;
719 
720       CXXScopeSpec tmpSS;
721       if (Corrected.getCorrectionSpecifier())
722         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
723                           SourceRange(IILoc));
724       // FIXME: Support class template argument deduction here.
725       SuggestedType =
726           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
727                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
728                       /*IsCtorOrDtorName=*/false,
729                       /*WantNontrivialTypeSourceInfo=*/true);
730     }
731     return;
732   }
733 
734   if (getLangOpts().CPlusPlus && !IsTemplateName) {
735     // See if II is a class template that the user forgot to pass arguments to.
736     UnqualifiedId Name;
737     Name.setIdentifier(II, IILoc);
738     CXXScopeSpec EmptySS;
739     TemplateTy TemplateResult;
740     bool MemberOfUnknownSpecialization;
741     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
742                        Name, nullptr, true, TemplateResult,
743                        MemberOfUnknownSpecialization) == TNK_Type_template) {
744       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
745       return;
746     }
747   }
748 
749   // FIXME: Should we move the logic that tries to recover from a missing tag
750   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
751 
752   if (!SS || (!SS->isSet() && !SS->isInvalid()))
753     Diag(IILoc, IsTemplateName ? diag::err_no_template
754                                : diag::err_unknown_typename)
755         << II;
756   else if (DeclContext *DC = computeDeclContext(*SS, false))
757     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
758                                : diag::err_typename_nested_not_found)
759         << II << DC << SS->getRange();
760   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
761     SuggestedType =
762         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
763   } else if (isDependentScopeSpecifier(*SS)) {
764     unsigned DiagID = diag::err_typename_missing;
765     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
766       DiagID = diag::ext_typename_missing;
767 
768     Diag(SS->getRange().getBegin(), DiagID)
769       << SS->getScopeRep() << II->getName()
770       << SourceRange(SS->getRange().getBegin(), IILoc)
771       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
772     SuggestedType = ActOnTypenameType(S, SourceLocation(),
773                                       *SS, *II, IILoc).get();
774   } else {
775     assert(SS && SS->isInvalid() &&
776            "Invalid scope specifier has already been diagnosed");
777   }
778 }
779 
780 /// Determine whether the given result set contains either a type name
781 /// or
782 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
783   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
784                        NextToken.is(tok::less);
785 
786   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
787     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
788       return true;
789 
790     if (CheckTemplate && isa<TemplateDecl>(*I))
791       return true;
792   }
793 
794   return false;
795 }
796 
797 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
798                                     Scope *S, CXXScopeSpec &SS,
799                                     IdentifierInfo *&Name,
800                                     SourceLocation NameLoc) {
801   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
802   SemaRef.LookupParsedName(R, S, &SS);
803   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
804     StringRef FixItTagName;
805     switch (Tag->getTagKind()) {
806       case TTK_Class:
807         FixItTagName = "class ";
808         break;
809 
810       case TTK_Enum:
811         FixItTagName = "enum ";
812         break;
813 
814       case TTK_Struct:
815         FixItTagName = "struct ";
816         break;
817 
818       case TTK_Interface:
819         FixItTagName = "__interface ";
820         break;
821 
822       case TTK_Union:
823         FixItTagName = "union ";
824         break;
825     }
826 
827     StringRef TagName = FixItTagName.drop_back();
828     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
829       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
830       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
831 
832     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
833          I != IEnd; ++I)
834       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
835         << Name << TagName;
836 
837     // Replace lookup results with just the tag decl.
838     Result.clear(Sema::LookupTagName);
839     SemaRef.LookupParsedName(Result, S, &SS);
840     return true;
841   }
842 
843   return false;
844 }
845 
846 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
847 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
848                                   QualType T, SourceLocation NameLoc) {
849   ASTContext &Context = S.Context;
850 
851   TypeLocBuilder Builder;
852   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
853 
854   T = S.getElaboratedType(ETK_None, SS, T);
855   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
856   ElabTL.setElaboratedKeywordLoc(SourceLocation());
857   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
858   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
859 }
860 
861 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
862                                             IdentifierInfo *&Name,
863                                             SourceLocation NameLoc,
864                                             const Token &NextToken,
865                                             CorrectionCandidateCallback *CCC) {
866   DeclarationNameInfo NameInfo(Name, NameLoc);
867   ObjCMethodDecl *CurMethod = getCurMethodDecl();
868 
869   assert(NextToken.isNot(tok::coloncolon) &&
870          "parse nested name specifiers before calling ClassifyName");
871   if (getLangOpts().CPlusPlus && SS.isSet() &&
872       isCurrentClassName(*Name, S, &SS)) {
873     // Per [class.qual]p2, this names the constructors of SS, not the
874     // injected-class-name. We don't have a classification for that.
875     // There's not much point caching this result, since the parser
876     // will reject it later.
877     return NameClassification::Unknown();
878   }
879 
880   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
881   LookupParsedName(Result, S, &SS, !CurMethod);
882 
883   if (SS.isInvalid())
884     return NameClassification::Error();
885 
886   // For unqualified lookup in a class template in MSVC mode, look into
887   // dependent base classes where the primary class template is known.
888   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
889     if (ParsedType TypeInBase =
890             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
891       return TypeInBase;
892   }
893 
894   // Perform lookup for Objective-C instance variables (including automatically
895   // synthesized instance variables), if we're in an Objective-C method.
896   // FIXME: This lookup really, really needs to be folded in to the normal
897   // unqualified lookup mechanism.
898   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
899     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
900     if (Ivar.isInvalid())
901       return NameClassification::Error();
902     if (Ivar.isUsable())
903       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
904 
905     // We defer builtin creation until after ivar lookup inside ObjC methods.
906     if (Result.empty())
907       LookupBuiltin(Result);
908   }
909 
910   bool SecondTry = false;
911   bool IsFilteredTemplateName = false;
912 
913 Corrected:
914   switch (Result.getResultKind()) {
915   case LookupResult::NotFound:
916     // If an unqualified-id is followed by a '(', then we have a function
917     // call.
918     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
919       // In C++, this is an ADL-only call.
920       // FIXME: Reference?
921       if (getLangOpts().CPlusPlus)
922         return NameClassification::UndeclaredNonType();
923 
924       // C90 6.3.2.2:
925       //   If the expression that precedes the parenthesized argument list in a
926       //   function call consists solely of an identifier, and if no
927       //   declaration is visible for this identifier, the identifier is
928       //   implicitly declared exactly as if, in the innermost block containing
929       //   the function call, the declaration
930       //
931       //     extern int identifier ();
932       //
933       //   appeared.
934       //
935       // We also allow this in C99 as an extension.
936       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
937         return NameClassification::NonType(D);
938     }
939 
940     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
941       // In C++20 onwards, this could be an ADL-only call to a function
942       // template, and we're required to assume that this is a template name.
943       //
944       // FIXME: Find a way to still do typo correction in this case.
945       TemplateName Template =
946           Context.getAssumedTemplateName(NameInfo.getName());
947       return NameClassification::UndeclaredTemplate(Template);
948     }
949 
950     // In C, we first see whether there is a tag type by the same name, in
951     // which case it's likely that the user just forgot to write "enum",
952     // "struct", or "union".
953     if (!getLangOpts().CPlusPlus && !SecondTry &&
954         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
955       break;
956     }
957 
958     // Perform typo correction to determine if there is another name that is
959     // close to this name.
960     if (!SecondTry && CCC) {
961       SecondTry = true;
962       if (TypoCorrection Corrected =
963               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
964                           &SS, *CCC, CTK_ErrorRecovery)) {
965         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
966         unsigned QualifiedDiag = diag::err_no_member_suggest;
967 
968         NamedDecl *FirstDecl = Corrected.getFoundDecl();
969         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
970         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
971             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
972           UnqualifiedDiag = diag::err_no_template_suggest;
973           QualifiedDiag = diag::err_no_member_template_suggest;
974         } else if (UnderlyingFirstDecl &&
975                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
976                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
977                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
978           UnqualifiedDiag = diag::err_unknown_typename_suggest;
979           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
980         }
981 
982         if (SS.isEmpty()) {
983           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
984         } else {// FIXME: is this even reachable? Test it.
985           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
986           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
987                                   Name->getName().equals(CorrectedStr);
988           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
989                                     << Name << computeDeclContext(SS, false)
990                                     << DroppedSpecifier << SS.getRange());
991         }
992 
993         // Update the name, so that the caller has the new name.
994         Name = Corrected.getCorrectionAsIdentifierInfo();
995 
996         // Typo correction corrected to a keyword.
997         if (Corrected.isKeyword())
998           return Name;
999 
1000         // Also update the LookupResult...
1001         // FIXME: This should probably go away at some point
1002         Result.clear();
1003         Result.setLookupName(Corrected.getCorrection());
1004         if (FirstDecl)
1005           Result.addDecl(FirstDecl);
1006 
1007         // If we found an Objective-C instance variable, let
1008         // LookupInObjCMethod build the appropriate expression to
1009         // reference the ivar.
1010         // FIXME: This is a gross hack.
1011         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1012           DeclResult R =
1013               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1014           if (R.isInvalid())
1015             return NameClassification::Error();
1016           if (R.isUsable())
1017             return NameClassification::NonType(Ivar);
1018         }
1019 
1020         goto Corrected;
1021       }
1022     }
1023 
1024     // We failed to correct; just fall through and let the parser deal with it.
1025     Result.suppressDiagnostics();
1026     return NameClassification::Unknown();
1027 
1028   case LookupResult::NotFoundInCurrentInstantiation: {
1029     // We performed name lookup into the current instantiation, and there were
1030     // dependent bases, so we treat this result the same way as any other
1031     // dependent nested-name-specifier.
1032 
1033     // C++ [temp.res]p2:
1034     //   A name used in a template declaration or definition and that is
1035     //   dependent on a template-parameter is assumed not to name a type
1036     //   unless the applicable name lookup finds a type name or the name is
1037     //   qualified by the keyword typename.
1038     //
1039     // FIXME: If the next token is '<', we might want to ask the parser to
1040     // perform some heroics to see if we actually have a
1041     // template-argument-list, which would indicate a missing 'template'
1042     // keyword here.
1043     return NameClassification::DependentNonType();
1044   }
1045 
1046   case LookupResult::Found:
1047   case LookupResult::FoundOverloaded:
1048   case LookupResult::FoundUnresolvedValue:
1049     break;
1050 
1051   case LookupResult::Ambiguous:
1052     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1053         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1054                                       /*AllowDependent=*/false)) {
1055       // C++ [temp.local]p3:
1056       //   A lookup that finds an injected-class-name (10.2) can result in an
1057       //   ambiguity in certain cases (for example, if it is found in more than
1058       //   one base class). If all of the injected-class-names that are found
1059       //   refer to specializations of the same class template, and if the name
1060       //   is followed by a template-argument-list, the reference refers to the
1061       //   class template itself and not a specialization thereof, and is not
1062       //   ambiguous.
1063       //
1064       // This filtering can make an ambiguous result into an unambiguous one,
1065       // so try again after filtering out template names.
1066       FilterAcceptableTemplateNames(Result);
1067       if (!Result.isAmbiguous()) {
1068         IsFilteredTemplateName = true;
1069         break;
1070       }
1071     }
1072 
1073     // Diagnose the ambiguity and return an error.
1074     return NameClassification::Error();
1075   }
1076 
1077   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1078       (IsFilteredTemplateName ||
1079        hasAnyAcceptableTemplateNames(
1080            Result, /*AllowFunctionTemplates=*/true,
1081            /*AllowDependent=*/false,
1082            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1083                getLangOpts().CPlusPlus20))) {
1084     // C++ [temp.names]p3:
1085     //   After name lookup (3.4) finds that a name is a template-name or that
1086     //   an operator-function-id or a literal- operator-id refers to a set of
1087     //   overloaded functions any member of which is a function template if
1088     //   this is followed by a <, the < is always taken as the delimiter of a
1089     //   template-argument-list and never as the less-than operator.
1090     // C++2a [temp.names]p2:
1091     //   A name is also considered to refer to a template if it is an
1092     //   unqualified-id followed by a < and name lookup finds either one
1093     //   or more functions or finds nothing.
1094     if (!IsFilteredTemplateName)
1095       FilterAcceptableTemplateNames(Result);
1096 
1097     bool IsFunctionTemplate;
1098     bool IsVarTemplate;
1099     TemplateName Template;
1100     if (Result.end() - Result.begin() > 1) {
1101       IsFunctionTemplate = true;
1102       Template = Context.getOverloadedTemplateName(Result.begin(),
1103                                                    Result.end());
1104     } else if (!Result.empty()) {
1105       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1106           *Result.begin(), /*AllowFunctionTemplates=*/true,
1107           /*AllowDependent=*/false));
1108       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1109       IsVarTemplate = isa<VarTemplateDecl>(TD);
1110 
1111       if (SS.isNotEmpty())
1112         Template =
1113             Context.getQualifiedTemplateName(SS.getScopeRep(),
1114                                              /*TemplateKeyword=*/false, TD);
1115       else
1116         Template = TemplateName(TD);
1117     } else {
1118       // All results were non-template functions. This is a function template
1119       // name.
1120       IsFunctionTemplate = true;
1121       Template = Context.getAssumedTemplateName(NameInfo.getName());
1122     }
1123 
1124     if (IsFunctionTemplate) {
1125       // Function templates always go through overload resolution, at which
1126       // point we'll perform the various checks (e.g., accessibility) we need
1127       // to based on which function we selected.
1128       Result.suppressDiagnostics();
1129 
1130       return NameClassification::FunctionTemplate(Template);
1131     }
1132 
1133     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1134                          : NameClassification::TypeTemplate(Template);
1135   }
1136 
1137   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1138   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1148   if (!Class) {
1149     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1150     if (ObjCCompatibleAliasDecl *Alias =
1151             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1152       Class = Alias->getClassInterface();
1153   }
1154 
1155   if (Class) {
1156     DiagnoseUseOfDecl(Class, NameLoc);
1157 
1158     if (NextToken.is(tok::period)) {
1159       // Interface. <something> is parsed as a property reference expression.
1160       // Just return "unknown" as a fall-through for now.
1161       Result.suppressDiagnostics();
1162       return NameClassification::Unknown();
1163     }
1164 
1165     QualType T = Context.getObjCInterfaceType(Class);
1166     return ParsedType::make(T);
1167   }
1168 
1169   if (isa<ConceptDecl>(FirstDecl))
1170     return NameClassification::Concept(
1171         TemplateName(cast<TemplateDecl>(FirstDecl)));
1172 
1173   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1174     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1175     return NameClassification::Error();
1176   }
1177 
1178   // We can have a type template here if we're classifying a template argument.
1179   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1180       !isa<VarTemplateDecl>(FirstDecl))
1181     return NameClassification::TypeTemplate(
1182         TemplateName(cast<TemplateDecl>(FirstDecl)));
1183 
1184   // Check for a tag type hidden by a non-type decl in a few cases where it
1185   // seems likely a type is wanted instead of the non-type that was found.
1186   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1187   if ((NextToken.is(tok::identifier) ||
1188        (NextIsOp &&
1189         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1190       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1191     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1192     DiagnoseUseOfDecl(Type, NameLoc);
1193     QualType T = Context.getTypeDeclType(Type);
1194     if (SS.isNotEmpty())
1195       return buildNestedType(*this, SS, T, NameLoc);
1196     return ParsedType::make(T);
1197   }
1198 
1199   // If we already know which single declaration is referenced, just annotate
1200   // that declaration directly. Defer resolving even non-overloaded class
1201   // member accesses, as we need to defer certain access checks until we know
1202   // the context.
1203   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1204   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1205     return NameClassification::NonType(Result.getRepresentativeDecl());
1206 
1207   // Otherwise, this is an overload set that we will need to resolve later.
1208   Result.suppressDiagnostics();
1209   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1210       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1211       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1212       Result.begin(), Result.end()));
1213 }
1214 
1215 ExprResult
1216 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1217                                              SourceLocation NameLoc) {
1218   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1219   CXXScopeSpec SS;
1220   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1221   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1226                                             IdentifierInfo *Name,
1227                                             SourceLocation NameLoc,
1228                                             bool IsAddressOfOperand) {
1229   DeclarationNameInfo NameInfo(Name, NameLoc);
1230   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1231                                     NameInfo, IsAddressOfOperand,
1232                                     /*TemplateArgs=*/nullptr);
1233 }
1234 
1235 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1236                                               NamedDecl *Found,
1237                                               SourceLocation NameLoc,
1238                                               const Token &NextToken) {
1239   if (getCurMethodDecl() && SS.isEmpty())
1240     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1241       return BuildIvarRefExpr(S, NameLoc, Ivar);
1242 
1243   // Reconstruct the lookup result.
1244   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1245   Result.addDecl(Found);
1246   Result.resolveKind();
1247 
1248   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1249   return BuildDeclarationNameExpr(SS, Result, ADL);
1250 }
1251 
1252 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1253   // For an implicit class member access, transform the result into a member
1254   // access expression if necessary.
1255   auto *ULE = cast<UnresolvedLookupExpr>(E);
1256   if ((*ULE->decls_begin())->isCXXClassMember()) {
1257     CXXScopeSpec SS;
1258     SS.Adopt(ULE->getQualifierLoc());
1259 
1260     // Reconstruct the lookup result.
1261     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1262                         LookupOrdinaryName);
1263     Result.setNamingClass(ULE->getNamingClass());
1264     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1265       Result.addDecl(*I, I.getAccess());
1266     Result.resolveKind();
1267     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1268                                            nullptr, S);
1269   }
1270 
1271   // Otherwise, this is already in the form we needed, and no further checks
1272   // are necessary.
1273   return ULE;
1274 }
1275 
1276 Sema::TemplateNameKindForDiagnostics
1277 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1278   auto *TD = Name.getAsTemplateDecl();
1279   if (!TD)
1280     return TemplateNameKindForDiagnostics::DependentTemplate;
1281   if (isa<ClassTemplateDecl>(TD))
1282     return TemplateNameKindForDiagnostics::ClassTemplate;
1283   if (isa<FunctionTemplateDecl>(TD))
1284     return TemplateNameKindForDiagnostics::FunctionTemplate;
1285   if (isa<VarTemplateDecl>(TD))
1286     return TemplateNameKindForDiagnostics::VarTemplate;
1287   if (isa<TypeAliasTemplateDecl>(TD))
1288     return TemplateNameKindForDiagnostics::AliasTemplate;
1289   if (isa<TemplateTemplateParmDecl>(TD))
1290     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1291   if (isa<ConceptDecl>(TD))
1292     return TemplateNameKindForDiagnostics::Concept;
1293   return TemplateNameKindForDiagnostics::DependentTemplate;
1294 }
1295 
1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1297   assert(DC->getLexicalParent() == CurContext &&
1298       "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = DC;
1300   S->setEntity(DC);
1301 }
1302 
1303 void Sema::PopDeclContext() {
1304   assert(CurContext && "DeclContext imbalance!");
1305 
1306   CurContext = CurContext->getLexicalParent();
1307   assert(CurContext && "Popped translation unit!");
1308 }
1309 
1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1311                                                                     Decl *D) {
1312   // Unlike PushDeclContext, the context to which we return is not necessarily
1313   // the containing DC of TD, because the new context will be some pre-existing
1314   // TagDecl definition instead of a fresh one.
1315   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1316   CurContext = cast<TagDecl>(D)->getDefinition();
1317   assert(CurContext && "skipping definition of undefined tag");
1318   // Start lookups from the parent of the current context; we don't want to look
1319   // into the pre-existing complete definition.
1320   S->setEntity(CurContext->getLookupParent());
1321   return Result;
1322 }
1323 
1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1325   CurContext = static_cast<decltype(CurContext)>(Context);
1326 }
1327 
1328 /// EnterDeclaratorContext - Used when we must lookup names in the context
1329 /// of a declarator's nested name specifier.
1330 ///
1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1332   // C++0x [basic.lookup.unqual]p13:
1333   //   A name used in the definition of a static data member of class
1334   //   X (after the qualified-id of the static member) is looked up as
1335   //   if the name was used in a member function of X.
1336   // C++0x [basic.lookup.unqual]p14:
1337   //   If a variable member of a namespace is defined outside of the
1338   //   scope of its namespace then any name used in the definition of
1339   //   the variable member (after the declarator-id) is looked up as
1340   //   if the definition of the variable member occurred in its
1341   //   namespace.
1342   // Both of these imply that we should push a scope whose context
1343   // is the semantic context of the declaration.  We can't use
1344   // PushDeclContext here because that context is not necessarily
1345   // lexically contained in the current context.  Fortunately,
1346   // the containing scope should have the appropriate information.
1347 
1348   assert(!S->getEntity() && "scope already has entity");
1349 
1350 #ifndef NDEBUG
1351   Scope *Ancestor = S->getParent();
1352   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1353   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1354 #endif
1355 
1356   CurContext = DC;
1357   S->setEntity(DC);
1358 
1359   if (S->getParent()->isTemplateParamScope()) {
1360     // Also set the corresponding entities for all immediately-enclosing
1361     // template parameter scopes.
1362     EnterTemplatedContext(S->getParent(), DC);
1363   }
1364 }
1365 
1366 void Sema::ExitDeclaratorContext(Scope *S) {
1367   assert(S->getEntity() == CurContext && "Context imbalance!");
1368 
1369   // Switch back to the lexical context.  The safety of this is
1370   // enforced by an assert in EnterDeclaratorContext.
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   CurContext = Ancestor->getEntity();
1374 
1375   // We don't need to do anything with the scope, which is going to
1376   // disappear.
1377 }
1378 
1379 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1380   assert(S->isTemplateParamScope() &&
1381          "expected to be initializing a template parameter scope");
1382 
1383   // C++20 [temp.local]p7:
1384   //   In the definition of a member of a class template that appears outside
1385   //   of the class template definition, the name of a member of the class
1386   //   template hides the name of a template-parameter of any enclosing class
1387   //   templates (but not a template-parameter of the member if the member is a
1388   //   class or function template).
1389   // C++20 [temp.local]p9:
1390   //   In the definition of a class template or in the definition of a member
1391   //   of such a template that appears outside of the template definition, for
1392   //   each non-dependent base class (13.8.2.1), if the name of the base class
1393   //   or the name of a member of the base class is the same as the name of a
1394   //   template-parameter, the base class name or member name hides the
1395   //   template-parameter name (6.4.10).
1396   //
1397   // This means that a template parameter scope should be searched immediately
1398   // after searching the DeclContext for which it is a template parameter
1399   // scope. For example, for
1400   //   template<typename T> template<typename U> template<typename V>
1401   //     void N::A<T>::B<U>::f(...)
1402   // we search V then B<U> (and base classes) then U then A<T> (and base
1403   // classes) then T then N then ::.
1404   unsigned ScopeDepth = getTemplateDepth(S);
1405   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1406     DeclContext *SearchDCAfterScope = DC;
1407     for (; DC; DC = DC->getLookupParent()) {
1408       if (const TemplateParameterList *TPL =
1409               cast<Decl>(DC)->getDescribedTemplateParams()) {
1410         unsigned DCDepth = TPL->getDepth() + 1;
1411         if (DCDepth > ScopeDepth)
1412           continue;
1413         if (ScopeDepth == DCDepth)
1414           SearchDCAfterScope = DC = DC->getLookupParent();
1415         break;
1416       }
1417     }
1418     S->setLookupEntity(SearchDCAfterScope);
1419   }
1420 }
1421 
1422 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1423   // We assume that the caller has already called
1424   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1425   FunctionDecl *FD = D->getAsFunction();
1426   if (!FD)
1427     return;
1428 
1429   // Same implementation as PushDeclContext, but enters the context
1430   // from the lexical parent, rather than the top-level class.
1431   assert(CurContext == FD->getLexicalParent() &&
1432     "The next DeclContext should be lexically contained in the current one.");
1433   CurContext = FD;
1434   S->setEntity(CurContext);
1435 
1436   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1437     ParmVarDecl *Param = FD->getParamDecl(P);
1438     // If the parameter has an identifier, then add it to the scope
1439     if (Param->getIdentifier()) {
1440       S->AddDecl(Param);
1441       IdResolver.AddDecl(Param);
1442     }
1443   }
1444 }
1445 
1446 void Sema::ActOnExitFunctionContext() {
1447   // Same implementation as PopDeclContext, but returns to the lexical parent,
1448   // rather than the top-level class.
1449   assert(CurContext && "DeclContext imbalance!");
1450   CurContext = CurContext->getLexicalParent();
1451   assert(CurContext && "Popped translation unit!");
1452 }
1453 
1454 /// Determine whether we allow overloading of the function
1455 /// PrevDecl with another declaration.
1456 ///
1457 /// This routine determines whether overloading is possible, not
1458 /// whether some new function is actually an overload. It will return
1459 /// true in C++ (where we can always provide overloads) or, as an
1460 /// extension, in C when the previous function is already an
1461 /// overloaded function declaration or has the "overloadable"
1462 /// attribute.
1463 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1464                                        ASTContext &Context,
1465                                        const FunctionDecl *New) {
1466   if (Context.getLangOpts().CPlusPlus)
1467     return true;
1468 
1469   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1470     return true;
1471 
1472   return Previous.getResultKind() == LookupResult::Found &&
1473          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1474           New->hasAttr<OverloadableAttr>());
1475 }
1476 
1477 /// Add this decl to the scope shadowed decl chains.
1478 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1479   // Move up the scope chain until we find the nearest enclosing
1480   // non-transparent context. The declaration will be introduced into this
1481   // scope.
1482   while (S->getEntity() && S->getEntity()->isTransparentContext())
1483     S = S->getParent();
1484 
1485   // Add scoped declarations into their context, so that they can be
1486   // found later. Declarations without a context won't be inserted
1487   // into any context.
1488   if (AddToContext)
1489     CurContext->addDecl(D);
1490 
1491   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1492   // are function-local declarations.
1493   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1494     return;
1495 
1496   // Template instantiations should also not be pushed into scope.
1497   if (isa<FunctionDecl>(D) &&
1498       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1499     return;
1500 
1501   // If this replaces anything in the current scope,
1502   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1503                                IEnd = IdResolver.end();
1504   for (; I != IEnd; ++I) {
1505     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1506       S->RemoveDecl(*I);
1507       IdResolver.RemoveDecl(*I);
1508 
1509       // Should only need to replace one decl.
1510       break;
1511     }
1512   }
1513 
1514   S->AddDecl(D);
1515 
1516   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1517     // Implicitly-generated labels may end up getting generated in an order that
1518     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1519     // the label at the appropriate place in the identifier chain.
1520     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1521       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1522       if (IDC == CurContext) {
1523         if (!S->isDeclScope(*I))
1524           continue;
1525       } else if (IDC->Encloses(CurContext))
1526         break;
1527     }
1528 
1529     IdResolver.InsertDeclAfter(I, D);
1530   } else {
1531     IdResolver.AddDecl(D);
1532   }
1533   warnOnReservedIdentifier(D);
1534 }
1535 
1536 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1537                          bool AllowInlineNamespace) {
1538   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1539 }
1540 
1541 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1542   DeclContext *TargetDC = DC->getPrimaryContext();
1543   do {
1544     if (DeclContext *ScopeDC = S->getEntity())
1545       if (ScopeDC->getPrimaryContext() == TargetDC)
1546         return S;
1547   } while ((S = S->getParent()));
1548 
1549   return nullptr;
1550 }
1551 
1552 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1553                                             DeclContext*,
1554                                             ASTContext&);
1555 
1556 /// Filters out lookup results that don't fall within the given scope
1557 /// as determined by isDeclInScope.
1558 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1559                                 bool ConsiderLinkage,
1560                                 bool AllowInlineNamespace) {
1561   LookupResult::Filter F = R.makeFilter();
1562   while (F.hasNext()) {
1563     NamedDecl *D = F.next();
1564 
1565     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1566       continue;
1567 
1568     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1569       continue;
1570 
1571     F.erase();
1572   }
1573 
1574   F.done();
1575 }
1576 
1577 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1578 /// have compatible owning modules.
1579 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1580   // FIXME: The Modules TS is not clear about how friend declarations are
1581   // to be treated. It's not meaningful to have different owning modules for
1582   // linkage in redeclarations of the same entity, so for now allow the
1583   // redeclaration and change the owning modules to match.
1584   if (New->getFriendObjectKind() &&
1585       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1586     New->setLocalOwningModule(Old->getOwningModule());
1587     makeMergedDefinitionVisible(New);
1588     return false;
1589   }
1590 
1591   Module *NewM = New->getOwningModule();
1592   Module *OldM = Old->getOwningModule();
1593 
1594   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1595     NewM = NewM->Parent;
1596   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1597     OldM = OldM->Parent;
1598 
1599   if (NewM == OldM)
1600     return false;
1601 
1602   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1603   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1604   if (NewIsModuleInterface || OldIsModuleInterface) {
1605     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1606     //   if a declaration of D [...] appears in the purview of a module, all
1607     //   other such declarations shall appear in the purview of the same module
1608     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1609       << New
1610       << NewIsModuleInterface
1611       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1612       << OldIsModuleInterface
1613       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1614     Diag(Old->getLocation(), diag::note_previous_declaration);
1615     New->setInvalidDecl();
1616     return true;
1617   }
1618 
1619   return false;
1620 }
1621 
1622 static bool isUsingDecl(NamedDecl *D) {
1623   return isa<UsingShadowDecl>(D) ||
1624          isa<UnresolvedUsingTypenameDecl>(D) ||
1625          isa<UnresolvedUsingValueDecl>(D);
1626 }
1627 
1628 /// Removes using shadow declarations from the lookup results.
1629 static void RemoveUsingDecls(LookupResult &R) {
1630   LookupResult::Filter F = R.makeFilter();
1631   while (F.hasNext())
1632     if (isUsingDecl(F.next()))
1633       F.erase();
1634 
1635   F.done();
1636 }
1637 
1638 /// Check for this common pattern:
1639 /// @code
1640 /// class S {
1641 ///   S(const S&); // DO NOT IMPLEMENT
1642 ///   void operator=(const S&); // DO NOT IMPLEMENT
1643 /// };
1644 /// @endcode
1645 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1646   // FIXME: Should check for private access too but access is set after we get
1647   // the decl here.
1648   if (D->doesThisDeclarationHaveABody())
1649     return false;
1650 
1651   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1652     return CD->isCopyConstructor();
1653   return D->isCopyAssignmentOperator();
1654 }
1655 
1656 // We need this to handle
1657 //
1658 // typedef struct {
1659 //   void *foo() { return 0; }
1660 // } A;
1661 //
1662 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1663 // for example. If 'A', foo will have external linkage. If we have '*A',
1664 // foo will have no linkage. Since we can't know until we get to the end
1665 // of the typedef, this function finds out if D might have non-external linkage.
1666 // Callers should verify at the end of the TU if it D has external linkage or
1667 // not.
1668 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1669   const DeclContext *DC = D->getDeclContext();
1670   while (!DC->isTranslationUnit()) {
1671     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1672       if (!RD->hasNameForLinkage())
1673         return true;
1674     }
1675     DC = DC->getParent();
1676   }
1677 
1678   return !D->isExternallyVisible();
1679 }
1680 
1681 // FIXME: This needs to be refactored; some other isInMainFile users want
1682 // these semantics.
1683 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1684   if (S.TUKind != TU_Complete)
1685     return false;
1686   return S.SourceMgr.isInMainFile(Loc);
1687 }
1688 
1689 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1690   assert(D);
1691 
1692   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1693     return false;
1694 
1695   // Ignore all entities declared within templates, and out-of-line definitions
1696   // of members of class templates.
1697   if (D->getDeclContext()->isDependentContext() ||
1698       D->getLexicalDeclContext()->isDependentContext())
1699     return false;
1700 
1701   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1702     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1703       return false;
1704     // A non-out-of-line declaration of a member specialization was implicitly
1705     // instantiated; it's the out-of-line declaration that we're interested in.
1706     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1707         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1708       return false;
1709 
1710     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1711       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1712         return false;
1713     } else {
1714       // 'static inline' functions are defined in headers; don't warn.
1715       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1716         return false;
1717     }
1718 
1719     if (FD->doesThisDeclarationHaveABody() &&
1720         Context.DeclMustBeEmitted(FD))
1721       return false;
1722   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1723     // Constants and utility variables are defined in headers with internal
1724     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1725     // like "inline".)
1726     if (!isMainFileLoc(*this, VD->getLocation()))
1727       return false;
1728 
1729     if (Context.DeclMustBeEmitted(VD))
1730       return false;
1731 
1732     if (VD->isStaticDataMember() &&
1733         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1734       return false;
1735     if (VD->isStaticDataMember() &&
1736         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1737         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1738       return false;
1739 
1740     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1741       return false;
1742   } else {
1743     return false;
1744   }
1745 
1746   // Only warn for unused decls internal to the translation unit.
1747   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1748   // for inline functions defined in the main source file, for instance.
1749   return mightHaveNonExternalLinkage(D);
1750 }
1751 
1752 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1753   if (!D)
1754     return;
1755 
1756   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1757     const FunctionDecl *First = FD->getFirstDecl();
1758     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1759       return; // First should already be in the vector.
1760   }
1761 
1762   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1763     const VarDecl *First = VD->getFirstDecl();
1764     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1765       return; // First should already be in the vector.
1766   }
1767 
1768   if (ShouldWarnIfUnusedFileScopedDecl(D))
1769     UnusedFileScopedDecls.push_back(D);
1770 }
1771 
1772 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1773   if (D->isInvalidDecl())
1774     return false;
1775 
1776   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1777     // For a decomposition declaration, warn if none of the bindings are
1778     // referenced, instead of if the variable itself is referenced (which
1779     // it is, by the bindings' expressions).
1780     for (auto *BD : DD->bindings())
1781       if (BD->isReferenced())
1782         return false;
1783   } else if (!D->getDeclName()) {
1784     return false;
1785   } else if (D->isReferenced() || D->isUsed()) {
1786     return false;
1787   }
1788 
1789   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1790     return false;
1791 
1792   if (isa<LabelDecl>(D))
1793     return true;
1794 
1795   // Except for labels, we only care about unused decls that are local to
1796   // functions.
1797   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1798   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1799     // For dependent types, the diagnostic is deferred.
1800     WithinFunction =
1801         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1802   if (!WithinFunction)
1803     return false;
1804 
1805   if (isa<TypedefNameDecl>(D))
1806     return true;
1807 
1808   // White-list anything that isn't a local variable.
1809   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1810     return false;
1811 
1812   // Types of valid local variables should be complete, so this should succeed.
1813   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1814 
1815     // White-list anything with an __attribute__((unused)) type.
1816     const auto *Ty = VD->getType().getTypePtr();
1817 
1818     // Only look at the outermost level of typedef.
1819     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1820       if (TT->getDecl()->hasAttr<UnusedAttr>())
1821         return false;
1822     }
1823 
1824     // If we failed to complete the type for some reason, or if the type is
1825     // dependent, don't diagnose the variable.
1826     if (Ty->isIncompleteType() || Ty->isDependentType())
1827       return false;
1828 
1829     // Look at the element type to ensure that the warning behaviour is
1830     // consistent for both scalars and arrays.
1831     Ty = Ty->getBaseElementTypeUnsafe();
1832 
1833     if (const TagType *TT = Ty->getAs<TagType>()) {
1834       const TagDecl *Tag = TT->getDecl();
1835       if (Tag->hasAttr<UnusedAttr>())
1836         return false;
1837 
1838       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1839         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1840           return false;
1841 
1842         if (const Expr *Init = VD->getInit()) {
1843           if (const ExprWithCleanups *Cleanups =
1844                   dyn_cast<ExprWithCleanups>(Init))
1845             Init = Cleanups->getSubExpr();
1846           const CXXConstructExpr *Construct =
1847             dyn_cast<CXXConstructExpr>(Init);
1848           if (Construct && !Construct->isElidable()) {
1849             CXXConstructorDecl *CD = Construct->getConstructor();
1850             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1851                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1852               return false;
1853           }
1854 
1855           // Suppress the warning if we don't know how this is constructed, and
1856           // it could possibly be non-trivial constructor.
1857           if (Init->isTypeDependent())
1858             for (const CXXConstructorDecl *Ctor : RD->ctors())
1859               if (!Ctor->isTrivial())
1860                 return false;
1861         }
1862       }
1863     }
1864 
1865     // TODO: __attribute__((unused)) templates?
1866   }
1867 
1868   return true;
1869 }
1870 
1871 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1872                                      FixItHint &Hint) {
1873   if (isa<LabelDecl>(D)) {
1874     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1875         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1876         true);
1877     if (AfterColon.isInvalid())
1878       return;
1879     Hint = FixItHint::CreateRemoval(
1880         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1881   }
1882 }
1883 
1884 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1885   if (D->getTypeForDecl()->isDependentType())
1886     return;
1887 
1888   for (auto *TmpD : D->decls()) {
1889     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1890       DiagnoseUnusedDecl(T);
1891     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1892       DiagnoseUnusedNestedTypedefs(R);
1893   }
1894 }
1895 
1896 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1897 /// unless they are marked attr(unused).
1898 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1899   if (!ShouldDiagnoseUnusedDecl(D))
1900     return;
1901 
1902   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1903     // typedefs can be referenced later on, so the diagnostics are emitted
1904     // at end-of-translation-unit.
1905     UnusedLocalTypedefNameCandidates.insert(TD);
1906     return;
1907   }
1908 
1909   FixItHint Hint;
1910   GenerateFixForUnusedDecl(D, Context, Hint);
1911 
1912   unsigned DiagID;
1913   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1914     DiagID = diag::warn_unused_exception_param;
1915   else if (isa<LabelDecl>(D))
1916     DiagID = diag::warn_unused_label;
1917   else
1918     DiagID = diag::warn_unused_variable;
1919 
1920   Diag(D->getLocation(), DiagID) << D << Hint;
1921 }
1922 
1923 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1924   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1925   // it's not really unused.
1926   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
1927       VD->hasAttr<CleanupAttr>())
1928     return;
1929 
1930   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1931 
1932   if (Ty->isReferenceType() || Ty->isDependentType())
1933     return;
1934 
1935   if (const TagType *TT = Ty->getAs<TagType>()) {
1936     const TagDecl *Tag = TT->getDecl();
1937     if (Tag->hasAttr<UnusedAttr>())
1938       return;
1939     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1940     // mimic gcc's behavior.
1941     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1942       if (!RD->hasAttr<WarnUnusedAttr>())
1943         return;
1944     }
1945   }
1946 
1947   // Don't warn about __block Objective-C pointer variables, as they might
1948   // be assigned in the block but not used elsewhere for the purpose of lifetime
1949   // extension.
1950   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
1951     return;
1952 
1953   auto iter = RefsMinusAssignments.find(VD);
1954   if (iter == RefsMinusAssignments.end())
1955     return;
1956 
1957   assert(iter->getSecond() >= 0 &&
1958          "Found a negative number of references to a VarDecl");
1959   if (iter->getSecond() != 0)
1960     return;
1961   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1962                                          : diag::warn_unused_but_set_variable;
1963   Diag(VD->getLocation(), DiagID) << VD;
1964 }
1965 
1966 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1967   // Verify that we have no forward references left.  If so, there was a goto
1968   // or address of a label taken, but no definition of it.  Label fwd
1969   // definitions are indicated with a null substmt which is also not a resolved
1970   // MS inline assembly label name.
1971   bool Diagnose = false;
1972   if (L->isMSAsmLabel())
1973     Diagnose = !L->isResolvedMSAsmLabel();
1974   else
1975     Diagnose = L->getStmt() == nullptr;
1976   if (Diagnose)
1977     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1978 }
1979 
1980 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1981   S->mergeNRVOIntoParent();
1982 
1983   if (S->decl_empty()) return;
1984   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1985          "Scope shouldn't contain decls!");
1986 
1987   for (auto *TmpD : S->decls()) {
1988     assert(TmpD && "This decl didn't get pushed??");
1989 
1990     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1991     NamedDecl *D = cast<NamedDecl>(TmpD);
1992 
1993     // Diagnose unused variables in this scope.
1994     if (!S->hasUnrecoverableErrorOccurred()) {
1995       DiagnoseUnusedDecl(D);
1996       if (const auto *RD = dyn_cast<RecordDecl>(D))
1997         DiagnoseUnusedNestedTypedefs(RD);
1998       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1999         DiagnoseUnusedButSetDecl(VD);
2000         RefsMinusAssignments.erase(VD);
2001       }
2002     }
2003 
2004     if (!D->getDeclName()) continue;
2005 
2006     // If this was a forward reference to a label, verify it was defined.
2007     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2008       CheckPoppedLabel(LD, *this);
2009 
2010     // Remove this name from our lexical scope, and warn on it if we haven't
2011     // already.
2012     IdResolver.RemoveDecl(D);
2013     auto ShadowI = ShadowingDecls.find(D);
2014     if (ShadowI != ShadowingDecls.end()) {
2015       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2016         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2017             << D << FD << FD->getParent();
2018         Diag(FD->getLocation(), diag::note_previous_declaration);
2019       }
2020       ShadowingDecls.erase(ShadowI);
2021     }
2022   }
2023 }
2024 
2025 /// Look for an Objective-C class in the translation unit.
2026 ///
2027 /// \param Id The name of the Objective-C class we're looking for. If
2028 /// typo-correction fixes this name, the Id will be updated
2029 /// to the fixed name.
2030 ///
2031 /// \param IdLoc The location of the name in the translation unit.
2032 ///
2033 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2034 /// if there is no class with the given name.
2035 ///
2036 /// \returns The declaration of the named Objective-C class, or NULL if the
2037 /// class could not be found.
2038 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2039                                               SourceLocation IdLoc,
2040                                               bool DoTypoCorrection) {
2041   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2042   // creation from this context.
2043   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2044 
2045   if (!IDecl && DoTypoCorrection) {
2046     // Perform typo correction at the given location, but only if we
2047     // find an Objective-C class name.
2048     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2049     if (TypoCorrection C =
2050             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2051                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2052       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2053       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2054       Id = IDecl->getIdentifier();
2055     }
2056   }
2057   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2058   // This routine must always return a class definition, if any.
2059   if (Def && Def->getDefinition())
2060       Def = Def->getDefinition();
2061   return Def;
2062 }
2063 
2064 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2065 /// from S, where a non-field would be declared. This routine copes
2066 /// with the difference between C and C++ scoping rules in structs and
2067 /// unions. For example, the following code is well-formed in C but
2068 /// ill-formed in C++:
2069 /// @code
2070 /// struct S6 {
2071 ///   enum { BAR } e;
2072 /// };
2073 ///
2074 /// void test_S6() {
2075 ///   struct S6 a;
2076 ///   a.e = BAR;
2077 /// }
2078 /// @endcode
2079 /// For the declaration of BAR, this routine will return a different
2080 /// scope. The scope S will be the scope of the unnamed enumeration
2081 /// within S6. In C++, this routine will return the scope associated
2082 /// with S6, because the enumeration's scope is a transparent
2083 /// context but structures can contain non-field names. In C, this
2084 /// routine will return the translation unit scope, since the
2085 /// enumeration's scope is a transparent context and structures cannot
2086 /// contain non-field names.
2087 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2088   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2089          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2090          (S->isClassScope() && !getLangOpts().CPlusPlus))
2091     S = S->getParent();
2092   return S;
2093 }
2094 
2095 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2096                                ASTContext::GetBuiltinTypeError Error) {
2097   switch (Error) {
2098   case ASTContext::GE_None:
2099     return "";
2100   case ASTContext::GE_Missing_type:
2101     return BuiltinInfo.getHeaderName(ID);
2102   case ASTContext::GE_Missing_stdio:
2103     return "stdio.h";
2104   case ASTContext::GE_Missing_setjmp:
2105     return "setjmp.h";
2106   case ASTContext::GE_Missing_ucontext:
2107     return "ucontext.h";
2108   }
2109   llvm_unreachable("unhandled error kind");
2110 }
2111 
2112 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2113                                   unsigned ID, SourceLocation Loc) {
2114   DeclContext *Parent = Context.getTranslationUnitDecl();
2115 
2116   if (getLangOpts().CPlusPlus) {
2117     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2118         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2119     CLinkageDecl->setImplicit();
2120     Parent->addDecl(CLinkageDecl);
2121     Parent = CLinkageDecl;
2122   }
2123 
2124   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2125                                            /*TInfo=*/nullptr, SC_Extern,
2126                                            getCurFPFeatures().isFPConstrained(),
2127                                            false, Type->isFunctionProtoType());
2128   New->setImplicit();
2129   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2130 
2131   // Create Decl objects for each parameter, adding them to the
2132   // FunctionDecl.
2133   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2134     SmallVector<ParmVarDecl *, 16> Params;
2135     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2136       ParmVarDecl *parm = ParmVarDecl::Create(
2137           Context, New, SourceLocation(), SourceLocation(), nullptr,
2138           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2139       parm->setScopeInfo(0, i);
2140       Params.push_back(parm);
2141     }
2142     New->setParams(Params);
2143   }
2144 
2145   AddKnownFunctionAttributes(New);
2146   return New;
2147 }
2148 
2149 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2150 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2151 /// if we're creating this built-in in anticipation of redeclaring the
2152 /// built-in.
2153 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2154                                      Scope *S, bool ForRedeclaration,
2155                                      SourceLocation Loc) {
2156   LookupNecessaryTypesForBuiltin(S, ID);
2157 
2158   ASTContext::GetBuiltinTypeError Error;
2159   QualType R = Context.GetBuiltinType(ID, Error);
2160   if (Error) {
2161     if (!ForRedeclaration)
2162       return nullptr;
2163 
2164     // If we have a builtin without an associated type we should not emit a
2165     // warning when we were not able to find a type for it.
2166     if (Error == ASTContext::GE_Missing_type ||
2167         Context.BuiltinInfo.allowTypeMismatch(ID))
2168       return nullptr;
2169 
2170     // If we could not find a type for setjmp it is because the jmp_buf type was
2171     // not defined prior to the setjmp declaration.
2172     if (Error == ASTContext::GE_Missing_setjmp) {
2173       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2174           << Context.BuiltinInfo.getName(ID);
2175       return nullptr;
2176     }
2177 
2178     // Generally, we emit a warning that the declaration requires the
2179     // appropriate header.
2180     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2181         << getHeaderName(Context.BuiltinInfo, ID, Error)
2182         << Context.BuiltinInfo.getName(ID);
2183     return nullptr;
2184   }
2185 
2186   if (!ForRedeclaration &&
2187       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2188        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2189     Diag(Loc, diag::ext_implicit_lib_function_decl)
2190         << Context.BuiltinInfo.getName(ID) << R;
2191     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2192       Diag(Loc, diag::note_include_header_or_declare)
2193           << Header << Context.BuiltinInfo.getName(ID);
2194   }
2195 
2196   if (R.isNull())
2197     return nullptr;
2198 
2199   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2200   RegisterLocallyScopedExternCDecl(New, S);
2201 
2202   // TUScope is the translation-unit scope to insert this function into.
2203   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2204   // relate Scopes to DeclContexts, and probably eliminate CurContext
2205   // entirely, but we're not there yet.
2206   DeclContext *SavedContext = CurContext;
2207   CurContext = New->getDeclContext();
2208   PushOnScopeChains(New, TUScope);
2209   CurContext = SavedContext;
2210   return New;
2211 }
2212 
2213 /// Typedef declarations don't have linkage, but they still denote the same
2214 /// entity if their types are the same.
2215 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2216 /// isSameEntity.
2217 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2218                                                      TypedefNameDecl *Decl,
2219                                                      LookupResult &Previous) {
2220   // This is only interesting when modules are enabled.
2221   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2222     return;
2223 
2224   // Empty sets are uninteresting.
2225   if (Previous.empty())
2226     return;
2227 
2228   LookupResult::Filter Filter = Previous.makeFilter();
2229   while (Filter.hasNext()) {
2230     NamedDecl *Old = Filter.next();
2231 
2232     // Non-hidden declarations are never ignored.
2233     if (S.isVisible(Old))
2234       continue;
2235 
2236     // Declarations of the same entity are not ignored, even if they have
2237     // different linkages.
2238     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2239       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2240                                 Decl->getUnderlyingType()))
2241         continue;
2242 
2243       // If both declarations give a tag declaration a typedef name for linkage
2244       // purposes, then they declare the same entity.
2245       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2246           Decl->getAnonDeclWithTypedefName())
2247         continue;
2248     }
2249 
2250     Filter.erase();
2251   }
2252 
2253   Filter.done();
2254 }
2255 
2256 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2257   QualType OldType;
2258   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2259     OldType = OldTypedef->getUnderlyingType();
2260   else
2261     OldType = Context.getTypeDeclType(Old);
2262   QualType NewType = New->getUnderlyingType();
2263 
2264   if (NewType->isVariablyModifiedType()) {
2265     // Must not redefine a typedef with a variably-modified type.
2266     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2267     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2268       << Kind << NewType;
2269     if (Old->getLocation().isValid())
2270       notePreviousDefinition(Old, New->getLocation());
2271     New->setInvalidDecl();
2272     return true;
2273   }
2274 
2275   if (OldType != NewType &&
2276       !OldType->isDependentType() &&
2277       !NewType->isDependentType() &&
2278       !Context.hasSameType(OldType, NewType)) {
2279     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2280     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2281       << Kind << NewType << OldType;
2282     if (Old->getLocation().isValid())
2283       notePreviousDefinition(Old, New->getLocation());
2284     New->setInvalidDecl();
2285     return true;
2286   }
2287   return false;
2288 }
2289 
2290 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2291 /// same name and scope as a previous declaration 'Old'.  Figure out
2292 /// how to resolve this situation, merging decls or emitting
2293 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2294 ///
2295 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2296                                 LookupResult &OldDecls) {
2297   // If the new decl is known invalid already, don't bother doing any
2298   // merging checks.
2299   if (New->isInvalidDecl()) return;
2300 
2301   // Allow multiple definitions for ObjC built-in typedefs.
2302   // FIXME: Verify the underlying types are equivalent!
2303   if (getLangOpts().ObjC) {
2304     const IdentifierInfo *TypeID = New->getIdentifier();
2305     switch (TypeID->getLength()) {
2306     default: break;
2307     case 2:
2308       {
2309         if (!TypeID->isStr("id"))
2310           break;
2311         QualType T = New->getUnderlyingType();
2312         if (!T->isPointerType())
2313           break;
2314         if (!T->isVoidPointerType()) {
2315           QualType PT = T->castAs<PointerType>()->getPointeeType();
2316           if (!PT->isStructureType())
2317             break;
2318         }
2319         Context.setObjCIdRedefinitionType(T);
2320         // Install the built-in type for 'id', ignoring the current definition.
2321         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2322         return;
2323       }
2324     case 5:
2325       if (!TypeID->isStr("Class"))
2326         break;
2327       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2328       // Install the built-in type for 'Class', ignoring the current definition.
2329       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2330       return;
2331     case 3:
2332       if (!TypeID->isStr("SEL"))
2333         break;
2334       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2335       // Install the built-in type for 'SEL', ignoring the current definition.
2336       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2337       return;
2338     }
2339     // Fall through - the typedef name was not a builtin type.
2340   }
2341 
2342   // Verify the old decl was also a type.
2343   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2344   if (!Old) {
2345     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2346       << New->getDeclName();
2347 
2348     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2349     if (OldD->getLocation().isValid())
2350       notePreviousDefinition(OldD, New->getLocation());
2351 
2352     return New->setInvalidDecl();
2353   }
2354 
2355   // If the old declaration is invalid, just give up here.
2356   if (Old->isInvalidDecl())
2357     return New->setInvalidDecl();
2358 
2359   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2360     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2361     auto *NewTag = New->getAnonDeclWithTypedefName();
2362     NamedDecl *Hidden = nullptr;
2363     if (OldTag && NewTag &&
2364         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2365         !hasVisibleDefinition(OldTag, &Hidden)) {
2366       // There is a definition of this tag, but it is not visible. Use it
2367       // instead of our tag.
2368       New->setTypeForDecl(OldTD->getTypeForDecl());
2369       if (OldTD->isModed())
2370         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2371                                     OldTD->getUnderlyingType());
2372       else
2373         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2374 
2375       // Make the old tag definition visible.
2376       makeMergedDefinitionVisible(Hidden);
2377 
2378       // If this was an unscoped enumeration, yank all of its enumerators
2379       // out of the scope.
2380       if (isa<EnumDecl>(NewTag)) {
2381         Scope *EnumScope = getNonFieldDeclScope(S);
2382         for (auto *D : NewTag->decls()) {
2383           auto *ED = cast<EnumConstantDecl>(D);
2384           assert(EnumScope->isDeclScope(ED));
2385           EnumScope->RemoveDecl(ED);
2386           IdResolver.RemoveDecl(ED);
2387           ED->getLexicalDeclContext()->removeDecl(ED);
2388         }
2389       }
2390     }
2391   }
2392 
2393   // If the typedef types are not identical, reject them in all languages and
2394   // with any extensions enabled.
2395   if (isIncompatibleTypedef(Old, New))
2396     return;
2397 
2398   // The types match.  Link up the redeclaration chain and merge attributes if
2399   // the old declaration was a typedef.
2400   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2401     New->setPreviousDecl(Typedef);
2402     mergeDeclAttributes(New, Old);
2403   }
2404 
2405   if (getLangOpts().MicrosoftExt)
2406     return;
2407 
2408   if (getLangOpts().CPlusPlus) {
2409     // C++ [dcl.typedef]p2:
2410     //   In a given non-class scope, a typedef specifier can be used to
2411     //   redefine the name of any type declared in that scope to refer
2412     //   to the type to which it already refers.
2413     if (!isa<CXXRecordDecl>(CurContext))
2414       return;
2415 
2416     // C++0x [dcl.typedef]p4:
2417     //   In a given class scope, a typedef specifier can be used to redefine
2418     //   any class-name declared in that scope that is not also a typedef-name
2419     //   to refer to the type to which it already refers.
2420     //
2421     // This wording came in via DR424, which was a correction to the
2422     // wording in DR56, which accidentally banned code like:
2423     //
2424     //   struct S {
2425     //     typedef struct A { } A;
2426     //   };
2427     //
2428     // in the C++03 standard. We implement the C++0x semantics, which
2429     // allow the above but disallow
2430     //
2431     //   struct S {
2432     //     typedef int I;
2433     //     typedef int I;
2434     //   };
2435     //
2436     // since that was the intent of DR56.
2437     if (!isa<TypedefNameDecl>(Old))
2438       return;
2439 
2440     Diag(New->getLocation(), diag::err_redefinition)
2441       << New->getDeclName();
2442     notePreviousDefinition(Old, New->getLocation());
2443     return New->setInvalidDecl();
2444   }
2445 
2446   // Modules always permit redefinition of typedefs, as does C11.
2447   if (getLangOpts().Modules || getLangOpts().C11)
2448     return;
2449 
2450   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2451   // is normally mapped to an error, but can be controlled with
2452   // -Wtypedef-redefinition.  If either the original or the redefinition is
2453   // in a system header, don't emit this for compatibility with GCC.
2454   if (getDiagnostics().getSuppressSystemWarnings() &&
2455       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2456       (Old->isImplicit() ||
2457        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2458        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2459     return;
2460 
2461   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2462     << New->getDeclName();
2463   notePreviousDefinition(Old, New->getLocation());
2464 }
2465 
2466 /// DeclhasAttr - returns true if decl Declaration already has the target
2467 /// attribute.
2468 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2469   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2470   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2471   for (const auto *i : D->attrs())
2472     if (i->getKind() == A->getKind()) {
2473       if (Ann) {
2474         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2475           return true;
2476         continue;
2477       }
2478       // FIXME: Don't hardcode this check
2479       if (OA && isa<OwnershipAttr>(i))
2480         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2481       return true;
2482     }
2483 
2484   return false;
2485 }
2486 
2487 static bool isAttributeTargetADefinition(Decl *D) {
2488   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2489     return VD->isThisDeclarationADefinition();
2490   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2491     return TD->isCompleteDefinition() || TD->isBeingDefined();
2492   return true;
2493 }
2494 
2495 /// Merge alignment attributes from \p Old to \p New, taking into account the
2496 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2497 ///
2498 /// \return \c true if any attributes were added to \p New.
2499 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2500   // Look for alignas attributes on Old, and pick out whichever attribute
2501   // specifies the strictest alignment requirement.
2502   AlignedAttr *OldAlignasAttr = nullptr;
2503   AlignedAttr *OldStrictestAlignAttr = nullptr;
2504   unsigned OldAlign = 0;
2505   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2506     // FIXME: We have no way of representing inherited dependent alignments
2507     // in a case like:
2508     //   template<int A, int B> struct alignas(A) X;
2509     //   template<int A, int B> struct alignas(B) X {};
2510     // For now, we just ignore any alignas attributes which are not on the
2511     // definition in such a case.
2512     if (I->isAlignmentDependent())
2513       return false;
2514 
2515     if (I->isAlignas())
2516       OldAlignasAttr = I;
2517 
2518     unsigned Align = I->getAlignment(S.Context);
2519     if (Align > OldAlign) {
2520       OldAlign = Align;
2521       OldStrictestAlignAttr = I;
2522     }
2523   }
2524 
2525   // Look for alignas attributes on New.
2526   AlignedAttr *NewAlignasAttr = nullptr;
2527   unsigned NewAlign = 0;
2528   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2529     if (I->isAlignmentDependent())
2530       return false;
2531 
2532     if (I->isAlignas())
2533       NewAlignasAttr = I;
2534 
2535     unsigned Align = I->getAlignment(S.Context);
2536     if (Align > NewAlign)
2537       NewAlign = Align;
2538   }
2539 
2540   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2541     // Both declarations have 'alignas' attributes. We require them to match.
2542     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2543     // fall short. (If two declarations both have alignas, they must both match
2544     // every definition, and so must match each other if there is a definition.)
2545 
2546     // If either declaration only contains 'alignas(0)' specifiers, then it
2547     // specifies the natural alignment for the type.
2548     if (OldAlign == 0 || NewAlign == 0) {
2549       QualType Ty;
2550       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2551         Ty = VD->getType();
2552       else
2553         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2554 
2555       if (OldAlign == 0)
2556         OldAlign = S.Context.getTypeAlign(Ty);
2557       if (NewAlign == 0)
2558         NewAlign = S.Context.getTypeAlign(Ty);
2559     }
2560 
2561     if (OldAlign != NewAlign) {
2562       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2563         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2564         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2565       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2566     }
2567   }
2568 
2569   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2570     // C++11 [dcl.align]p6:
2571     //   if any declaration of an entity has an alignment-specifier,
2572     //   every defining declaration of that entity shall specify an
2573     //   equivalent alignment.
2574     // C11 6.7.5/7:
2575     //   If the definition of an object does not have an alignment
2576     //   specifier, any other declaration of that object shall also
2577     //   have no alignment specifier.
2578     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2579       << OldAlignasAttr;
2580     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2581       << OldAlignasAttr;
2582   }
2583 
2584   bool AnyAdded = false;
2585 
2586   // Ensure we have an attribute representing the strictest alignment.
2587   if (OldAlign > NewAlign) {
2588     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2589     Clone->setInherited(true);
2590     New->addAttr(Clone);
2591     AnyAdded = true;
2592   }
2593 
2594   // Ensure we have an alignas attribute if the old declaration had one.
2595   if (OldAlignasAttr && !NewAlignasAttr &&
2596       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2597     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2598     Clone->setInherited(true);
2599     New->addAttr(Clone);
2600     AnyAdded = true;
2601   }
2602 
2603   return AnyAdded;
2604 }
2605 
2606 #define WANT_DECL_MERGE_LOGIC
2607 #include "clang/Sema/AttrParsedAttrImpl.inc"
2608 #undef WANT_DECL_MERGE_LOGIC
2609 
2610 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2611                                const InheritableAttr *Attr,
2612                                Sema::AvailabilityMergeKind AMK) {
2613   // Diagnose any mutual exclusions between the attribute that we want to add
2614   // and attributes that already exist on the declaration.
2615   if (!DiagnoseMutualExclusions(S, D, Attr))
2616     return false;
2617 
2618   // This function copies an attribute Attr from a previous declaration to the
2619   // new declaration D if the new declaration doesn't itself have that attribute
2620   // yet or if that attribute allows duplicates.
2621   // If you're adding a new attribute that requires logic different from
2622   // "use explicit attribute on decl if present, else use attribute from
2623   // previous decl", for example if the attribute needs to be consistent
2624   // between redeclarations, you need to call a custom merge function here.
2625   InheritableAttr *NewAttr = nullptr;
2626   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2627     NewAttr = S.mergeAvailabilityAttr(
2628         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2629         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2630         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2631         AA->getPriority());
2632   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2633     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2634   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2635     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2636   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2637     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2638   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2639     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2640   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2641     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2642   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2643     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2644                                 FA->getFirstArg());
2645   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2646     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2647   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2648     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2649   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2650     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2651                                        IA->getInheritanceModel());
2652   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2653     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2654                                       &S.Context.Idents.get(AA->getSpelling()));
2655   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2656            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2657             isa<CUDAGlobalAttr>(Attr))) {
2658     // CUDA target attributes are part of function signature for
2659     // overloading purposes and must not be merged.
2660     return false;
2661   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2662     NewAttr = S.mergeMinSizeAttr(D, *MA);
2663   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2664     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2665   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2666     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2667   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2668     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2669   else if (isa<AlignedAttr>(Attr))
2670     // AlignedAttrs are handled separately, because we need to handle all
2671     // such attributes on a declaration at the same time.
2672     NewAttr = nullptr;
2673   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2674            (AMK == Sema::AMK_Override ||
2675             AMK == Sema::AMK_ProtocolImplementation ||
2676             AMK == Sema::AMK_OptionalProtocolImplementation))
2677     NewAttr = nullptr;
2678   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2679     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2680   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2681     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2682   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2683     NewAttr = S.mergeImportNameAttr(D, *INA);
2684   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2685     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2686   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2687     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2688   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2689     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2690   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2691     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2692 
2693   if (NewAttr) {
2694     NewAttr->setInherited(true);
2695     D->addAttr(NewAttr);
2696     if (isa<MSInheritanceAttr>(NewAttr))
2697       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2698     return true;
2699   }
2700 
2701   return false;
2702 }
2703 
2704 static const NamedDecl *getDefinition(const Decl *D) {
2705   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2706     return TD->getDefinition();
2707   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2708     const VarDecl *Def = VD->getDefinition();
2709     if (Def)
2710       return Def;
2711     return VD->getActingDefinition();
2712   }
2713   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2714     const FunctionDecl *Def = nullptr;
2715     if (FD->isDefined(Def, true))
2716       return Def;
2717   }
2718   return nullptr;
2719 }
2720 
2721 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2722   for (const auto *Attribute : D->attrs())
2723     if (Attribute->getKind() == Kind)
2724       return true;
2725   return false;
2726 }
2727 
2728 /// checkNewAttributesAfterDef - If we already have a definition, check that
2729 /// there are no new attributes in this declaration.
2730 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2731   if (!New->hasAttrs())
2732     return;
2733 
2734   const NamedDecl *Def = getDefinition(Old);
2735   if (!Def || Def == New)
2736     return;
2737 
2738   AttrVec &NewAttributes = New->getAttrs();
2739   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2740     const Attr *NewAttribute = NewAttributes[I];
2741 
2742     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2743       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2744         Sema::SkipBodyInfo SkipBody;
2745         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2746 
2747         // If we're skipping this definition, drop the "alias" attribute.
2748         if (SkipBody.ShouldSkip) {
2749           NewAttributes.erase(NewAttributes.begin() + I);
2750           --E;
2751           continue;
2752         }
2753       } else {
2754         VarDecl *VD = cast<VarDecl>(New);
2755         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2756                                 VarDecl::TentativeDefinition
2757                             ? diag::err_alias_after_tentative
2758                             : diag::err_redefinition;
2759         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2760         if (Diag == diag::err_redefinition)
2761           S.notePreviousDefinition(Def, VD->getLocation());
2762         else
2763           S.Diag(Def->getLocation(), diag::note_previous_definition);
2764         VD->setInvalidDecl();
2765       }
2766       ++I;
2767       continue;
2768     }
2769 
2770     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2771       // Tentative definitions are only interesting for the alias check above.
2772       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2773         ++I;
2774         continue;
2775       }
2776     }
2777 
2778     if (hasAttribute(Def, NewAttribute->getKind())) {
2779       ++I;
2780       continue; // regular attr merging will take care of validating this.
2781     }
2782 
2783     if (isa<C11NoReturnAttr>(NewAttribute)) {
2784       // C's _Noreturn is allowed to be added to a function after it is defined.
2785       ++I;
2786       continue;
2787     } else if (isa<UuidAttr>(NewAttribute)) {
2788       // msvc will allow a subsequent definition to add an uuid to a class
2789       ++I;
2790       continue;
2791     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2792       if (AA->isAlignas()) {
2793         // C++11 [dcl.align]p6:
2794         //   if any declaration of an entity has an alignment-specifier,
2795         //   every defining declaration of that entity shall specify an
2796         //   equivalent alignment.
2797         // C11 6.7.5/7:
2798         //   If the definition of an object does not have an alignment
2799         //   specifier, any other declaration of that object shall also
2800         //   have no alignment specifier.
2801         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2802           << AA;
2803         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2804           << AA;
2805         NewAttributes.erase(NewAttributes.begin() + I);
2806         --E;
2807         continue;
2808       }
2809     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2810       // If there is a C definition followed by a redeclaration with this
2811       // attribute then there are two different definitions. In C++, prefer the
2812       // standard diagnostics.
2813       if (!S.getLangOpts().CPlusPlus) {
2814         S.Diag(NewAttribute->getLocation(),
2815                diag::err_loader_uninitialized_redeclaration);
2816         S.Diag(Def->getLocation(), diag::note_previous_definition);
2817         NewAttributes.erase(NewAttributes.begin() + I);
2818         --E;
2819         continue;
2820       }
2821     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2822                cast<VarDecl>(New)->isInline() &&
2823                !cast<VarDecl>(New)->isInlineSpecified()) {
2824       // Don't warn about applying selectany to implicitly inline variables.
2825       // Older compilers and language modes would require the use of selectany
2826       // to make such variables inline, and it would have no effect if we
2827       // honored it.
2828       ++I;
2829       continue;
2830     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2831       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2832       // declarations after defintions.
2833       ++I;
2834       continue;
2835     }
2836 
2837     S.Diag(NewAttribute->getLocation(),
2838            diag::warn_attribute_precede_definition);
2839     S.Diag(Def->getLocation(), diag::note_previous_definition);
2840     NewAttributes.erase(NewAttributes.begin() + I);
2841     --E;
2842   }
2843 }
2844 
2845 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2846                                      const ConstInitAttr *CIAttr,
2847                                      bool AttrBeforeInit) {
2848   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2849 
2850   // Figure out a good way to write this specifier on the old declaration.
2851   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2852   // enough of the attribute list spelling information to extract that without
2853   // heroics.
2854   std::string SuitableSpelling;
2855   if (S.getLangOpts().CPlusPlus20)
2856     SuitableSpelling = std::string(
2857         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2858   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2859     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2860         InsertLoc, {tok::l_square, tok::l_square,
2861                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2862                     S.PP.getIdentifierInfo("require_constant_initialization"),
2863                     tok::r_square, tok::r_square}));
2864   if (SuitableSpelling.empty())
2865     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2866         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2867                     S.PP.getIdentifierInfo("require_constant_initialization"),
2868                     tok::r_paren, tok::r_paren}));
2869   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2870     SuitableSpelling = "constinit";
2871   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2872     SuitableSpelling = "[[clang::require_constant_initialization]]";
2873   if (SuitableSpelling.empty())
2874     SuitableSpelling = "__attribute__((require_constant_initialization))";
2875   SuitableSpelling += " ";
2876 
2877   if (AttrBeforeInit) {
2878     // extern constinit int a;
2879     // int a = 0; // error (missing 'constinit'), accepted as extension
2880     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2881     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2882         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2883     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2884   } else {
2885     // int a = 0;
2886     // constinit extern int a; // error (missing 'constinit')
2887     S.Diag(CIAttr->getLocation(),
2888            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2889                                  : diag::warn_require_const_init_added_too_late)
2890         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2891     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2892         << CIAttr->isConstinit()
2893         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2894   }
2895 }
2896 
2897 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2898 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2899                                AvailabilityMergeKind AMK) {
2900   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2901     UsedAttr *NewAttr = OldAttr->clone(Context);
2902     NewAttr->setInherited(true);
2903     New->addAttr(NewAttr);
2904   }
2905   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2906     RetainAttr *NewAttr = OldAttr->clone(Context);
2907     NewAttr->setInherited(true);
2908     New->addAttr(NewAttr);
2909   }
2910 
2911   if (!Old->hasAttrs() && !New->hasAttrs())
2912     return;
2913 
2914   // [dcl.constinit]p1:
2915   //   If the [constinit] specifier is applied to any declaration of a
2916   //   variable, it shall be applied to the initializing declaration.
2917   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2918   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2919   if (bool(OldConstInit) != bool(NewConstInit)) {
2920     const auto *OldVD = cast<VarDecl>(Old);
2921     auto *NewVD = cast<VarDecl>(New);
2922 
2923     // Find the initializing declaration. Note that we might not have linked
2924     // the new declaration into the redeclaration chain yet.
2925     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2926     if (!InitDecl &&
2927         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2928       InitDecl = NewVD;
2929 
2930     if (InitDecl == NewVD) {
2931       // This is the initializing declaration. If it would inherit 'constinit',
2932       // that's ill-formed. (Note that we do not apply this to the attribute
2933       // form).
2934       if (OldConstInit && OldConstInit->isConstinit())
2935         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2936                                  /*AttrBeforeInit=*/true);
2937     } else if (NewConstInit) {
2938       // This is the first time we've been told that this declaration should
2939       // have a constant initializer. If we already saw the initializing
2940       // declaration, this is too late.
2941       if (InitDecl && InitDecl != NewVD) {
2942         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2943                                  /*AttrBeforeInit=*/false);
2944         NewVD->dropAttr<ConstInitAttr>();
2945       }
2946     }
2947   }
2948 
2949   // Attributes declared post-definition are currently ignored.
2950   checkNewAttributesAfterDef(*this, New, Old);
2951 
2952   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2953     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2954       if (!OldA->isEquivalent(NewA)) {
2955         // This redeclaration changes __asm__ label.
2956         Diag(New->getLocation(), diag::err_different_asm_label);
2957         Diag(OldA->getLocation(), diag::note_previous_declaration);
2958       }
2959     } else if (Old->isUsed()) {
2960       // This redeclaration adds an __asm__ label to a declaration that has
2961       // already been ODR-used.
2962       Diag(New->getLocation(), diag::err_late_asm_label_name)
2963         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2964     }
2965   }
2966 
2967   // Re-declaration cannot add abi_tag's.
2968   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2969     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2970       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2971         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
2972           Diag(NewAbiTagAttr->getLocation(),
2973                diag::err_new_abi_tag_on_redeclaration)
2974               << NewTag;
2975           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2976         }
2977       }
2978     } else {
2979       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2980       Diag(Old->getLocation(), diag::note_previous_declaration);
2981     }
2982   }
2983 
2984   // This redeclaration adds a section attribute.
2985   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2986     if (auto *VD = dyn_cast<VarDecl>(New)) {
2987       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2988         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2989         Diag(Old->getLocation(), diag::note_previous_declaration);
2990       }
2991     }
2992   }
2993 
2994   // Redeclaration adds code-seg attribute.
2995   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2996   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2997       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2998     Diag(New->getLocation(), diag::warn_mismatched_section)
2999          << 0 /*codeseg*/;
3000     Diag(Old->getLocation(), diag::note_previous_declaration);
3001   }
3002 
3003   if (!Old->hasAttrs())
3004     return;
3005 
3006   bool foundAny = New->hasAttrs();
3007 
3008   // Ensure that any moving of objects within the allocated map is done before
3009   // we process them.
3010   if (!foundAny) New->setAttrs(AttrVec());
3011 
3012   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3013     // Ignore deprecated/unavailable/availability attributes if requested.
3014     AvailabilityMergeKind LocalAMK = AMK_None;
3015     if (isa<DeprecatedAttr>(I) ||
3016         isa<UnavailableAttr>(I) ||
3017         isa<AvailabilityAttr>(I)) {
3018       switch (AMK) {
3019       case AMK_None:
3020         continue;
3021 
3022       case AMK_Redeclaration:
3023       case AMK_Override:
3024       case AMK_ProtocolImplementation:
3025       case AMK_OptionalProtocolImplementation:
3026         LocalAMK = AMK;
3027         break;
3028       }
3029     }
3030 
3031     // Already handled.
3032     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3033       continue;
3034 
3035     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3036       foundAny = true;
3037   }
3038 
3039   if (mergeAlignedAttrs(*this, New, Old))
3040     foundAny = true;
3041 
3042   if (!foundAny) New->dropAttrs();
3043 }
3044 
3045 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3046 /// to the new one.
3047 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3048                                      const ParmVarDecl *oldDecl,
3049                                      Sema &S) {
3050   // C++11 [dcl.attr.depend]p2:
3051   //   The first declaration of a function shall specify the
3052   //   carries_dependency attribute for its declarator-id if any declaration
3053   //   of the function specifies the carries_dependency attribute.
3054   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3055   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3056     S.Diag(CDA->getLocation(),
3057            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3058     // Find the first declaration of the parameter.
3059     // FIXME: Should we build redeclaration chains for function parameters?
3060     const FunctionDecl *FirstFD =
3061       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3062     const ParmVarDecl *FirstVD =
3063       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3064     S.Diag(FirstVD->getLocation(),
3065            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3066   }
3067 
3068   if (!oldDecl->hasAttrs())
3069     return;
3070 
3071   bool foundAny = newDecl->hasAttrs();
3072 
3073   // Ensure that any moving of objects within the allocated map is
3074   // done before we process them.
3075   if (!foundAny) newDecl->setAttrs(AttrVec());
3076 
3077   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3078     if (!DeclHasAttr(newDecl, I)) {
3079       InheritableAttr *newAttr =
3080         cast<InheritableParamAttr>(I->clone(S.Context));
3081       newAttr->setInherited(true);
3082       newDecl->addAttr(newAttr);
3083       foundAny = true;
3084     }
3085   }
3086 
3087   if (!foundAny) newDecl->dropAttrs();
3088 }
3089 
3090 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3091                                 const ParmVarDecl *OldParam,
3092                                 Sema &S) {
3093   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3094     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3095       if (*Oldnullability != *Newnullability) {
3096         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3097           << DiagNullabilityKind(
3098                *Newnullability,
3099                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3100                 != 0))
3101           << DiagNullabilityKind(
3102                *Oldnullability,
3103                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3104                 != 0));
3105         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3106       }
3107     } else {
3108       QualType NewT = NewParam->getType();
3109       NewT = S.Context.getAttributedType(
3110                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3111                          NewT, NewT);
3112       NewParam->setType(NewT);
3113     }
3114   }
3115 }
3116 
3117 namespace {
3118 
3119 /// Used in MergeFunctionDecl to keep track of function parameters in
3120 /// C.
3121 struct GNUCompatibleParamWarning {
3122   ParmVarDecl *OldParm;
3123   ParmVarDecl *NewParm;
3124   QualType PromotedType;
3125 };
3126 
3127 } // end anonymous namespace
3128 
3129 // Determine whether the previous declaration was a definition, implicit
3130 // declaration, or a declaration.
3131 template <typename T>
3132 static std::pair<diag::kind, SourceLocation>
3133 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3134   diag::kind PrevDiag;
3135   SourceLocation OldLocation = Old->getLocation();
3136   if (Old->isThisDeclarationADefinition())
3137     PrevDiag = diag::note_previous_definition;
3138   else if (Old->isImplicit()) {
3139     PrevDiag = diag::note_previous_implicit_declaration;
3140     if (OldLocation.isInvalid())
3141       OldLocation = New->getLocation();
3142   } else
3143     PrevDiag = diag::note_previous_declaration;
3144   return std::make_pair(PrevDiag, OldLocation);
3145 }
3146 
3147 /// canRedefineFunction - checks if a function can be redefined. Currently,
3148 /// only extern inline functions can be redefined, and even then only in
3149 /// GNU89 mode.
3150 static bool canRedefineFunction(const FunctionDecl *FD,
3151                                 const LangOptions& LangOpts) {
3152   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3153           !LangOpts.CPlusPlus &&
3154           FD->isInlineSpecified() &&
3155           FD->getStorageClass() == SC_Extern);
3156 }
3157 
3158 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3159   const AttributedType *AT = T->getAs<AttributedType>();
3160   while (AT && !AT->isCallingConv())
3161     AT = AT->getModifiedType()->getAs<AttributedType>();
3162   return AT;
3163 }
3164 
3165 template <typename T>
3166 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3167   const DeclContext *DC = Old->getDeclContext();
3168   if (DC->isRecord())
3169     return false;
3170 
3171   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3172   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3173     return true;
3174   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3175     return true;
3176   return false;
3177 }
3178 
3179 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3180 static bool isExternC(VarTemplateDecl *) { return false; }
3181 static bool isExternC(FunctionTemplateDecl *) { return false; }
3182 
3183 /// Check whether a redeclaration of an entity introduced by a
3184 /// using-declaration is valid, given that we know it's not an overload
3185 /// (nor a hidden tag declaration).
3186 template<typename ExpectedDecl>
3187 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3188                                    ExpectedDecl *New) {
3189   // C++11 [basic.scope.declarative]p4:
3190   //   Given a set of declarations in a single declarative region, each of
3191   //   which specifies the same unqualified name,
3192   //   -- they shall all refer to the same entity, or all refer to functions
3193   //      and function templates; or
3194   //   -- exactly one declaration shall declare a class name or enumeration
3195   //      name that is not a typedef name and the other declarations shall all
3196   //      refer to the same variable or enumerator, or all refer to functions
3197   //      and function templates; in this case the class name or enumeration
3198   //      name is hidden (3.3.10).
3199 
3200   // C++11 [namespace.udecl]p14:
3201   //   If a function declaration in namespace scope or block scope has the
3202   //   same name and the same parameter-type-list as a function introduced
3203   //   by a using-declaration, and the declarations do not declare the same
3204   //   function, the program is ill-formed.
3205 
3206   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3207   if (Old &&
3208       !Old->getDeclContext()->getRedeclContext()->Equals(
3209           New->getDeclContext()->getRedeclContext()) &&
3210       !(isExternC(Old) && isExternC(New)))
3211     Old = nullptr;
3212 
3213   if (!Old) {
3214     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3215     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3216     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3217     return true;
3218   }
3219   return false;
3220 }
3221 
3222 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3223                                             const FunctionDecl *B) {
3224   assert(A->getNumParams() == B->getNumParams());
3225 
3226   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3227     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3228     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3229     if (AttrA == AttrB)
3230       return true;
3231     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3232            AttrA->isDynamic() == AttrB->isDynamic();
3233   };
3234 
3235   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3236 }
3237 
3238 /// If necessary, adjust the semantic declaration context for a qualified
3239 /// declaration to name the correct inline namespace within the qualifier.
3240 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3241                                                DeclaratorDecl *OldD) {
3242   // The only case where we need to update the DeclContext is when
3243   // redeclaration lookup for a qualified name finds a declaration
3244   // in an inline namespace within the context named by the qualifier:
3245   //
3246   //   inline namespace N { int f(); }
3247   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3248   //
3249   // For unqualified declarations, the semantic context *can* change
3250   // along the redeclaration chain (for local extern declarations,
3251   // extern "C" declarations, and friend declarations in particular).
3252   if (!NewD->getQualifier())
3253     return;
3254 
3255   // NewD is probably already in the right context.
3256   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3257   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3258   if (NamedDC->Equals(SemaDC))
3259     return;
3260 
3261   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3262           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3263          "unexpected context for redeclaration");
3264 
3265   auto *LexDC = NewD->getLexicalDeclContext();
3266   auto FixSemaDC = [=](NamedDecl *D) {
3267     if (!D)
3268       return;
3269     D->setDeclContext(SemaDC);
3270     D->setLexicalDeclContext(LexDC);
3271   };
3272 
3273   FixSemaDC(NewD);
3274   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3275     FixSemaDC(FD->getDescribedFunctionTemplate());
3276   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3277     FixSemaDC(VD->getDescribedVarTemplate());
3278 }
3279 
3280 /// MergeFunctionDecl - We just parsed a function 'New' from
3281 /// declarator D which has the same name and scope as a previous
3282 /// declaration 'Old'.  Figure out how to resolve this situation,
3283 /// merging decls or emitting diagnostics as appropriate.
3284 ///
3285 /// In C++, New and Old must be declarations that are not
3286 /// overloaded. Use IsOverload to determine whether New and Old are
3287 /// overloaded, and to select the Old declaration that New should be
3288 /// merged with.
3289 ///
3290 /// Returns true if there was an error, false otherwise.
3291 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3292                              Scope *S, bool MergeTypeWithOld) {
3293   // Verify the old decl was also a function.
3294   FunctionDecl *Old = OldD->getAsFunction();
3295   if (!Old) {
3296     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3297       if (New->getFriendObjectKind()) {
3298         Diag(New->getLocation(), diag::err_using_decl_friend);
3299         Diag(Shadow->getTargetDecl()->getLocation(),
3300              diag::note_using_decl_target);
3301         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3302             << 0;
3303         return true;
3304       }
3305 
3306       // Check whether the two declarations might declare the same function or
3307       // function template.
3308       if (FunctionTemplateDecl *NewTemplate =
3309               New->getDescribedFunctionTemplate()) {
3310         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3311                                                          NewTemplate))
3312           return true;
3313         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3314                          ->getAsFunction();
3315       } else {
3316         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3317           return true;
3318         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3319       }
3320     } else {
3321       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3322         << New->getDeclName();
3323       notePreviousDefinition(OldD, New->getLocation());
3324       return true;
3325     }
3326   }
3327 
3328   // If the old declaration was found in an inline namespace and the new
3329   // declaration was qualified, update the DeclContext to match.
3330   adjustDeclContextForDeclaratorDecl(New, Old);
3331 
3332   // If the old declaration is invalid, just give up here.
3333   if (Old->isInvalidDecl())
3334     return true;
3335 
3336   // Disallow redeclaration of some builtins.
3337   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3338     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3339     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3340         << Old << Old->getType();
3341     return true;
3342   }
3343 
3344   diag::kind PrevDiag;
3345   SourceLocation OldLocation;
3346   std::tie(PrevDiag, OldLocation) =
3347       getNoteDiagForInvalidRedeclaration(Old, New);
3348 
3349   // Don't complain about this if we're in GNU89 mode and the old function
3350   // is an extern inline function.
3351   // Don't complain about specializations. They are not supposed to have
3352   // storage classes.
3353   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3354       New->getStorageClass() == SC_Static &&
3355       Old->hasExternalFormalLinkage() &&
3356       !New->getTemplateSpecializationInfo() &&
3357       !canRedefineFunction(Old, getLangOpts())) {
3358     if (getLangOpts().MicrosoftExt) {
3359       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3360       Diag(OldLocation, PrevDiag);
3361     } else {
3362       Diag(New->getLocation(), diag::err_static_non_static) << New;
3363       Diag(OldLocation, PrevDiag);
3364       return true;
3365     }
3366   }
3367 
3368   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3369     if (!Old->hasAttr<InternalLinkageAttr>()) {
3370       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3371           << ILA;
3372       Diag(Old->getLocation(), diag::note_previous_declaration);
3373       New->dropAttr<InternalLinkageAttr>();
3374     }
3375 
3376   if (auto *EA = New->getAttr<ErrorAttr>()) {
3377     if (!Old->hasAttr<ErrorAttr>()) {
3378       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3379       Diag(Old->getLocation(), diag::note_previous_declaration);
3380       New->dropAttr<ErrorAttr>();
3381     }
3382   }
3383 
3384   if (CheckRedeclarationModuleOwnership(New, Old))
3385     return true;
3386 
3387   if (!getLangOpts().CPlusPlus) {
3388     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3389     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3390       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3391         << New << OldOvl;
3392 
3393       // Try our best to find a decl that actually has the overloadable
3394       // attribute for the note. In most cases (e.g. programs with only one
3395       // broken declaration/definition), this won't matter.
3396       //
3397       // FIXME: We could do this if we juggled some extra state in
3398       // OverloadableAttr, rather than just removing it.
3399       const Decl *DiagOld = Old;
3400       if (OldOvl) {
3401         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3402           const auto *A = D->getAttr<OverloadableAttr>();
3403           return A && !A->isImplicit();
3404         });
3405         // If we've implicitly added *all* of the overloadable attrs to this
3406         // chain, emitting a "previous redecl" note is pointless.
3407         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3408       }
3409 
3410       if (DiagOld)
3411         Diag(DiagOld->getLocation(),
3412              diag::note_attribute_overloadable_prev_overload)
3413           << OldOvl;
3414 
3415       if (OldOvl)
3416         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3417       else
3418         New->dropAttr<OverloadableAttr>();
3419     }
3420   }
3421 
3422   // If a function is first declared with a calling convention, but is later
3423   // declared or defined without one, all following decls assume the calling
3424   // convention of the first.
3425   //
3426   // It's OK if a function is first declared without a calling convention,
3427   // but is later declared or defined with the default calling convention.
3428   //
3429   // To test if either decl has an explicit calling convention, we look for
3430   // AttributedType sugar nodes on the type as written.  If they are missing or
3431   // were canonicalized away, we assume the calling convention was implicit.
3432   //
3433   // Note also that we DO NOT return at this point, because we still have
3434   // other tests to run.
3435   QualType OldQType = Context.getCanonicalType(Old->getType());
3436   QualType NewQType = Context.getCanonicalType(New->getType());
3437   const FunctionType *OldType = cast<FunctionType>(OldQType);
3438   const FunctionType *NewType = cast<FunctionType>(NewQType);
3439   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3440   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3441   bool RequiresAdjustment = false;
3442 
3443   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3444     FunctionDecl *First = Old->getFirstDecl();
3445     const FunctionType *FT =
3446         First->getType().getCanonicalType()->castAs<FunctionType>();
3447     FunctionType::ExtInfo FI = FT->getExtInfo();
3448     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3449     if (!NewCCExplicit) {
3450       // Inherit the CC from the previous declaration if it was specified
3451       // there but not here.
3452       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3453       RequiresAdjustment = true;
3454     } else if (Old->getBuiltinID()) {
3455       // Builtin attribute isn't propagated to the new one yet at this point,
3456       // so we check if the old one is a builtin.
3457 
3458       // Calling Conventions on a Builtin aren't really useful and setting a
3459       // default calling convention and cdecl'ing some builtin redeclarations is
3460       // common, so warn and ignore the calling convention on the redeclaration.
3461       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3462           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3463           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3464       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3465       RequiresAdjustment = true;
3466     } else {
3467       // Calling conventions aren't compatible, so complain.
3468       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3469       Diag(New->getLocation(), diag::err_cconv_change)
3470         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3471         << !FirstCCExplicit
3472         << (!FirstCCExplicit ? "" :
3473             FunctionType::getNameForCallConv(FI.getCC()));
3474 
3475       // Put the note on the first decl, since it is the one that matters.
3476       Diag(First->getLocation(), diag::note_previous_declaration);
3477       return true;
3478     }
3479   }
3480 
3481   // FIXME: diagnose the other way around?
3482   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3483     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3484     RequiresAdjustment = true;
3485   }
3486 
3487   // Merge regparm attribute.
3488   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3489       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3490     if (NewTypeInfo.getHasRegParm()) {
3491       Diag(New->getLocation(), diag::err_regparm_mismatch)
3492         << NewType->getRegParmType()
3493         << OldType->getRegParmType();
3494       Diag(OldLocation, diag::note_previous_declaration);
3495       return true;
3496     }
3497 
3498     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3499     RequiresAdjustment = true;
3500   }
3501 
3502   // Merge ns_returns_retained attribute.
3503   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3504     if (NewTypeInfo.getProducesResult()) {
3505       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3506           << "'ns_returns_retained'";
3507       Diag(OldLocation, diag::note_previous_declaration);
3508       return true;
3509     }
3510 
3511     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3512     RequiresAdjustment = true;
3513   }
3514 
3515   if (OldTypeInfo.getNoCallerSavedRegs() !=
3516       NewTypeInfo.getNoCallerSavedRegs()) {
3517     if (NewTypeInfo.getNoCallerSavedRegs()) {
3518       AnyX86NoCallerSavedRegistersAttr *Attr =
3519         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3520       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3521       Diag(OldLocation, diag::note_previous_declaration);
3522       return true;
3523     }
3524 
3525     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3526     RequiresAdjustment = true;
3527   }
3528 
3529   if (RequiresAdjustment) {
3530     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3531     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3532     New->setType(QualType(AdjustedType, 0));
3533     NewQType = Context.getCanonicalType(New->getType());
3534   }
3535 
3536   // If this redeclaration makes the function inline, we may need to add it to
3537   // UndefinedButUsed.
3538   if (!Old->isInlined() && New->isInlined() &&
3539       !New->hasAttr<GNUInlineAttr>() &&
3540       !getLangOpts().GNUInline &&
3541       Old->isUsed(false) &&
3542       !Old->isDefined() && !New->isThisDeclarationADefinition())
3543     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3544                                            SourceLocation()));
3545 
3546   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3547   // about it.
3548   if (New->hasAttr<GNUInlineAttr>() &&
3549       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3550     UndefinedButUsed.erase(Old->getCanonicalDecl());
3551   }
3552 
3553   // If pass_object_size params don't match up perfectly, this isn't a valid
3554   // redeclaration.
3555   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3556       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3557     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3558         << New->getDeclName();
3559     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3560     return true;
3561   }
3562 
3563   if (getLangOpts().CPlusPlus) {
3564     // C++1z [over.load]p2
3565     //   Certain function declarations cannot be overloaded:
3566     //     -- Function declarations that differ only in the return type,
3567     //        the exception specification, or both cannot be overloaded.
3568 
3569     // Check the exception specifications match. This may recompute the type of
3570     // both Old and New if it resolved exception specifications, so grab the
3571     // types again after this. Because this updates the type, we do this before
3572     // any of the other checks below, which may update the "de facto" NewQType
3573     // but do not necessarily update the type of New.
3574     if (CheckEquivalentExceptionSpec(Old, New))
3575       return true;
3576     OldQType = Context.getCanonicalType(Old->getType());
3577     NewQType = Context.getCanonicalType(New->getType());
3578 
3579     // Go back to the type source info to compare the declared return types,
3580     // per C++1y [dcl.type.auto]p13:
3581     //   Redeclarations or specializations of a function or function template
3582     //   with a declared return type that uses a placeholder type shall also
3583     //   use that placeholder, not a deduced type.
3584     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3585     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3586     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3587         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3588                                        OldDeclaredReturnType)) {
3589       QualType ResQT;
3590       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3591           OldDeclaredReturnType->isObjCObjectPointerType())
3592         // FIXME: This does the wrong thing for a deduced return type.
3593         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3594       if (ResQT.isNull()) {
3595         if (New->isCXXClassMember() && New->isOutOfLine())
3596           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3597               << New << New->getReturnTypeSourceRange();
3598         else
3599           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3600               << New->getReturnTypeSourceRange();
3601         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3602                                     << Old->getReturnTypeSourceRange();
3603         return true;
3604       }
3605       else
3606         NewQType = ResQT;
3607     }
3608 
3609     QualType OldReturnType = OldType->getReturnType();
3610     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3611     if (OldReturnType != NewReturnType) {
3612       // If this function has a deduced return type and has already been
3613       // defined, copy the deduced value from the old declaration.
3614       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3615       if (OldAT && OldAT->isDeduced()) {
3616         QualType DT = OldAT->getDeducedType();
3617         if (DT.isNull()) {
3618           New->setType(SubstAutoTypeDependent(New->getType()));
3619           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3620         } else {
3621           New->setType(SubstAutoType(New->getType(), DT));
3622           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3623         }
3624       }
3625     }
3626 
3627     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3628     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3629     if (OldMethod && NewMethod) {
3630       // Preserve triviality.
3631       NewMethod->setTrivial(OldMethod->isTrivial());
3632 
3633       // MSVC allows explicit template specialization at class scope:
3634       // 2 CXXMethodDecls referring to the same function will be injected.
3635       // We don't want a redeclaration error.
3636       bool IsClassScopeExplicitSpecialization =
3637                               OldMethod->isFunctionTemplateSpecialization() &&
3638                               NewMethod->isFunctionTemplateSpecialization();
3639       bool isFriend = NewMethod->getFriendObjectKind();
3640 
3641       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3642           !IsClassScopeExplicitSpecialization) {
3643         //    -- Member function declarations with the same name and the
3644         //       same parameter types cannot be overloaded if any of them
3645         //       is a static member function declaration.
3646         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3647           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3648           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3649           return true;
3650         }
3651 
3652         // C++ [class.mem]p1:
3653         //   [...] A member shall not be declared twice in the
3654         //   member-specification, except that a nested class or member
3655         //   class template can be declared and then later defined.
3656         if (!inTemplateInstantiation()) {
3657           unsigned NewDiag;
3658           if (isa<CXXConstructorDecl>(OldMethod))
3659             NewDiag = diag::err_constructor_redeclared;
3660           else if (isa<CXXDestructorDecl>(NewMethod))
3661             NewDiag = diag::err_destructor_redeclared;
3662           else if (isa<CXXConversionDecl>(NewMethod))
3663             NewDiag = diag::err_conv_function_redeclared;
3664           else
3665             NewDiag = diag::err_member_redeclared;
3666 
3667           Diag(New->getLocation(), NewDiag);
3668         } else {
3669           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3670             << New << New->getType();
3671         }
3672         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3673         return true;
3674 
3675       // Complain if this is an explicit declaration of a special
3676       // member that was initially declared implicitly.
3677       //
3678       // As an exception, it's okay to befriend such methods in order
3679       // to permit the implicit constructor/destructor/operator calls.
3680       } else if (OldMethod->isImplicit()) {
3681         if (isFriend) {
3682           NewMethod->setImplicit();
3683         } else {
3684           Diag(NewMethod->getLocation(),
3685                diag::err_definition_of_implicitly_declared_member)
3686             << New << getSpecialMember(OldMethod);
3687           return true;
3688         }
3689       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3690         Diag(NewMethod->getLocation(),
3691              diag::err_definition_of_explicitly_defaulted_member)
3692           << getSpecialMember(OldMethod);
3693         return true;
3694       }
3695     }
3696 
3697     // C++11 [dcl.attr.noreturn]p1:
3698     //   The first declaration of a function shall specify the noreturn
3699     //   attribute if any declaration of that function specifies the noreturn
3700     //   attribute.
3701     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3702       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3703         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3704             << NRA;
3705         Diag(Old->getLocation(), diag::note_previous_declaration);
3706       }
3707 
3708     // C++11 [dcl.attr.depend]p2:
3709     //   The first declaration of a function shall specify the
3710     //   carries_dependency attribute for its declarator-id if any declaration
3711     //   of the function specifies the carries_dependency attribute.
3712     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3713     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3714       Diag(CDA->getLocation(),
3715            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3716       Diag(Old->getFirstDecl()->getLocation(),
3717            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3718     }
3719 
3720     // (C++98 8.3.5p3):
3721     //   All declarations for a function shall agree exactly in both the
3722     //   return type and the parameter-type-list.
3723     // We also want to respect all the extended bits except noreturn.
3724 
3725     // noreturn should now match unless the old type info didn't have it.
3726     QualType OldQTypeForComparison = OldQType;
3727     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3728       auto *OldType = OldQType->castAs<FunctionProtoType>();
3729       const FunctionType *OldTypeForComparison
3730         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3731       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3732       assert(OldQTypeForComparison.isCanonical());
3733     }
3734 
3735     if (haveIncompatibleLanguageLinkages(Old, New)) {
3736       // As a special case, retain the language linkage from previous
3737       // declarations of a friend function as an extension.
3738       //
3739       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3740       // and is useful because there's otherwise no way to specify language
3741       // linkage within class scope.
3742       //
3743       // Check cautiously as the friend object kind isn't yet complete.
3744       if (New->getFriendObjectKind() != Decl::FOK_None) {
3745         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3746         Diag(OldLocation, PrevDiag);
3747       } else {
3748         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3749         Diag(OldLocation, PrevDiag);
3750         return true;
3751       }
3752     }
3753 
3754     // If the function types are compatible, merge the declarations. Ignore the
3755     // exception specifier because it was already checked above in
3756     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3757     // about incompatible types under -fms-compatibility.
3758     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3759                                                          NewQType))
3760       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3761 
3762     // If the types are imprecise (due to dependent constructs in friends or
3763     // local extern declarations), it's OK if they differ. We'll check again
3764     // during instantiation.
3765     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3766       return false;
3767 
3768     // Fall through for conflicting redeclarations and redefinitions.
3769   }
3770 
3771   // C: Function types need to be compatible, not identical. This handles
3772   // duplicate function decls like "void f(int); void f(enum X);" properly.
3773   if (!getLangOpts().CPlusPlus &&
3774       Context.typesAreCompatible(OldQType, NewQType)) {
3775     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3776     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3777     const FunctionProtoType *OldProto = nullptr;
3778     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3779         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3780       // The old declaration provided a function prototype, but the
3781       // new declaration does not. Merge in the prototype.
3782       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3783       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3784       NewQType =
3785           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3786                                   OldProto->getExtProtoInfo());
3787       New->setType(NewQType);
3788       New->setHasInheritedPrototype();
3789 
3790       // Synthesize parameters with the same types.
3791       SmallVector<ParmVarDecl*, 16> Params;
3792       for (const auto &ParamType : OldProto->param_types()) {
3793         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3794                                                  SourceLocation(), nullptr,
3795                                                  ParamType, /*TInfo=*/nullptr,
3796                                                  SC_None, nullptr);
3797         Param->setScopeInfo(0, Params.size());
3798         Param->setImplicit();
3799         Params.push_back(Param);
3800       }
3801 
3802       New->setParams(Params);
3803     }
3804 
3805     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3806   }
3807 
3808   // Check if the function types are compatible when pointer size address
3809   // spaces are ignored.
3810   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3811     return false;
3812 
3813   // GNU C permits a K&R definition to follow a prototype declaration
3814   // if the declared types of the parameters in the K&R definition
3815   // match the types in the prototype declaration, even when the
3816   // promoted types of the parameters from the K&R definition differ
3817   // from the types in the prototype. GCC then keeps the types from
3818   // the prototype.
3819   //
3820   // If a variadic prototype is followed by a non-variadic K&R definition,
3821   // the K&R definition becomes variadic.  This is sort of an edge case, but
3822   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3823   // C99 6.9.1p8.
3824   if (!getLangOpts().CPlusPlus &&
3825       Old->hasPrototype() && !New->hasPrototype() &&
3826       New->getType()->getAs<FunctionProtoType>() &&
3827       Old->getNumParams() == New->getNumParams()) {
3828     SmallVector<QualType, 16> ArgTypes;
3829     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3830     const FunctionProtoType *OldProto
3831       = Old->getType()->getAs<FunctionProtoType>();
3832     const FunctionProtoType *NewProto
3833       = New->getType()->getAs<FunctionProtoType>();
3834 
3835     // Determine whether this is the GNU C extension.
3836     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3837                                                NewProto->getReturnType());
3838     bool LooseCompatible = !MergedReturn.isNull();
3839     for (unsigned Idx = 0, End = Old->getNumParams();
3840          LooseCompatible && Idx != End; ++Idx) {
3841       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3842       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3843       if (Context.typesAreCompatible(OldParm->getType(),
3844                                      NewProto->getParamType(Idx))) {
3845         ArgTypes.push_back(NewParm->getType());
3846       } else if (Context.typesAreCompatible(OldParm->getType(),
3847                                             NewParm->getType(),
3848                                             /*CompareUnqualified=*/true)) {
3849         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3850                                            NewProto->getParamType(Idx) };
3851         Warnings.push_back(Warn);
3852         ArgTypes.push_back(NewParm->getType());
3853       } else
3854         LooseCompatible = false;
3855     }
3856 
3857     if (LooseCompatible) {
3858       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3859         Diag(Warnings[Warn].NewParm->getLocation(),
3860              diag::ext_param_promoted_not_compatible_with_prototype)
3861           << Warnings[Warn].PromotedType
3862           << Warnings[Warn].OldParm->getType();
3863         if (Warnings[Warn].OldParm->getLocation().isValid())
3864           Diag(Warnings[Warn].OldParm->getLocation(),
3865                diag::note_previous_declaration);
3866       }
3867 
3868       if (MergeTypeWithOld)
3869         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3870                                              OldProto->getExtProtoInfo()));
3871       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3872     }
3873 
3874     // Fall through to diagnose conflicting types.
3875   }
3876 
3877   // A function that has already been declared has been redeclared or
3878   // defined with a different type; show an appropriate diagnostic.
3879 
3880   // If the previous declaration was an implicitly-generated builtin
3881   // declaration, then at the very least we should use a specialized note.
3882   unsigned BuiltinID;
3883   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3884     // If it's actually a library-defined builtin function like 'malloc'
3885     // or 'printf', just warn about the incompatible redeclaration.
3886     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3887       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3888       Diag(OldLocation, diag::note_previous_builtin_declaration)
3889         << Old << Old->getType();
3890       return false;
3891     }
3892 
3893     PrevDiag = diag::note_previous_builtin_declaration;
3894   }
3895 
3896   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3897   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3898   return true;
3899 }
3900 
3901 /// Completes the merge of two function declarations that are
3902 /// known to be compatible.
3903 ///
3904 /// This routine handles the merging of attributes and other
3905 /// properties of function declarations from the old declaration to
3906 /// the new declaration, once we know that New is in fact a
3907 /// redeclaration of Old.
3908 ///
3909 /// \returns false
3910 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3911                                         Scope *S, bool MergeTypeWithOld) {
3912   // Merge the attributes
3913   mergeDeclAttributes(New, Old);
3914 
3915   // Merge "pure" flag.
3916   if (Old->isPure())
3917     New->setPure();
3918 
3919   // Merge "used" flag.
3920   if (Old->getMostRecentDecl()->isUsed(false))
3921     New->setIsUsed();
3922 
3923   // Merge attributes from the parameters.  These can mismatch with K&R
3924   // declarations.
3925   if (New->getNumParams() == Old->getNumParams())
3926       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3927         ParmVarDecl *NewParam = New->getParamDecl(i);
3928         ParmVarDecl *OldParam = Old->getParamDecl(i);
3929         mergeParamDeclAttributes(NewParam, OldParam, *this);
3930         mergeParamDeclTypes(NewParam, OldParam, *this);
3931       }
3932 
3933   if (getLangOpts().CPlusPlus)
3934     return MergeCXXFunctionDecl(New, Old, S);
3935 
3936   // Merge the function types so the we get the composite types for the return
3937   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3938   // was visible.
3939   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3940   if (!Merged.isNull() && MergeTypeWithOld)
3941     New->setType(Merged);
3942 
3943   return false;
3944 }
3945 
3946 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3947                                 ObjCMethodDecl *oldMethod) {
3948   // Merge the attributes, including deprecated/unavailable
3949   AvailabilityMergeKind MergeKind =
3950       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3951           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3952                                      : AMK_ProtocolImplementation)
3953           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3954                                                            : AMK_Override;
3955 
3956   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3957 
3958   // Merge attributes from the parameters.
3959   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3960                                        oe = oldMethod->param_end();
3961   for (ObjCMethodDecl::param_iterator
3962          ni = newMethod->param_begin(), ne = newMethod->param_end();
3963        ni != ne && oi != oe; ++ni, ++oi)
3964     mergeParamDeclAttributes(*ni, *oi, *this);
3965 
3966   CheckObjCMethodOverride(newMethod, oldMethod);
3967 }
3968 
3969 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3970   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3971 
3972   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3973          ? diag::err_redefinition_different_type
3974          : diag::err_redeclaration_different_type)
3975     << New->getDeclName() << New->getType() << Old->getType();
3976 
3977   diag::kind PrevDiag;
3978   SourceLocation OldLocation;
3979   std::tie(PrevDiag, OldLocation)
3980     = getNoteDiagForInvalidRedeclaration(Old, New);
3981   S.Diag(OldLocation, PrevDiag);
3982   New->setInvalidDecl();
3983 }
3984 
3985 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3986 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3987 /// emitting diagnostics as appropriate.
3988 ///
3989 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3990 /// to here in AddInitializerToDecl. We can't check them before the initializer
3991 /// is attached.
3992 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3993                              bool MergeTypeWithOld) {
3994   if (New->isInvalidDecl() || Old->isInvalidDecl())
3995     return;
3996 
3997   QualType MergedT;
3998   if (getLangOpts().CPlusPlus) {
3999     if (New->getType()->isUndeducedType()) {
4000       // We don't know what the new type is until the initializer is attached.
4001       return;
4002     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4003       // These could still be something that needs exception specs checked.
4004       return MergeVarDeclExceptionSpecs(New, Old);
4005     }
4006     // C++ [basic.link]p10:
4007     //   [...] the types specified by all declarations referring to a given
4008     //   object or function shall be identical, except that declarations for an
4009     //   array object can specify array types that differ by the presence or
4010     //   absence of a major array bound (8.3.4).
4011     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4012       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4013       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4014 
4015       // We are merging a variable declaration New into Old. If it has an array
4016       // bound, and that bound differs from Old's bound, we should diagnose the
4017       // mismatch.
4018       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4019         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4020              PrevVD = PrevVD->getPreviousDecl()) {
4021           QualType PrevVDTy = PrevVD->getType();
4022           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4023             continue;
4024 
4025           if (!Context.hasSameType(New->getType(), PrevVDTy))
4026             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4027         }
4028       }
4029 
4030       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4031         if (Context.hasSameType(OldArray->getElementType(),
4032                                 NewArray->getElementType()))
4033           MergedT = New->getType();
4034       }
4035       // FIXME: Check visibility. New is hidden but has a complete type. If New
4036       // has no array bound, it should not inherit one from Old, if Old is not
4037       // visible.
4038       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4039         if (Context.hasSameType(OldArray->getElementType(),
4040                                 NewArray->getElementType()))
4041           MergedT = Old->getType();
4042       }
4043     }
4044     else if (New->getType()->isObjCObjectPointerType() &&
4045                Old->getType()->isObjCObjectPointerType()) {
4046       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4047                                               Old->getType());
4048     }
4049   } else {
4050     // C 6.2.7p2:
4051     //   All declarations that refer to the same object or function shall have
4052     //   compatible type.
4053     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4054   }
4055   if (MergedT.isNull()) {
4056     // It's OK if we couldn't merge types if either type is dependent, for a
4057     // block-scope variable. In other cases (static data members of class
4058     // templates, variable templates, ...), we require the types to be
4059     // equivalent.
4060     // FIXME: The C++ standard doesn't say anything about this.
4061     if ((New->getType()->isDependentType() ||
4062          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4063       // If the old type was dependent, we can't merge with it, so the new type
4064       // becomes dependent for now. We'll reproduce the original type when we
4065       // instantiate the TypeSourceInfo for the variable.
4066       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4067         New->setType(Context.DependentTy);
4068       return;
4069     }
4070     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4071   }
4072 
4073   // Don't actually update the type on the new declaration if the old
4074   // declaration was an extern declaration in a different scope.
4075   if (MergeTypeWithOld)
4076     New->setType(MergedT);
4077 }
4078 
4079 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4080                                   LookupResult &Previous) {
4081   // C11 6.2.7p4:
4082   //   For an identifier with internal or external linkage declared
4083   //   in a scope in which a prior declaration of that identifier is
4084   //   visible, if the prior declaration specifies internal or
4085   //   external linkage, the type of the identifier at the later
4086   //   declaration becomes the composite type.
4087   //
4088   // If the variable isn't visible, we do not merge with its type.
4089   if (Previous.isShadowed())
4090     return false;
4091 
4092   if (S.getLangOpts().CPlusPlus) {
4093     // C++11 [dcl.array]p3:
4094     //   If there is a preceding declaration of the entity in the same
4095     //   scope in which the bound was specified, an omitted array bound
4096     //   is taken to be the same as in that earlier declaration.
4097     return NewVD->isPreviousDeclInSameBlockScope() ||
4098            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4099             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4100   } else {
4101     // If the old declaration was function-local, don't merge with its
4102     // type unless we're in the same function.
4103     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4104            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4105   }
4106 }
4107 
4108 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4109 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4110 /// situation, merging decls or emitting diagnostics as appropriate.
4111 ///
4112 /// Tentative definition rules (C99 6.9.2p2) are checked by
4113 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4114 /// definitions here, since the initializer hasn't been attached.
4115 ///
4116 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4117   // If the new decl is already invalid, don't do any other checking.
4118   if (New->isInvalidDecl())
4119     return;
4120 
4121   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4122     return;
4123 
4124   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4125 
4126   // Verify the old decl was also a variable or variable template.
4127   VarDecl *Old = nullptr;
4128   VarTemplateDecl *OldTemplate = nullptr;
4129   if (Previous.isSingleResult()) {
4130     if (NewTemplate) {
4131       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4132       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4133 
4134       if (auto *Shadow =
4135               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4136         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4137           return New->setInvalidDecl();
4138     } else {
4139       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4140 
4141       if (auto *Shadow =
4142               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4143         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4144           return New->setInvalidDecl();
4145     }
4146   }
4147   if (!Old) {
4148     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4149         << New->getDeclName();
4150     notePreviousDefinition(Previous.getRepresentativeDecl(),
4151                            New->getLocation());
4152     return New->setInvalidDecl();
4153   }
4154 
4155   // If the old declaration was found in an inline namespace and the new
4156   // declaration was qualified, update the DeclContext to match.
4157   adjustDeclContextForDeclaratorDecl(New, Old);
4158 
4159   // Ensure the template parameters are compatible.
4160   if (NewTemplate &&
4161       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4162                                       OldTemplate->getTemplateParameters(),
4163                                       /*Complain=*/true, TPL_TemplateMatch))
4164     return New->setInvalidDecl();
4165 
4166   // C++ [class.mem]p1:
4167   //   A member shall not be declared twice in the member-specification [...]
4168   //
4169   // Here, we need only consider static data members.
4170   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4171     Diag(New->getLocation(), diag::err_duplicate_member)
4172       << New->getIdentifier();
4173     Diag(Old->getLocation(), diag::note_previous_declaration);
4174     New->setInvalidDecl();
4175   }
4176 
4177   mergeDeclAttributes(New, Old);
4178   // Warn if an already-declared variable is made a weak_import in a subsequent
4179   // declaration
4180   if (New->hasAttr<WeakImportAttr>() &&
4181       Old->getStorageClass() == SC_None &&
4182       !Old->hasAttr<WeakImportAttr>()) {
4183     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4184     Diag(Old->getLocation(), diag::note_previous_declaration);
4185     // Remove weak_import attribute on new declaration.
4186     New->dropAttr<WeakImportAttr>();
4187   }
4188 
4189   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4190     if (!Old->hasAttr<InternalLinkageAttr>()) {
4191       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4192           << ILA;
4193       Diag(Old->getLocation(), diag::note_previous_declaration);
4194       New->dropAttr<InternalLinkageAttr>();
4195     }
4196 
4197   // Merge the types.
4198   VarDecl *MostRecent = Old->getMostRecentDecl();
4199   if (MostRecent != Old) {
4200     MergeVarDeclTypes(New, MostRecent,
4201                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4202     if (New->isInvalidDecl())
4203       return;
4204   }
4205 
4206   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4207   if (New->isInvalidDecl())
4208     return;
4209 
4210   diag::kind PrevDiag;
4211   SourceLocation OldLocation;
4212   std::tie(PrevDiag, OldLocation) =
4213       getNoteDiagForInvalidRedeclaration(Old, New);
4214 
4215   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4216   if (New->getStorageClass() == SC_Static &&
4217       !New->isStaticDataMember() &&
4218       Old->hasExternalFormalLinkage()) {
4219     if (getLangOpts().MicrosoftExt) {
4220       Diag(New->getLocation(), diag::ext_static_non_static)
4221           << New->getDeclName();
4222       Diag(OldLocation, PrevDiag);
4223     } else {
4224       Diag(New->getLocation(), diag::err_static_non_static)
4225           << New->getDeclName();
4226       Diag(OldLocation, PrevDiag);
4227       return New->setInvalidDecl();
4228     }
4229   }
4230   // C99 6.2.2p4:
4231   //   For an identifier declared with the storage-class specifier
4232   //   extern in a scope in which a prior declaration of that
4233   //   identifier is visible,23) if the prior declaration specifies
4234   //   internal or external linkage, the linkage of the identifier at
4235   //   the later declaration is the same as the linkage specified at
4236   //   the prior declaration. If no prior declaration is visible, or
4237   //   if the prior declaration specifies no linkage, then the
4238   //   identifier has external linkage.
4239   if (New->hasExternalStorage() && Old->hasLinkage())
4240     /* Okay */;
4241   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4242            !New->isStaticDataMember() &&
4243            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4244     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4245     Diag(OldLocation, PrevDiag);
4246     return New->setInvalidDecl();
4247   }
4248 
4249   // Check if extern is followed by non-extern and vice-versa.
4250   if (New->hasExternalStorage() &&
4251       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4252     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4253     Diag(OldLocation, PrevDiag);
4254     return New->setInvalidDecl();
4255   }
4256   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4257       !New->hasExternalStorage()) {
4258     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4259     Diag(OldLocation, PrevDiag);
4260     return New->setInvalidDecl();
4261   }
4262 
4263   if (CheckRedeclarationModuleOwnership(New, Old))
4264     return;
4265 
4266   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4267 
4268   // FIXME: The test for external storage here seems wrong? We still
4269   // need to check for mismatches.
4270   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4271       // Don't complain about out-of-line definitions of static members.
4272       !(Old->getLexicalDeclContext()->isRecord() &&
4273         !New->getLexicalDeclContext()->isRecord())) {
4274     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4275     Diag(OldLocation, PrevDiag);
4276     return New->setInvalidDecl();
4277   }
4278 
4279   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4280     if (VarDecl *Def = Old->getDefinition()) {
4281       // C++1z [dcl.fcn.spec]p4:
4282       //   If the definition of a variable appears in a translation unit before
4283       //   its first declaration as inline, the program is ill-formed.
4284       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4285       Diag(Def->getLocation(), diag::note_previous_definition);
4286     }
4287   }
4288 
4289   // If this redeclaration makes the variable inline, we may need to add it to
4290   // UndefinedButUsed.
4291   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4292       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4293     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4294                                            SourceLocation()));
4295 
4296   if (New->getTLSKind() != Old->getTLSKind()) {
4297     if (!Old->getTLSKind()) {
4298       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4299       Diag(OldLocation, PrevDiag);
4300     } else if (!New->getTLSKind()) {
4301       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4302       Diag(OldLocation, PrevDiag);
4303     } else {
4304       // Do not allow redeclaration to change the variable between requiring
4305       // static and dynamic initialization.
4306       // FIXME: GCC allows this, but uses the TLS keyword on the first
4307       // declaration to determine the kind. Do we need to be compatible here?
4308       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4309         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4310       Diag(OldLocation, PrevDiag);
4311     }
4312   }
4313 
4314   // C++ doesn't have tentative definitions, so go right ahead and check here.
4315   if (getLangOpts().CPlusPlus &&
4316       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4317     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4318         Old->getCanonicalDecl()->isConstexpr()) {
4319       // This definition won't be a definition any more once it's been merged.
4320       Diag(New->getLocation(),
4321            diag::warn_deprecated_redundant_constexpr_static_def);
4322     } else if (VarDecl *Def = Old->getDefinition()) {
4323       if (checkVarDeclRedefinition(Def, New))
4324         return;
4325     }
4326   }
4327 
4328   if (haveIncompatibleLanguageLinkages(Old, New)) {
4329     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4330     Diag(OldLocation, PrevDiag);
4331     New->setInvalidDecl();
4332     return;
4333   }
4334 
4335   // Merge "used" flag.
4336   if (Old->getMostRecentDecl()->isUsed(false))
4337     New->setIsUsed();
4338 
4339   // Keep a chain of previous declarations.
4340   New->setPreviousDecl(Old);
4341   if (NewTemplate)
4342     NewTemplate->setPreviousDecl(OldTemplate);
4343 
4344   // Inherit access appropriately.
4345   New->setAccess(Old->getAccess());
4346   if (NewTemplate)
4347     NewTemplate->setAccess(New->getAccess());
4348 
4349   if (Old->isInline())
4350     New->setImplicitlyInline();
4351 }
4352 
4353 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4354   SourceManager &SrcMgr = getSourceManager();
4355   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4356   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4357   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4358   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4359   auto &HSI = PP.getHeaderSearchInfo();
4360   StringRef HdrFilename =
4361       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4362 
4363   auto noteFromModuleOrInclude = [&](Module *Mod,
4364                                      SourceLocation IncLoc) -> bool {
4365     // Redefinition errors with modules are common with non modular mapped
4366     // headers, example: a non-modular header H in module A that also gets
4367     // included directly in a TU. Pointing twice to the same header/definition
4368     // is confusing, try to get better diagnostics when modules is on.
4369     if (IncLoc.isValid()) {
4370       if (Mod) {
4371         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4372             << HdrFilename.str() << Mod->getFullModuleName();
4373         if (!Mod->DefinitionLoc.isInvalid())
4374           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4375               << Mod->getFullModuleName();
4376       } else {
4377         Diag(IncLoc, diag::note_redefinition_include_same_file)
4378             << HdrFilename.str();
4379       }
4380       return true;
4381     }
4382 
4383     return false;
4384   };
4385 
4386   // Is it the same file and same offset? Provide more information on why
4387   // this leads to a redefinition error.
4388   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4389     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4390     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4391     bool EmittedDiag =
4392         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4393     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4394 
4395     // If the header has no guards, emit a note suggesting one.
4396     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4397       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4398 
4399     if (EmittedDiag)
4400       return;
4401   }
4402 
4403   // Redefinition coming from different files or couldn't do better above.
4404   if (Old->getLocation().isValid())
4405     Diag(Old->getLocation(), diag::note_previous_definition);
4406 }
4407 
4408 /// We've just determined that \p Old and \p New both appear to be definitions
4409 /// of the same variable. Either diagnose or fix the problem.
4410 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4411   if (!hasVisibleDefinition(Old) &&
4412       (New->getFormalLinkage() == InternalLinkage ||
4413        New->isInline() ||
4414        New->getDescribedVarTemplate() ||
4415        New->getNumTemplateParameterLists() ||
4416        New->getDeclContext()->isDependentContext())) {
4417     // The previous definition is hidden, and multiple definitions are
4418     // permitted (in separate TUs). Demote this to a declaration.
4419     New->demoteThisDefinitionToDeclaration();
4420 
4421     // Make the canonical definition visible.
4422     if (auto *OldTD = Old->getDescribedVarTemplate())
4423       makeMergedDefinitionVisible(OldTD);
4424     makeMergedDefinitionVisible(Old);
4425     return false;
4426   } else {
4427     Diag(New->getLocation(), diag::err_redefinition) << New;
4428     notePreviousDefinition(Old, New->getLocation());
4429     New->setInvalidDecl();
4430     return true;
4431   }
4432 }
4433 
4434 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4435 /// no declarator (e.g. "struct foo;") is parsed.
4436 Decl *
4437 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4438                                  RecordDecl *&AnonRecord) {
4439   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4440                                     AnonRecord);
4441 }
4442 
4443 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4444 // disambiguate entities defined in different scopes.
4445 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4446 // compatibility.
4447 // We will pick our mangling number depending on which version of MSVC is being
4448 // targeted.
4449 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4450   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4451              ? S->getMSCurManglingNumber()
4452              : S->getMSLastManglingNumber();
4453 }
4454 
4455 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4456   if (!Context.getLangOpts().CPlusPlus)
4457     return;
4458 
4459   if (isa<CXXRecordDecl>(Tag->getParent())) {
4460     // If this tag is the direct child of a class, number it if
4461     // it is anonymous.
4462     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4463       return;
4464     MangleNumberingContext &MCtx =
4465         Context.getManglingNumberContext(Tag->getParent());
4466     Context.setManglingNumber(
4467         Tag, MCtx.getManglingNumber(
4468                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4469     return;
4470   }
4471 
4472   // If this tag isn't a direct child of a class, number it if it is local.
4473   MangleNumberingContext *MCtx;
4474   Decl *ManglingContextDecl;
4475   std::tie(MCtx, ManglingContextDecl) =
4476       getCurrentMangleNumberContext(Tag->getDeclContext());
4477   if (MCtx) {
4478     Context.setManglingNumber(
4479         Tag, MCtx->getManglingNumber(
4480                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4481   }
4482 }
4483 
4484 namespace {
4485 struct NonCLikeKind {
4486   enum {
4487     None,
4488     BaseClass,
4489     DefaultMemberInit,
4490     Lambda,
4491     Friend,
4492     OtherMember,
4493     Invalid,
4494   } Kind = None;
4495   SourceRange Range;
4496 
4497   explicit operator bool() { return Kind != None; }
4498 };
4499 }
4500 
4501 /// Determine whether a class is C-like, according to the rules of C++
4502 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4503 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4504   if (RD->isInvalidDecl())
4505     return {NonCLikeKind::Invalid, {}};
4506 
4507   // C++ [dcl.typedef]p9: [P1766R1]
4508   //   An unnamed class with a typedef name for linkage purposes shall not
4509   //
4510   //    -- have any base classes
4511   if (RD->getNumBases())
4512     return {NonCLikeKind::BaseClass,
4513             SourceRange(RD->bases_begin()->getBeginLoc(),
4514                         RD->bases_end()[-1].getEndLoc())};
4515   bool Invalid = false;
4516   for (Decl *D : RD->decls()) {
4517     // Don't complain about things we already diagnosed.
4518     if (D->isInvalidDecl()) {
4519       Invalid = true;
4520       continue;
4521     }
4522 
4523     //  -- have any [...] default member initializers
4524     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4525       if (FD->hasInClassInitializer()) {
4526         auto *Init = FD->getInClassInitializer();
4527         return {NonCLikeKind::DefaultMemberInit,
4528                 Init ? Init->getSourceRange() : D->getSourceRange()};
4529       }
4530       continue;
4531     }
4532 
4533     // FIXME: We don't allow friend declarations. This violates the wording of
4534     // P1766, but not the intent.
4535     if (isa<FriendDecl>(D))
4536       return {NonCLikeKind::Friend, D->getSourceRange()};
4537 
4538     //  -- declare any members other than non-static data members, member
4539     //     enumerations, or member classes,
4540     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4541         isa<EnumDecl>(D))
4542       continue;
4543     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4544     if (!MemberRD) {
4545       if (D->isImplicit())
4546         continue;
4547       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4548     }
4549 
4550     //  -- contain a lambda-expression,
4551     if (MemberRD->isLambda())
4552       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4553 
4554     //  and all member classes shall also satisfy these requirements
4555     //  (recursively).
4556     if (MemberRD->isThisDeclarationADefinition()) {
4557       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4558         return Kind;
4559     }
4560   }
4561 
4562   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4563 }
4564 
4565 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4566                                         TypedefNameDecl *NewTD) {
4567   if (TagFromDeclSpec->isInvalidDecl())
4568     return;
4569 
4570   // Do nothing if the tag already has a name for linkage purposes.
4571   if (TagFromDeclSpec->hasNameForLinkage())
4572     return;
4573 
4574   // A well-formed anonymous tag must always be a TUK_Definition.
4575   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4576 
4577   // The type must match the tag exactly;  no qualifiers allowed.
4578   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4579                            Context.getTagDeclType(TagFromDeclSpec))) {
4580     if (getLangOpts().CPlusPlus)
4581       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4582     return;
4583   }
4584 
4585   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4586   //   An unnamed class with a typedef name for linkage purposes shall [be
4587   //   C-like].
4588   //
4589   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4590   // shouldn't happen, but there are constructs that the language rule doesn't
4591   // disallow for which we can't reasonably avoid computing linkage early.
4592   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4593   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4594                              : NonCLikeKind();
4595   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4596   if (NonCLike || ChangesLinkage) {
4597     if (NonCLike.Kind == NonCLikeKind::Invalid)
4598       return;
4599 
4600     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4601     if (ChangesLinkage) {
4602       // If the linkage changes, we can't accept this as an extension.
4603       if (NonCLike.Kind == NonCLikeKind::None)
4604         DiagID = diag::err_typedef_changes_linkage;
4605       else
4606         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4607     }
4608 
4609     SourceLocation FixitLoc =
4610         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4611     llvm::SmallString<40> TextToInsert;
4612     TextToInsert += ' ';
4613     TextToInsert += NewTD->getIdentifier()->getName();
4614 
4615     Diag(FixitLoc, DiagID)
4616       << isa<TypeAliasDecl>(NewTD)
4617       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4618     if (NonCLike.Kind != NonCLikeKind::None) {
4619       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4620         << NonCLike.Kind - 1 << NonCLike.Range;
4621     }
4622     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4623       << NewTD << isa<TypeAliasDecl>(NewTD);
4624 
4625     if (ChangesLinkage)
4626       return;
4627   }
4628 
4629   // Otherwise, set this as the anon-decl typedef for the tag.
4630   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4631 }
4632 
4633 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4634   switch (T) {
4635   case DeclSpec::TST_class:
4636     return 0;
4637   case DeclSpec::TST_struct:
4638     return 1;
4639   case DeclSpec::TST_interface:
4640     return 2;
4641   case DeclSpec::TST_union:
4642     return 3;
4643   case DeclSpec::TST_enum:
4644     return 4;
4645   default:
4646     llvm_unreachable("unexpected type specifier");
4647   }
4648 }
4649 
4650 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4651 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4652 /// parameters to cope with template friend declarations.
4653 Decl *
4654 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4655                                  MultiTemplateParamsArg TemplateParams,
4656                                  bool IsExplicitInstantiation,
4657                                  RecordDecl *&AnonRecord) {
4658   Decl *TagD = nullptr;
4659   TagDecl *Tag = nullptr;
4660   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4661       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4662       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4663       DS.getTypeSpecType() == DeclSpec::TST_union ||
4664       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4665     TagD = DS.getRepAsDecl();
4666 
4667     if (!TagD) // We probably had an error
4668       return nullptr;
4669 
4670     // Note that the above type specs guarantee that the
4671     // type rep is a Decl, whereas in many of the others
4672     // it's a Type.
4673     if (isa<TagDecl>(TagD))
4674       Tag = cast<TagDecl>(TagD);
4675     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4676       Tag = CTD->getTemplatedDecl();
4677   }
4678 
4679   if (Tag) {
4680     handleTagNumbering(Tag, S);
4681     Tag->setFreeStanding();
4682     if (Tag->isInvalidDecl())
4683       return Tag;
4684   }
4685 
4686   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4687     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4688     // or incomplete types shall not be restrict-qualified."
4689     if (TypeQuals & DeclSpec::TQ_restrict)
4690       Diag(DS.getRestrictSpecLoc(),
4691            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4692            << DS.getSourceRange();
4693   }
4694 
4695   if (DS.isInlineSpecified())
4696     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4697         << getLangOpts().CPlusPlus17;
4698 
4699   if (DS.hasConstexprSpecifier()) {
4700     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4701     // and definitions of functions and variables.
4702     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4703     // the declaration of a function or function template
4704     if (Tag)
4705       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4706           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4707           << static_cast<int>(DS.getConstexprSpecifier());
4708     else
4709       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4710           << static_cast<int>(DS.getConstexprSpecifier());
4711     // Don't emit warnings after this error.
4712     return TagD;
4713   }
4714 
4715   DiagnoseFunctionSpecifiers(DS);
4716 
4717   if (DS.isFriendSpecified()) {
4718     // If we're dealing with a decl but not a TagDecl, assume that
4719     // whatever routines created it handled the friendship aspect.
4720     if (TagD && !Tag)
4721       return nullptr;
4722     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4723   }
4724 
4725   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4726   bool IsExplicitSpecialization =
4727     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4728   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4729       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4730       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4731     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4732     // nested-name-specifier unless it is an explicit instantiation
4733     // or an explicit specialization.
4734     //
4735     // FIXME: We allow class template partial specializations here too, per the
4736     // obvious intent of DR1819.
4737     //
4738     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4739     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4740         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4741     return nullptr;
4742   }
4743 
4744   // Track whether this decl-specifier declares anything.
4745   bool DeclaresAnything = true;
4746 
4747   // Handle anonymous struct definitions.
4748   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4749     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4750         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4751       if (getLangOpts().CPlusPlus ||
4752           Record->getDeclContext()->isRecord()) {
4753         // If CurContext is a DeclContext that can contain statements,
4754         // RecursiveASTVisitor won't visit the decls that
4755         // BuildAnonymousStructOrUnion() will put into CurContext.
4756         // Also store them here so that they can be part of the
4757         // DeclStmt that gets created in this case.
4758         // FIXME: Also return the IndirectFieldDecls created by
4759         // BuildAnonymousStructOr union, for the same reason?
4760         if (CurContext->isFunctionOrMethod())
4761           AnonRecord = Record;
4762         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4763                                            Context.getPrintingPolicy());
4764       }
4765 
4766       DeclaresAnything = false;
4767     }
4768   }
4769 
4770   // C11 6.7.2.1p2:
4771   //   A struct-declaration that does not declare an anonymous structure or
4772   //   anonymous union shall contain a struct-declarator-list.
4773   //
4774   // This rule also existed in C89 and C99; the grammar for struct-declaration
4775   // did not permit a struct-declaration without a struct-declarator-list.
4776   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4777       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4778     // Check for Microsoft C extension: anonymous struct/union member.
4779     // Handle 2 kinds of anonymous struct/union:
4780     //   struct STRUCT;
4781     //   union UNION;
4782     // and
4783     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4784     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4785     if ((Tag && Tag->getDeclName()) ||
4786         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4787       RecordDecl *Record = nullptr;
4788       if (Tag)
4789         Record = dyn_cast<RecordDecl>(Tag);
4790       else if (const RecordType *RT =
4791                    DS.getRepAsType().get()->getAsStructureType())
4792         Record = RT->getDecl();
4793       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4794         Record = UT->getDecl();
4795 
4796       if (Record && getLangOpts().MicrosoftExt) {
4797         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4798             << Record->isUnion() << DS.getSourceRange();
4799         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4800       }
4801 
4802       DeclaresAnything = false;
4803     }
4804   }
4805 
4806   // Skip all the checks below if we have a type error.
4807   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4808       (TagD && TagD->isInvalidDecl()))
4809     return TagD;
4810 
4811   if (getLangOpts().CPlusPlus &&
4812       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4813     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4814       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4815           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4816         DeclaresAnything = false;
4817 
4818   if (!DS.isMissingDeclaratorOk()) {
4819     // Customize diagnostic for a typedef missing a name.
4820     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4821       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4822           << DS.getSourceRange();
4823     else
4824       DeclaresAnything = false;
4825   }
4826 
4827   if (DS.isModulePrivateSpecified() &&
4828       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4829     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4830       << Tag->getTagKind()
4831       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4832 
4833   ActOnDocumentableDecl(TagD);
4834 
4835   // C 6.7/2:
4836   //   A declaration [...] shall declare at least a declarator [...], a tag,
4837   //   or the members of an enumeration.
4838   // C++ [dcl.dcl]p3:
4839   //   [If there are no declarators], and except for the declaration of an
4840   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4841   //   names into the program, or shall redeclare a name introduced by a
4842   //   previous declaration.
4843   if (!DeclaresAnything) {
4844     // In C, we allow this as a (popular) extension / bug. Don't bother
4845     // producing further diagnostics for redundant qualifiers after this.
4846     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4847                                ? diag::err_no_declarators
4848                                : diag::ext_no_declarators)
4849         << DS.getSourceRange();
4850     return TagD;
4851   }
4852 
4853   // C++ [dcl.stc]p1:
4854   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4855   //   init-declarator-list of the declaration shall not be empty.
4856   // C++ [dcl.fct.spec]p1:
4857   //   If a cv-qualifier appears in a decl-specifier-seq, the
4858   //   init-declarator-list of the declaration shall not be empty.
4859   //
4860   // Spurious qualifiers here appear to be valid in C.
4861   unsigned DiagID = diag::warn_standalone_specifier;
4862   if (getLangOpts().CPlusPlus)
4863     DiagID = diag::ext_standalone_specifier;
4864 
4865   // Note that a linkage-specification sets a storage class, but
4866   // 'extern "C" struct foo;' is actually valid and not theoretically
4867   // useless.
4868   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4869     if (SCS == DeclSpec::SCS_mutable)
4870       // Since mutable is not a viable storage class specifier in C, there is
4871       // no reason to treat it as an extension. Instead, diagnose as an error.
4872       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4873     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4874       Diag(DS.getStorageClassSpecLoc(), DiagID)
4875         << DeclSpec::getSpecifierName(SCS);
4876   }
4877 
4878   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4879     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4880       << DeclSpec::getSpecifierName(TSCS);
4881   if (DS.getTypeQualifiers()) {
4882     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4883       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4884     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4885       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4886     // Restrict is covered above.
4887     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4888       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4889     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4890       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4891   }
4892 
4893   // Warn about ignored type attributes, for example:
4894   // __attribute__((aligned)) struct A;
4895   // Attributes should be placed after tag to apply to type declaration.
4896   if (!DS.getAttributes().empty()) {
4897     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4898     if (TypeSpecType == DeclSpec::TST_class ||
4899         TypeSpecType == DeclSpec::TST_struct ||
4900         TypeSpecType == DeclSpec::TST_interface ||
4901         TypeSpecType == DeclSpec::TST_union ||
4902         TypeSpecType == DeclSpec::TST_enum) {
4903       for (const ParsedAttr &AL : DS.getAttributes())
4904         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4905             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4906     }
4907   }
4908 
4909   return TagD;
4910 }
4911 
4912 /// We are trying to inject an anonymous member into the given scope;
4913 /// check if there's an existing declaration that can't be overloaded.
4914 ///
4915 /// \return true if this is a forbidden redeclaration
4916 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4917                                          Scope *S,
4918                                          DeclContext *Owner,
4919                                          DeclarationName Name,
4920                                          SourceLocation NameLoc,
4921                                          bool IsUnion) {
4922   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4923                  Sema::ForVisibleRedeclaration);
4924   if (!SemaRef.LookupName(R, S)) return false;
4925 
4926   // Pick a representative declaration.
4927   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4928   assert(PrevDecl && "Expected a non-null Decl");
4929 
4930   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4931     return false;
4932 
4933   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4934     << IsUnion << Name;
4935   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4936 
4937   return true;
4938 }
4939 
4940 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4941 /// anonymous struct or union AnonRecord into the owning context Owner
4942 /// and scope S. This routine will be invoked just after we realize
4943 /// that an unnamed union or struct is actually an anonymous union or
4944 /// struct, e.g.,
4945 ///
4946 /// @code
4947 /// union {
4948 ///   int i;
4949 ///   float f;
4950 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4951 ///    // f into the surrounding scope.x
4952 /// @endcode
4953 ///
4954 /// This routine is recursive, injecting the names of nested anonymous
4955 /// structs/unions into the owning context and scope as well.
4956 static bool
4957 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4958                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4959                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4960   bool Invalid = false;
4961 
4962   // Look every FieldDecl and IndirectFieldDecl with a name.
4963   for (auto *D : AnonRecord->decls()) {
4964     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4965         cast<NamedDecl>(D)->getDeclName()) {
4966       ValueDecl *VD = cast<ValueDecl>(D);
4967       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4968                                        VD->getLocation(),
4969                                        AnonRecord->isUnion())) {
4970         // C++ [class.union]p2:
4971         //   The names of the members of an anonymous union shall be
4972         //   distinct from the names of any other entity in the
4973         //   scope in which the anonymous union is declared.
4974         Invalid = true;
4975       } else {
4976         // C++ [class.union]p2:
4977         //   For the purpose of name lookup, after the anonymous union
4978         //   definition, the members of the anonymous union are
4979         //   considered to have been defined in the scope in which the
4980         //   anonymous union is declared.
4981         unsigned OldChainingSize = Chaining.size();
4982         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4983           Chaining.append(IF->chain_begin(), IF->chain_end());
4984         else
4985           Chaining.push_back(VD);
4986 
4987         assert(Chaining.size() >= 2);
4988         NamedDecl **NamedChain =
4989           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4990         for (unsigned i = 0; i < Chaining.size(); i++)
4991           NamedChain[i] = Chaining[i];
4992 
4993         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4994             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4995             VD->getType(), {NamedChain, Chaining.size()});
4996 
4997         for (const auto *Attr : VD->attrs())
4998           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4999 
5000         IndirectField->setAccess(AS);
5001         IndirectField->setImplicit();
5002         SemaRef.PushOnScopeChains(IndirectField, S);
5003 
5004         // That includes picking up the appropriate access specifier.
5005         if (AS != AS_none) IndirectField->setAccess(AS);
5006 
5007         Chaining.resize(OldChainingSize);
5008       }
5009     }
5010   }
5011 
5012   return Invalid;
5013 }
5014 
5015 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5016 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5017 /// illegal input values are mapped to SC_None.
5018 static StorageClass
5019 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5020   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5021   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5022          "Parser allowed 'typedef' as storage class VarDecl.");
5023   switch (StorageClassSpec) {
5024   case DeclSpec::SCS_unspecified:    return SC_None;
5025   case DeclSpec::SCS_extern:
5026     if (DS.isExternInLinkageSpec())
5027       return SC_None;
5028     return SC_Extern;
5029   case DeclSpec::SCS_static:         return SC_Static;
5030   case DeclSpec::SCS_auto:           return SC_Auto;
5031   case DeclSpec::SCS_register:       return SC_Register;
5032   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5033     // Illegal SCSs map to None: error reporting is up to the caller.
5034   case DeclSpec::SCS_mutable:        // Fall through.
5035   case DeclSpec::SCS_typedef:        return SC_None;
5036   }
5037   llvm_unreachable("unknown storage class specifier");
5038 }
5039 
5040 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5041   assert(Record->hasInClassInitializer());
5042 
5043   for (const auto *I : Record->decls()) {
5044     const auto *FD = dyn_cast<FieldDecl>(I);
5045     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5046       FD = IFD->getAnonField();
5047     if (FD && FD->hasInClassInitializer())
5048       return FD->getLocation();
5049   }
5050 
5051   llvm_unreachable("couldn't find in-class initializer");
5052 }
5053 
5054 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5055                                       SourceLocation DefaultInitLoc) {
5056   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5057     return;
5058 
5059   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5060   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5061 }
5062 
5063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5064                                       CXXRecordDecl *AnonUnion) {
5065   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5066     return;
5067 
5068   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5069 }
5070 
5071 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5072 /// anonymous structure or union. Anonymous unions are a C++ feature
5073 /// (C++ [class.union]) and a C11 feature; anonymous structures
5074 /// are a C11 feature and GNU C++ extension.
5075 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5076                                         AccessSpecifier AS,
5077                                         RecordDecl *Record,
5078                                         const PrintingPolicy &Policy) {
5079   DeclContext *Owner = Record->getDeclContext();
5080 
5081   // Diagnose whether this anonymous struct/union is an extension.
5082   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5083     Diag(Record->getLocation(), diag::ext_anonymous_union);
5084   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5085     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5086   else if (!Record->isUnion() && !getLangOpts().C11)
5087     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5088 
5089   // C and C++ require different kinds of checks for anonymous
5090   // structs/unions.
5091   bool Invalid = false;
5092   if (getLangOpts().CPlusPlus) {
5093     const char *PrevSpec = nullptr;
5094     if (Record->isUnion()) {
5095       // C++ [class.union]p6:
5096       // C++17 [class.union.anon]p2:
5097       //   Anonymous unions declared in a named namespace or in the
5098       //   global namespace shall be declared static.
5099       unsigned DiagID;
5100       DeclContext *OwnerScope = Owner->getRedeclContext();
5101       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5102           (OwnerScope->isTranslationUnit() ||
5103            (OwnerScope->isNamespace() &&
5104             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5105         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5106           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5107 
5108         // Recover by adding 'static'.
5109         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5110                                PrevSpec, DiagID, Policy);
5111       }
5112       // C++ [class.union]p6:
5113       //   A storage class is not allowed in a declaration of an
5114       //   anonymous union in a class scope.
5115       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5116                isa<RecordDecl>(Owner)) {
5117         Diag(DS.getStorageClassSpecLoc(),
5118              diag::err_anonymous_union_with_storage_spec)
5119           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5120 
5121         // Recover by removing the storage specifier.
5122         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5123                                SourceLocation(),
5124                                PrevSpec, DiagID, Context.getPrintingPolicy());
5125       }
5126     }
5127 
5128     // Ignore const/volatile/restrict qualifiers.
5129     if (DS.getTypeQualifiers()) {
5130       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5131         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5132           << Record->isUnion() << "const"
5133           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5134       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5135         Diag(DS.getVolatileSpecLoc(),
5136              diag::ext_anonymous_struct_union_qualified)
5137           << Record->isUnion() << "volatile"
5138           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5139       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5140         Diag(DS.getRestrictSpecLoc(),
5141              diag::ext_anonymous_struct_union_qualified)
5142           << Record->isUnion() << "restrict"
5143           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5144       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5145         Diag(DS.getAtomicSpecLoc(),
5146              diag::ext_anonymous_struct_union_qualified)
5147           << Record->isUnion() << "_Atomic"
5148           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5149       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5150         Diag(DS.getUnalignedSpecLoc(),
5151              diag::ext_anonymous_struct_union_qualified)
5152           << Record->isUnion() << "__unaligned"
5153           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5154 
5155       DS.ClearTypeQualifiers();
5156     }
5157 
5158     // C++ [class.union]p2:
5159     //   The member-specification of an anonymous union shall only
5160     //   define non-static data members. [Note: nested types and
5161     //   functions cannot be declared within an anonymous union. ]
5162     for (auto *Mem : Record->decls()) {
5163       // Ignore invalid declarations; we already diagnosed them.
5164       if (Mem->isInvalidDecl())
5165         continue;
5166 
5167       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5168         // C++ [class.union]p3:
5169         //   An anonymous union shall not have private or protected
5170         //   members (clause 11).
5171         assert(FD->getAccess() != AS_none);
5172         if (FD->getAccess() != AS_public) {
5173           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5174             << Record->isUnion() << (FD->getAccess() == AS_protected);
5175           Invalid = true;
5176         }
5177 
5178         // C++ [class.union]p1
5179         //   An object of a class with a non-trivial constructor, a non-trivial
5180         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5181         //   assignment operator cannot be a member of a union, nor can an
5182         //   array of such objects.
5183         if (CheckNontrivialField(FD))
5184           Invalid = true;
5185       } else if (Mem->isImplicit()) {
5186         // Any implicit members are fine.
5187       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5188         // This is a type that showed up in an
5189         // elaborated-type-specifier inside the anonymous struct or
5190         // union, but which actually declares a type outside of the
5191         // anonymous struct or union. It's okay.
5192       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5193         if (!MemRecord->isAnonymousStructOrUnion() &&
5194             MemRecord->getDeclName()) {
5195           // Visual C++ allows type definition in anonymous struct or union.
5196           if (getLangOpts().MicrosoftExt)
5197             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5198               << Record->isUnion();
5199           else {
5200             // This is a nested type declaration.
5201             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5202               << Record->isUnion();
5203             Invalid = true;
5204           }
5205         } else {
5206           // This is an anonymous type definition within another anonymous type.
5207           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5208           // not part of standard C++.
5209           Diag(MemRecord->getLocation(),
5210                diag::ext_anonymous_record_with_anonymous_type)
5211             << Record->isUnion();
5212         }
5213       } else if (isa<AccessSpecDecl>(Mem)) {
5214         // Any access specifier is fine.
5215       } else if (isa<StaticAssertDecl>(Mem)) {
5216         // In C++1z, static_assert declarations are also fine.
5217       } else {
5218         // We have something that isn't a non-static data
5219         // member. Complain about it.
5220         unsigned DK = diag::err_anonymous_record_bad_member;
5221         if (isa<TypeDecl>(Mem))
5222           DK = diag::err_anonymous_record_with_type;
5223         else if (isa<FunctionDecl>(Mem))
5224           DK = diag::err_anonymous_record_with_function;
5225         else if (isa<VarDecl>(Mem))
5226           DK = diag::err_anonymous_record_with_static;
5227 
5228         // Visual C++ allows type definition in anonymous struct or union.
5229         if (getLangOpts().MicrosoftExt &&
5230             DK == diag::err_anonymous_record_with_type)
5231           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5232             << Record->isUnion();
5233         else {
5234           Diag(Mem->getLocation(), DK) << Record->isUnion();
5235           Invalid = true;
5236         }
5237       }
5238     }
5239 
5240     // C++11 [class.union]p8 (DR1460):
5241     //   At most one variant member of a union may have a
5242     //   brace-or-equal-initializer.
5243     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5244         Owner->isRecord())
5245       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5246                                 cast<CXXRecordDecl>(Record));
5247   }
5248 
5249   if (!Record->isUnion() && !Owner->isRecord()) {
5250     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5251       << getLangOpts().CPlusPlus;
5252     Invalid = true;
5253   }
5254 
5255   // C++ [dcl.dcl]p3:
5256   //   [If there are no declarators], and except for the declaration of an
5257   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5258   //   names into the program
5259   // C++ [class.mem]p2:
5260   //   each such member-declaration shall either declare at least one member
5261   //   name of the class or declare at least one unnamed bit-field
5262   //
5263   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5264   if (getLangOpts().CPlusPlus && Record->field_empty())
5265     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5266 
5267   // Mock up a declarator.
5268   Declarator Dc(DS, DeclaratorContext::Member);
5269   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5270   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5271 
5272   // Create a declaration for this anonymous struct/union.
5273   NamedDecl *Anon = nullptr;
5274   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5275     Anon = FieldDecl::Create(
5276         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5277         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5278         /*BitWidth=*/nullptr, /*Mutable=*/false,
5279         /*InitStyle=*/ICIS_NoInit);
5280     Anon->setAccess(AS);
5281     ProcessDeclAttributes(S, Anon, Dc);
5282 
5283     if (getLangOpts().CPlusPlus)
5284       FieldCollector->Add(cast<FieldDecl>(Anon));
5285   } else {
5286     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5287     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5288     if (SCSpec == DeclSpec::SCS_mutable) {
5289       // mutable can only appear on non-static class members, so it's always
5290       // an error here
5291       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5292       Invalid = true;
5293       SC = SC_None;
5294     }
5295 
5296     assert(DS.getAttributes().empty() && "No attribute expected");
5297     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5298                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5299                            Context.getTypeDeclType(Record), TInfo, SC);
5300 
5301     // Default-initialize the implicit variable. This initialization will be
5302     // trivial in almost all cases, except if a union member has an in-class
5303     // initializer:
5304     //   union { int n = 0; };
5305     ActOnUninitializedDecl(Anon);
5306   }
5307   Anon->setImplicit();
5308 
5309   // Mark this as an anonymous struct/union type.
5310   Record->setAnonymousStructOrUnion(true);
5311 
5312   // Add the anonymous struct/union object to the current
5313   // context. We'll be referencing this object when we refer to one of
5314   // its members.
5315   Owner->addDecl(Anon);
5316 
5317   // Inject the members of the anonymous struct/union into the owning
5318   // context and into the identifier resolver chain for name lookup
5319   // purposes.
5320   SmallVector<NamedDecl*, 2> Chain;
5321   Chain.push_back(Anon);
5322 
5323   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5324     Invalid = true;
5325 
5326   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5327     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5328       MangleNumberingContext *MCtx;
5329       Decl *ManglingContextDecl;
5330       std::tie(MCtx, ManglingContextDecl) =
5331           getCurrentMangleNumberContext(NewVD->getDeclContext());
5332       if (MCtx) {
5333         Context.setManglingNumber(
5334             NewVD, MCtx->getManglingNumber(
5335                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5336         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5337       }
5338     }
5339   }
5340 
5341   if (Invalid)
5342     Anon->setInvalidDecl();
5343 
5344   return Anon;
5345 }
5346 
5347 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5348 /// Microsoft C anonymous structure.
5349 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5350 /// Example:
5351 ///
5352 /// struct A { int a; };
5353 /// struct B { struct A; int b; };
5354 ///
5355 /// void foo() {
5356 ///   B var;
5357 ///   var.a = 3;
5358 /// }
5359 ///
5360 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5361                                            RecordDecl *Record) {
5362   assert(Record && "expected a record!");
5363 
5364   // Mock up a declarator.
5365   Declarator Dc(DS, DeclaratorContext::TypeName);
5366   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5367   assert(TInfo && "couldn't build declarator info for anonymous struct");
5368 
5369   auto *ParentDecl = cast<RecordDecl>(CurContext);
5370   QualType RecTy = Context.getTypeDeclType(Record);
5371 
5372   // Create a declaration for this anonymous struct.
5373   NamedDecl *Anon =
5374       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5375                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5376                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5377                         /*InitStyle=*/ICIS_NoInit);
5378   Anon->setImplicit();
5379 
5380   // Add the anonymous struct object to the current context.
5381   CurContext->addDecl(Anon);
5382 
5383   // Inject the members of the anonymous struct into the current
5384   // context and into the identifier resolver chain for name lookup
5385   // purposes.
5386   SmallVector<NamedDecl*, 2> Chain;
5387   Chain.push_back(Anon);
5388 
5389   RecordDecl *RecordDef = Record->getDefinition();
5390   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5391                                diag::err_field_incomplete_or_sizeless) ||
5392       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5393                                           AS_none, Chain)) {
5394     Anon->setInvalidDecl();
5395     ParentDecl->setInvalidDecl();
5396   }
5397 
5398   return Anon;
5399 }
5400 
5401 /// GetNameForDeclarator - Determine the full declaration name for the
5402 /// given Declarator.
5403 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5404   return GetNameFromUnqualifiedId(D.getName());
5405 }
5406 
5407 /// Retrieves the declaration name from a parsed unqualified-id.
5408 DeclarationNameInfo
5409 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5410   DeclarationNameInfo NameInfo;
5411   NameInfo.setLoc(Name.StartLocation);
5412 
5413   switch (Name.getKind()) {
5414 
5415   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5416   case UnqualifiedIdKind::IK_Identifier:
5417     NameInfo.setName(Name.Identifier);
5418     return NameInfo;
5419 
5420   case UnqualifiedIdKind::IK_DeductionGuideName: {
5421     // C++ [temp.deduct.guide]p3:
5422     //   The simple-template-id shall name a class template specialization.
5423     //   The template-name shall be the same identifier as the template-name
5424     //   of the simple-template-id.
5425     // These together intend to imply that the template-name shall name a
5426     // class template.
5427     // FIXME: template<typename T> struct X {};
5428     //        template<typename T> using Y = X<T>;
5429     //        Y(int) -> Y<int>;
5430     //   satisfies these rules but does not name a class template.
5431     TemplateName TN = Name.TemplateName.get().get();
5432     auto *Template = TN.getAsTemplateDecl();
5433     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5434       Diag(Name.StartLocation,
5435            diag::err_deduction_guide_name_not_class_template)
5436         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5437       if (Template)
5438         Diag(Template->getLocation(), diag::note_template_decl_here);
5439       return DeclarationNameInfo();
5440     }
5441 
5442     NameInfo.setName(
5443         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5444     return NameInfo;
5445   }
5446 
5447   case UnqualifiedIdKind::IK_OperatorFunctionId:
5448     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5449                                            Name.OperatorFunctionId.Operator));
5450     NameInfo.setCXXOperatorNameRange(SourceRange(
5451         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5452     return NameInfo;
5453 
5454   case UnqualifiedIdKind::IK_LiteralOperatorId:
5455     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5456                                                            Name.Identifier));
5457     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5458     return NameInfo;
5459 
5460   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5461     TypeSourceInfo *TInfo;
5462     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5463     if (Ty.isNull())
5464       return DeclarationNameInfo();
5465     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5466                                                Context.getCanonicalType(Ty)));
5467     NameInfo.setNamedTypeInfo(TInfo);
5468     return NameInfo;
5469   }
5470 
5471   case UnqualifiedIdKind::IK_ConstructorName: {
5472     TypeSourceInfo *TInfo;
5473     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5474     if (Ty.isNull())
5475       return DeclarationNameInfo();
5476     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5477                                               Context.getCanonicalType(Ty)));
5478     NameInfo.setNamedTypeInfo(TInfo);
5479     return NameInfo;
5480   }
5481 
5482   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5483     // In well-formed code, we can only have a constructor
5484     // template-id that refers to the current context, so go there
5485     // to find the actual type being constructed.
5486     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5487     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5488       return DeclarationNameInfo();
5489 
5490     // Determine the type of the class being constructed.
5491     QualType CurClassType = Context.getTypeDeclType(CurClass);
5492 
5493     // FIXME: Check two things: that the template-id names the same type as
5494     // CurClassType, and that the template-id does not occur when the name
5495     // was qualified.
5496 
5497     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5498                                     Context.getCanonicalType(CurClassType)));
5499     // FIXME: should we retrieve TypeSourceInfo?
5500     NameInfo.setNamedTypeInfo(nullptr);
5501     return NameInfo;
5502   }
5503 
5504   case UnqualifiedIdKind::IK_DestructorName: {
5505     TypeSourceInfo *TInfo;
5506     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5507     if (Ty.isNull())
5508       return DeclarationNameInfo();
5509     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5510                                               Context.getCanonicalType(Ty)));
5511     NameInfo.setNamedTypeInfo(TInfo);
5512     return NameInfo;
5513   }
5514 
5515   case UnqualifiedIdKind::IK_TemplateId: {
5516     TemplateName TName = Name.TemplateId->Template.get();
5517     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5518     return Context.getNameForTemplate(TName, TNameLoc);
5519   }
5520 
5521   } // switch (Name.getKind())
5522 
5523   llvm_unreachable("Unknown name kind");
5524 }
5525 
5526 static QualType getCoreType(QualType Ty) {
5527   do {
5528     if (Ty->isPointerType() || Ty->isReferenceType())
5529       Ty = Ty->getPointeeType();
5530     else if (Ty->isArrayType())
5531       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5532     else
5533       return Ty.withoutLocalFastQualifiers();
5534   } while (true);
5535 }
5536 
5537 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5538 /// and Definition have "nearly" matching parameters. This heuristic is
5539 /// used to improve diagnostics in the case where an out-of-line function
5540 /// definition doesn't match any declaration within the class or namespace.
5541 /// Also sets Params to the list of indices to the parameters that differ
5542 /// between the declaration and the definition. If hasSimilarParameters
5543 /// returns true and Params is empty, then all of the parameters match.
5544 static bool hasSimilarParameters(ASTContext &Context,
5545                                      FunctionDecl *Declaration,
5546                                      FunctionDecl *Definition,
5547                                      SmallVectorImpl<unsigned> &Params) {
5548   Params.clear();
5549   if (Declaration->param_size() != Definition->param_size())
5550     return false;
5551   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5552     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5553     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5554 
5555     // The parameter types are identical
5556     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5557       continue;
5558 
5559     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5560     QualType DefParamBaseTy = getCoreType(DefParamTy);
5561     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5562     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5563 
5564     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5565         (DeclTyName && DeclTyName == DefTyName))
5566       Params.push_back(Idx);
5567     else  // The two parameters aren't even close
5568       return false;
5569   }
5570 
5571   return true;
5572 }
5573 
5574 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5575 /// declarator needs to be rebuilt in the current instantiation.
5576 /// Any bits of declarator which appear before the name are valid for
5577 /// consideration here.  That's specifically the type in the decl spec
5578 /// and the base type in any member-pointer chunks.
5579 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5580                                                     DeclarationName Name) {
5581   // The types we specifically need to rebuild are:
5582   //   - typenames, typeofs, and decltypes
5583   //   - types which will become injected class names
5584   // Of course, we also need to rebuild any type referencing such a
5585   // type.  It's safest to just say "dependent", but we call out a
5586   // few cases here.
5587 
5588   DeclSpec &DS = D.getMutableDeclSpec();
5589   switch (DS.getTypeSpecType()) {
5590   case DeclSpec::TST_typename:
5591   case DeclSpec::TST_typeofType:
5592   case DeclSpec::TST_underlyingType:
5593   case DeclSpec::TST_atomic: {
5594     // Grab the type from the parser.
5595     TypeSourceInfo *TSI = nullptr;
5596     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5597     if (T.isNull() || !T->isInstantiationDependentType()) break;
5598 
5599     // Make sure there's a type source info.  This isn't really much
5600     // of a waste; most dependent types should have type source info
5601     // attached already.
5602     if (!TSI)
5603       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5604 
5605     // Rebuild the type in the current instantiation.
5606     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5607     if (!TSI) return true;
5608 
5609     // Store the new type back in the decl spec.
5610     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5611     DS.UpdateTypeRep(LocType);
5612     break;
5613   }
5614 
5615   case DeclSpec::TST_decltype:
5616   case DeclSpec::TST_typeofExpr: {
5617     Expr *E = DS.getRepAsExpr();
5618     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5619     if (Result.isInvalid()) return true;
5620     DS.UpdateExprRep(Result.get());
5621     break;
5622   }
5623 
5624   default:
5625     // Nothing to do for these decl specs.
5626     break;
5627   }
5628 
5629   // It doesn't matter what order we do this in.
5630   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5631     DeclaratorChunk &Chunk = D.getTypeObject(I);
5632 
5633     // The only type information in the declarator which can come
5634     // before the declaration name is the base type of a member
5635     // pointer.
5636     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5637       continue;
5638 
5639     // Rebuild the scope specifier in-place.
5640     CXXScopeSpec &SS = Chunk.Mem.Scope();
5641     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5642       return true;
5643   }
5644 
5645   return false;
5646 }
5647 
5648 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5649   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5650   // of system decl.
5651   if (D->getPreviousDecl() || D->isImplicit())
5652     return;
5653   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5654   if (Status != ReservedIdentifierStatus::NotReserved &&
5655       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5656     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5657         << D << static_cast<int>(Status);
5658 }
5659 
5660 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5661   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5662   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5663 
5664   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5665       Dcl && Dcl->getDeclContext()->isFileContext())
5666     Dcl->setTopLevelDeclInObjCContainer();
5667 
5668   return Dcl;
5669 }
5670 
5671 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5672 ///   If T is the name of a class, then each of the following shall have a
5673 ///   name different from T:
5674 ///     - every static data member of class T;
5675 ///     - every member function of class T
5676 ///     - every member of class T that is itself a type;
5677 /// \returns true if the declaration name violates these rules.
5678 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5679                                    DeclarationNameInfo NameInfo) {
5680   DeclarationName Name = NameInfo.getName();
5681 
5682   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5683   while (Record && Record->isAnonymousStructOrUnion())
5684     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5685   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5686     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5687     return true;
5688   }
5689 
5690   return false;
5691 }
5692 
5693 /// Diagnose a declaration whose declarator-id has the given
5694 /// nested-name-specifier.
5695 ///
5696 /// \param SS The nested-name-specifier of the declarator-id.
5697 ///
5698 /// \param DC The declaration context to which the nested-name-specifier
5699 /// resolves.
5700 ///
5701 /// \param Name The name of the entity being declared.
5702 ///
5703 /// \param Loc The location of the name of the entity being declared.
5704 ///
5705 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5706 /// we're declaring an explicit / partial specialization / instantiation.
5707 ///
5708 /// \returns true if we cannot safely recover from this error, false otherwise.
5709 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5710                                         DeclarationName Name,
5711                                         SourceLocation Loc, bool IsTemplateId) {
5712   DeclContext *Cur = CurContext;
5713   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5714     Cur = Cur->getParent();
5715 
5716   // If the user provided a superfluous scope specifier that refers back to the
5717   // class in which the entity is already declared, diagnose and ignore it.
5718   //
5719   // class X {
5720   //   void X::f();
5721   // };
5722   //
5723   // Note, it was once ill-formed to give redundant qualification in all
5724   // contexts, but that rule was removed by DR482.
5725   if (Cur->Equals(DC)) {
5726     if (Cur->isRecord()) {
5727       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5728                                       : diag::err_member_extra_qualification)
5729         << Name << FixItHint::CreateRemoval(SS.getRange());
5730       SS.clear();
5731     } else {
5732       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5733     }
5734     return false;
5735   }
5736 
5737   // Check whether the qualifying scope encloses the scope of the original
5738   // declaration. For a template-id, we perform the checks in
5739   // CheckTemplateSpecializationScope.
5740   if (!Cur->Encloses(DC) && !IsTemplateId) {
5741     if (Cur->isRecord())
5742       Diag(Loc, diag::err_member_qualification)
5743         << Name << SS.getRange();
5744     else if (isa<TranslationUnitDecl>(DC))
5745       Diag(Loc, diag::err_invalid_declarator_global_scope)
5746         << Name << SS.getRange();
5747     else if (isa<FunctionDecl>(Cur))
5748       Diag(Loc, diag::err_invalid_declarator_in_function)
5749         << Name << SS.getRange();
5750     else if (isa<BlockDecl>(Cur))
5751       Diag(Loc, diag::err_invalid_declarator_in_block)
5752         << Name << SS.getRange();
5753     else
5754       Diag(Loc, diag::err_invalid_declarator_scope)
5755       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5756 
5757     return true;
5758   }
5759 
5760   if (Cur->isRecord()) {
5761     // Cannot qualify members within a class.
5762     Diag(Loc, diag::err_member_qualification)
5763       << Name << SS.getRange();
5764     SS.clear();
5765 
5766     // C++ constructors and destructors with incorrect scopes can break
5767     // our AST invariants by having the wrong underlying types. If
5768     // that's the case, then drop this declaration entirely.
5769     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5770          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5771         !Context.hasSameType(Name.getCXXNameType(),
5772                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5773       return true;
5774 
5775     return false;
5776   }
5777 
5778   // C++11 [dcl.meaning]p1:
5779   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5780   //   not begin with a decltype-specifer"
5781   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5782   while (SpecLoc.getPrefix())
5783     SpecLoc = SpecLoc.getPrefix();
5784   if (isa_and_nonnull<DecltypeType>(
5785           SpecLoc.getNestedNameSpecifier()->getAsType()))
5786     Diag(Loc, diag::err_decltype_in_declarator)
5787       << SpecLoc.getTypeLoc().getSourceRange();
5788 
5789   return false;
5790 }
5791 
5792 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5793                                   MultiTemplateParamsArg TemplateParamLists) {
5794   // TODO: consider using NameInfo for diagnostic.
5795   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5796   DeclarationName Name = NameInfo.getName();
5797 
5798   // All of these full declarators require an identifier.  If it doesn't have
5799   // one, the ParsedFreeStandingDeclSpec action should be used.
5800   if (D.isDecompositionDeclarator()) {
5801     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5802   } else if (!Name) {
5803     if (!D.isInvalidType())  // Reject this if we think it is valid.
5804       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5805           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5806     return nullptr;
5807   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5808     return nullptr;
5809 
5810   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5811   // we find one that is.
5812   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5813          (S->getFlags() & Scope::TemplateParamScope) != 0)
5814     S = S->getParent();
5815 
5816   DeclContext *DC = CurContext;
5817   if (D.getCXXScopeSpec().isInvalid())
5818     D.setInvalidType();
5819   else if (D.getCXXScopeSpec().isSet()) {
5820     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5821                                         UPPC_DeclarationQualifier))
5822       return nullptr;
5823 
5824     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5825     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5826     if (!DC || isa<EnumDecl>(DC)) {
5827       // If we could not compute the declaration context, it's because the
5828       // declaration context is dependent but does not refer to a class,
5829       // class template, or class template partial specialization. Complain
5830       // and return early, to avoid the coming semantic disaster.
5831       Diag(D.getIdentifierLoc(),
5832            diag::err_template_qualified_declarator_no_match)
5833         << D.getCXXScopeSpec().getScopeRep()
5834         << D.getCXXScopeSpec().getRange();
5835       return nullptr;
5836     }
5837     bool IsDependentContext = DC->isDependentContext();
5838 
5839     if (!IsDependentContext &&
5840         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5841       return nullptr;
5842 
5843     // If a class is incomplete, do not parse entities inside it.
5844     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5845       Diag(D.getIdentifierLoc(),
5846            diag::err_member_def_undefined_record)
5847         << Name << DC << D.getCXXScopeSpec().getRange();
5848       return nullptr;
5849     }
5850     if (!D.getDeclSpec().isFriendSpecified()) {
5851       if (diagnoseQualifiedDeclaration(
5852               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5853               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5854         if (DC->isRecord())
5855           return nullptr;
5856 
5857         D.setInvalidType();
5858       }
5859     }
5860 
5861     // Check whether we need to rebuild the type of the given
5862     // declaration in the current instantiation.
5863     if (EnteringContext && IsDependentContext &&
5864         TemplateParamLists.size() != 0) {
5865       ContextRAII SavedContext(*this, DC);
5866       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5867         D.setInvalidType();
5868     }
5869   }
5870 
5871   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5872   QualType R = TInfo->getType();
5873 
5874   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5875                                       UPPC_DeclarationType))
5876     D.setInvalidType();
5877 
5878   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5879                         forRedeclarationInCurContext());
5880 
5881   // See if this is a redefinition of a variable in the same scope.
5882   if (!D.getCXXScopeSpec().isSet()) {
5883     bool IsLinkageLookup = false;
5884     bool CreateBuiltins = false;
5885 
5886     // If the declaration we're planning to build will be a function
5887     // or object with linkage, then look for another declaration with
5888     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5889     //
5890     // If the declaration we're planning to build will be declared with
5891     // external linkage in the translation unit, create any builtin with
5892     // the same name.
5893     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5894       /* Do nothing*/;
5895     else if (CurContext->isFunctionOrMethod() &&
5896              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5897               R->isFunctionType())) {
5898       IsLinkageLookup = true;
5899       CreateBuiltins =
5900           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5901     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5902                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5903       CreateBuiltins = true;
5904 
5905     if (IsLinkageLookup) {
5906       Previous.clear(LookupRedeclarationWithLinkage);
5907       Previous.setRedeclarationKind(ForExternalRedeclaration);
5908     }
5909 
5910     LookupName(Previous, S, CreateBuiltins);
5911   } else { // Something like "int foo::x;"
5912     LookupQualifiedName(Previous, DC);
5913 
5914     // C++ [dcl.meaning]p1:
5915     //   When the declarator-id is qualified, the declaration shall refer to a
5916     //  previously declared member of the class or namespace to which the
5917     //  qualifier refers (or, in the case of a namespace, of an element of the
5918     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5919     //  thereof; [...]
5920     //
5921     // Note that we already checked the context above, and that we do not have
5922     // enough information to make sure that Previous contains the declaration
5923     // we want to match. For example, given:
5924     //
5925     //   class X {
5926     //     void f();
5927     //     void f(float);
5928     //   };
5929     //
5930     //   void X::f(int) { } // ill-formed
5931     //
5932     // In this case, Previous will point to the overload set
5933     // containing the two f's declared in X, but neither of them
5934     // matches.
5935 
5936     // C++ [dcl.meaning]p1:
5937     //   [...] the member shall not merely have been introduced by a
5938     //   using-declaration in the scope of the class or namespace nominated by
5939     //   the nested-name-specifier of the declarator-id.
5940     RemoveUsingDecls(Previous);
5941   }
5942 
5943   if (Previous.isSingleResult() &&
5944       Previous.getFoundDecl()->isTemplateParameter()) {
5945     // Maybe we will complain about the shadowed template parameter.
5946     if (!D.isInvalidType())
5947       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5948                                       Previous.getFoundDecl());
5949 
5950     // Just pretend that we didn't see the previous declaration.
5951     Previous.clear();
5952   }
5953 
5954   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5955     // Forget that the previous declaration is the injected-class-name.
5956     Previous.clear();
5957 
5958   // In C++, the previous declaration we find might be a tag type
5959   // (class or enum). In this case, the new declaration will hide the
5960   // tag type. Note that this applies to functions, function templates, and
5961   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5962   if (Previous.isSingleTagDecl() &&
5963       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5964       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5965     Previous.clear();
5966 
5967   // Check that there are no default arguments other than in the parameters
5968   // of a function declaration (C++ only).
5969   if (getLangOpts().CPlusPlus)
5970     CheckExtraCXXDefaultArguments(D);
5971 
5972   NamedDecl *New;
5973 
5974   bool AddToScope = true;
5975   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5976     if (TemplateParamLists.size()) {
5977       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5978       return nullptr;
5979     }
5980 
5981     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5982   } else if (R->isFunctionType()) {
5983     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5984                                   TemplateParamLists,
5985                                   AddToScope);
5986   } else {
5987     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5988                                   AddToScope);
5989   }
5990 
5991   if (!New)
5992     return nullptr;
5993 
5994   // If this has an identifier and is not a function template specialization,
5995   // add it to the scope stack.
5996   if (New->getDeclName() && AddToScope)
5997     PushOnScopeChains(New, S);
5998 
5999   if (isInOpenMPDeclareTargetContext())
6000     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6001 
6002   return New;
6003 }
6004 
6005 /// Helper method to turn variable array types into constant array
6006 /// types in certain situations which would otherwise be errors (for
6007 /// GCC compatibility).
6008 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6009                                                     ASTContext &Context,
6010                                                     bool &SizeIsNegative,
6011                                                     llvm::APSInt &Oversized) {
6012   // This method tries to turn a variable array into a constant
6013   // array even when the size isn't an ICE.  This is necessary
6014   // for compatibility with code that depends on gcc's buggy
6015   // constant expression folding, like struct {char x[(int)(char*)2];}
6016   SizeIsNegative = false;
6017   Oversized = 0;
6018 
6019   if (T->isDependentType())
6020     return QualType();
6021 
6022   QualifierCollector Qs;
6023   const Type *Ty = Qs.strip(T);
6024 
6025   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6026     QualType Pointee = PTy->getPointeeType();
6027     QualType FixedType =
6028         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6029                                             Oversized);
6030     if (FixedType.isNull()) return FixedType;
6031     FixedType = Context.getPointerType(FixedType);
6032     return Qs.apply(Context, FixedType);
6033   }
6034   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6035     QualType Inner = PTy->getInnerType();
6036     QualType FixedType =
6037         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6038                                             Oversized);
6039     if (FixedType.isNull()) return FixedType;
6040     FixedType = Context.getParenType(FixedType);
6041     return Qs.apply(Context, FixedType);
6042   }
6043 
6044   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6045   if (!VLATy)
6046     return QualType();
6047 
6048   QualType ElemTy = VLATy->getElementType();
6049   if (ElemTy->isVariablyModifiedType()) {
6050     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6051                                                  SizeIsNegative, Oversized);
6052     if (ElemTy.isNull())
6053       return QualType();
6054   }
6055 
6056   Expr::EvalResult Result;
6057   if (!VLATy->getSizeExpr() ||
6058       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6059     return QualType();
6060 
6061   llvm::APSInt Res = Result.Val.getInt();
6062 
6063   // Check whether the array size is negative.
6064   if (Res.isSigned() && Res.isNegative()) {
6065     SizeIsNegative = true;
6066     return QualType();
6067   }
6068 
6069   // Check whether the array is too large to be addressed.
6070   unsigned ActiveSizeBits =
6071       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6072        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6073           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6074           : Res.getActiveBits();
6075   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6076     Oversized = Res;
6077     return QualType();
6078   }
6079 
6080   QualType FoldedArrayType = Context.getConstantArrayType(
6081       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6082   return Qs.apply(Context, FoldedArrayType);
6083 }
6084 
6085 static void
6086 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6087   SrcTL = SrcTL.getUnqualifiedLoc();
6088   DstTL = DstTL.getUnqualifiedLoc();
6089   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6090     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6091     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6092                                       DstPTL.getPointeeLoc());
6093     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6094     return;
6095   }
6096   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6097     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6098     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6099                                       DstPTL.getInnerLoc());
6100     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6101     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6102     return;
6103   }
6104   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6105   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6106   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6107   TypeLoc DstElemTL = DstATL.getElementLoc();
6108   if (VariableArrayTypeLoc SrcElemATL =
6109           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6110     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6111     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6112   } else {
6113     DstElemTL.initializeFullCopy(SrcElemTL);
6114   }
6115   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6116   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6117   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6118 }
6119 
6120 /// Helper method to turn variable array types into constant array
6121 /// types in certain situations which would otherwise be errors (for
6122 /// GCC compatibility).
6123 static TypeSourceInfo*
6124 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6125                                               ASTContext &Context,
6126                                               bool &SizeIsNegative,
6127                                               llvm::APSInt &Oversized) {
6128   QualType FixedTy
6129     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6130                                           SizeIsNegative, Oversized);
6131   if (FixedTy.isNull())
6132     return nullptr;
6133   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6134   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6135                                     FixedTInfo->getTypeLoc());
6136   return FixedTInfo;
6137 }
6138 
6139 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6140 /// true if we were successful.
6141 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6142                                            QualType &T, SourceLocation Loc,
6143                                            unsigned FailedFoldDiagID) {
6144   bool SizeIsNegative;
6145   llvm::APSInt Oversized;
6146   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6147       TInfo, Context, SizeIsNegative, Oversized);
6148   if (FixedTInfo) {
6149     Diag(Loc, diag::ext_vla_folded_to_constant);
6150     TInfo = FixedTInfo;
6151     T = FixedTInfo->getType();
6152     return true;
6153   }
6154 
6155   if (SizeIsNegative)
6156     Diag(Loc, diag::err_typecheck_negative_array_size);
6157   else if (Oversized.getBoolValue())
6158     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6159   else if (FailedFoldDiagID)
6160     Diag(Loc, FailedFoldDiagID);
6161   return false;
6162 }
6163 
6164 /// Register the given locally-scoped extern "C" declaration so
6165 /// that it can be found later for redeclarations. We include any extern "C"
6166 /// declaration that is not visible in the translation unit here, not just
6167 /// function-scope declarations.
6168 void
6169 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6170   if (!getLangOpts().CPlusPlus &&
6171       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6172     // Don't need to track declarations in the TU in C.
6173     return;
6174 
6175   // Note that we have a locally-scoped external with this name.
6176   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6177 }
6178 
6179 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6180   // FIXME: We can have multiple results via __attribute__((overloadable)).
6181   auto Result = Context.getExternCContextDecl()->lookup(Name);
6182   return Result.empty() ? nullptr : *Result.begin();
6183 }
6184 
6185 /// Diagnose function specifiers on a declaration of an identifier that
6186 /// does not identify a function.
6187 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6188   // FIXME: We should probably indicate the identifier in question to avoid
6189   // confusion for constructs like "virtual int a(), b;"
6190   if (DS.isVirtualSpecified())
6191     Diag(DS.getVirtualSpecLoc(),
6192          diag::err_virtual_non_function);
6193 
6194   if (DS.hasExplicitSpecifier())
6195     Diag(DS.getExplicitSpecLoc(),
6196          diag::err_explicit_non_function);
6197 
6198   if (DS.isNoreturnSpecified())
6199     Diag(DS.getNoreturnSpecLoc(),
6200          diag::err_noreturn_non_function);
6201 }
6202 
6203 NamedDecl*
6204 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6205                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6206   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6207   if (D.getCXXScopeSpec().isSet()) {
6208     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6209       << D.getCXXScopeSpec().getRange();
6210     D.setInvalidType();
6211     // Pretend we didn't see the scope specifier.
6212     DC = CurContext;
6213     Previous.clear();
6214   }
6215 
6216   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6217 
6218   if (D.getDeclSpec().isInlineSpecified())
6219     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6220         << getLangOpts().CPlusPlus17;
6221   if (D.getDeclSpec().hasConstexprSpecifier())
6222     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6223         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6224 
6225   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6226     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6227       Diag(D.getName().StartLocation,
6228            diag::err_deduction_guide_invalid_specifier)
6229           << "typedef";
6230     else
6231       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6232           << D.getName().getSourceRange();
6233     return nullptr;
6234   }
6235 
6236   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6237   if (!NewTD) return nullptr;
6238 
6239   // Handle attributes prior to checking for duplicates in MergeVarDecl
6240   ProcessDeclAttributes(S, NewTD, D);
6241 
6242   CheckTypedefForVariablyModifiedType(S, NewTD);
6243 
6244   bool Redeclaration = D.isRedeclaration();
6245   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6246   D.setRedeclaration(Redeclaration);
6247   return ND;
6248 }
6249 
6250 void
6251 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6252   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6253   // then it shall have block scope.
6254   // Note that variably modified types must be fixed before merging the decl so
6255   // that redeclarations will match.
6256   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6257   QualType T = TInfo->getType();
6258   if (T->isVariablyModifiedType()) {
6259     setFunctionHasBranchProtectedScope();
6260 
6261     if (S->getFnParent() == nullptr) {
6262       bool SizeIsNegative;
6263       llvm::APSInt Oversized;
6264       TypeSourceInfo *FixedTInfo =
6265         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6266                                                       SizeIsNegative,
6267                                                       Oversized);
6268       if (FixedTInfo) {
6269         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6270         NewTD->setTypeSourceInfo(FixedTInfo);
6271       } else {
6272         if (SizeIsNegative)
6273           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6274         else if (T->isVariableArrayType())
6275           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6276         else if (Oversized.getBoolValue())
6277           Diag(NewTD->getLocation(), diag::err_array_too_large)
6278             << toString(Oversized, 10);
6279         else
6280           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6281         NewTD->setInvalidDecl();
6282       }
6283     }
6284   }
6285 }
6286 
6287 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6288 /// declares a typedef-name, either using the 'typedef' type specifier or via
6289 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6290 NamedDecl*
6291 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6292                            LookupResult &Previous, bool &Redeclaration) {
6293 
6294   // Find the shadowed declaration before filtering for scope.
6295   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6296 
6297   // Merge the decl with the existing one if appropriate. If the decl is
6298   // in an outer scope, it isn't the same thing.
6299   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6300                        /*AllowInlineNamespace*/false);
6301   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6302   if (!Previous.empty()) {
6303     Redeclaration = true;
6304     MergeTypedefNameDecl(S, NewTD, Previous);
6305   } else {
6306     inferGslPointerAttribute(NewTD);
6307   }
6308 
6309   if (ShadowedDecl && !Redeclaration)
6310     CheckShadow(NewTD, ShadowedDecl, Previous);
6311 
6312   // If this is the C FILE type, notify the AST context.
6313   if (IdentifierInfo *II = NewTD->getIdentifier())
6314     if (!NewTD->isInvalidDecl() &&
6315         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6316       if (II->isStr("FILE"))
6317         Context.setFILEDecl(NewTD);
6318       else if (II->isStr("jmp_buf"))
6319         Context.setjmp_bufDecl(NewTD);
6320       else if (II->isStr("sigjmp_buf"))
6321         Context.setsigjmp_bufDecl(NewTD);
6322       else if (II->isStr("ucontext_t"))
6323         Context.setucontext_tDecl(NewTD);
6324     }
6325 
6326   return NewTD;
6327 }
6328 
6329 /// Determines whether the given declaration is an out-of-scope
6330 /// previous declaration.
6331 ///
6332 /// This routine should be invoked when name lookup has found a
6333 /// previous declaration (PrevDecl) that is not in the scope where a
6334 /// new declaration by the same name is being introduced. If the new
6335 /// declaration occurs in a local scope, previous declarations with
6336 /// linkage may still be considered previous declarations (C99
6337 /// 6.2.2p4-5, C++ [basic.link]p6).
6338 ///
6339 /// \param PrevDecl the previous declaration found by name
6340 /// lookup
6341 ///
6342 /// \param DC the context in which the new declaration is being
6343 /// declared.
6344 ///
6345 /// \returns true if PrevDecl is an out-of-scope previous declaration
6346 /// for a new delcaration with the same name.
6347 static bool
6348 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6349                                 ASTContext &Context) {
6350   if (!PrevDecl)
6351     return false;
6352 
6353   if (!PrevDecl->hasLinkage())
6354     return false;
6355 
6356   if (Context.getLangOpts().CPlusPlus) {
6357     // C++ [basic.link]p6:
6358     //   If there is a visible declaration of an entity with linkage
6359     //   having the same name and type, ignoring entities declared
6360     //   outside the innermost enclosing namespace scope, the block
6361     //   scope declaration declares that same entity and receives the
6362     //   linkage of the previous declaration.
6363     DeclContext *OuterContext = DC->getRedeclContext();
6364     if (!OuterContext->isFunctionOrMethod())
6365       // This rule only applies to block-scope declarations.
6366       return false;
6367 
6368     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6369     if (PrevOuterContext->isRecord())
6370       // We found a member function: ignore it.
6371       return false;
6372 
6373     // Find the innermost enclosing namespace for the new and
6374     // previous declarations.
6375     OuterContext = OuterContext->getEnclosingNamespaceContext();
6376     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6377 
6378     // The previous declaration is in a different namespace, so it
6379     // isn't the same function.
6380     if (!OuterContext->Equals(PrevOuterContext))
6381       return false;
6382   }
6383 
6384   return true;
6385 }
6386 
6387 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6388   CXXScopeSpec &SS = D.getCXXScopeSpec();
6389   if (!SS.isSet()) return;
6390   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6391 }
6392 
6393 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6394   QualType type = decl->getType();
6395   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6396   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6397     // Various kinds of declaration aren't allowed to be __autoreleasing.
6398     unsigned kind = -1U;
6399     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6400       if (var->hasAttr<BlocksAttr>())
6401         kind = 0; // __block
6402       else if (!var->hasLocalStorage())
6403         kind = 1; // global
6404     } else if (isa<ObjCIvarDecl>(decl)) {
6405       kind = 3; // ivar
6406     } else if (isa<FieldDecl>(decl)) {
6407       kind = 2; // field
6408     }
6409 
6410     if (kind != -1U) {
6411       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6412         << kind;
6413     }
6414   } else if (lifetime == Qualifiers::OCL_None) {
6415     // Try to infer lifetime.
6416     if (!type->isObjCLifetimeType())
6417       return false;
6418 
6419     lifetime = type->getObjCARCImplicitLifetime();
6420     type = Context.getLifetimeQualifiedType(type, lifetime);
6421     decl->setType(type);
6422   }
6423 
6424   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6425     // Thread-local variables cannot have lifetime.
6426     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6427         var->getTLSKind()) {
6428       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6429         << var->getType();
6430       return true;
6431     }
6432   }
6433 
6434   return false;
6435 }
6436 
6437 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6438   if (Decl->getType().hasAddressSpace())
6439     return;
6440   if (Decl->getType()->isDependentType())
6441     return;
6442   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6443     QualType Type = Var->getType();
6444     if (Type->isSamplerT() || Type->isVoidType())
6445       return;
6446     LangAS ImplAS = LangAS::opencl_private;
6447     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6448     // __opencl_c_program_scope_global_variables feature, the address space
6449     // for a variable at program scope or a static or extern variable inside
6450     // a function are inferred to be __global.
6451     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6452         Var->hasGlobalStorage())
6453       ImplAS = LangAS::opencl_global;
6454     // If the original type from a decayed type is an array type and that array
6455     // type has no address space yet, deduce it now.
6456     if (auto DT = dyn_cast<DecayedType>(Type)) {
6457       auto OrigTy = DT->getOriginalType();
6458       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6459         // Add the address space to the original array type and then propagate
6460         // that to the element type through `getAsArrayType`.
6461         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6462         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6463         // Re-generate the decayed type.
6464         Type = Context.getDecayedType(OrigTy);
6465       }
6466     }
6467     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6468     // Apply any qualifiers (including address space) from the array type to
6469     // the element type. This implements C99 6.7.3p8: "If the specification of
6470     // an array type includes any type qualifiers, the element type is so
6471     // qualified, not the array type."
6472     if (Type->isArrayType())
6473       Type = QualType(Context.getAsArrayType(Type), 0);
6474     Decl->setType(Type);
6475   }
6476 }
6477 
6478 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6479   // Ensure that an auto decl is deduced otherwise the checks below might cache
6480   // the wrong linkage.
6481   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6482 
6483   // 'weak' only applies to declarations with external linkage.
6484   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6485     if (!ND.isExternallyVisible()) {
6486       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6487       ND.dropAttr<WeakAttr>();
6488     }
6489   }
6490   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6491     if (ND.isExternallyVisible()) {
6492       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6493       ND.dropAttr<WeakRefAttr>();
6494       ND.dropAttr<AliasAttr>();
6495     }
6496   }
6497 
6498   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6499     if (VD->hasInit()) {
6500       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6501         assert(VD->isThisDeclarationADefinition() &&
6502                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6503         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6504         VD->dropAttr<AliasAttr>();
6505       }
6506     }
6507   }
6508 
6509   // 'selectany' only applies to externally visible variable declarations.
6510   // It does not apply to functions.
6511   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6512     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6513       S.Diag(Attr->getLocation(),
6514              diag::err_attribute_selectany_non_extern_data);
6515       ND.dropAttr<SelectAnyAttr>();
6516     }
6517   }
6518 
6519   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6520     auto *VD = dyn_cast<VarDecl>(&ND);
6521     bool IsAnonymousNS = false;
6522     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6523     if (VD) {
6524       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6525       while (NS && !IsAnonymousNS) {
6526         IsAnonymousNS = NS->isAnonymousNamespace();
6527         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6528       }
6529     }
6530     // dll attributes require external linkage. Static locals may have external
6531     // linkage but still cannot be explicitly imported or exported.
6532     // In Microsoft mode, a variable defined in anonymous namespace must have
6533     // external linkage in order to be exported.
6534     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6535     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6536         (!AnonNSInMicrosoftMode &&
6537          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6538       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6539         << &ND << Attr;
6540       ND.setInvalidDecl();
6541     }
6542   }
6543 
6544   // Check the attributes on the function type, if any.
6545   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6546     // Don't declare this variable in the second operand of the for-statement;
6547     // GCC miscompiles that by ending its lifetime before evaluating the
6548     // third operand. See gcc.gnu.org/PR86769.
6549     AttributedTypeLoc ATL;
6550     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6551          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6552          TL = ATL.getModifiedLoc()) {
6553       // The [[lifetimebound]] attribute can be applied to the implicit object
6554       // parameter of a non-static member function (other than a ctor or dtor)
6555       // by applying it to the function type.
6556       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6557         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6558         if (!MD || MD->isStatic()) {
6559           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6560               << !MD << A->getRange();
6561         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6562           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6563               << isa<CXXDestructorDecl>(MD) << A->getRange();
6564         }
6565       }
6566     }
6567   }
6568 }
6569 
6570 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6571                                            NamedDecl *NewDecl,
6572                                            bool IsSpecialization,
6573                                            bool IsDefinition) {
6574   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6575     return;
6576 
6577   bool IsTemplate = false;
6578   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6579     OldDecl = OldTD->getTemplatedDecl();
6580     IsTemplate = true;
6581     if (!IsSpecialization)
6582       IsDefinition = false;
6583   }
6584   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6585     NewDecl = NewTD->getTemplatedDecl();
6586     IsTemplate = true;
6587   }
6588 
6589   if (!OldDecl || !NewDecl)
6590     return;
6591 
6592   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6593   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6594   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6595   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6596 
6597   // dllimport and dllexport are inheritable attributes so we have to exclude
6598   // inherited attribute instances.
6599   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6600                     (NewExportAttr && !NewExportAttr->isInherited());
6601 
6602   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6603   // the only exception being explicit specializations.
6604   // Implicitly generated declarations are also excluded for now because there
6605   // is no other way to switch these to use dllimport or dllexport.
6606   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6607 
6608   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6609     // Allow with a warning for free functions and global variables.
6610     bool JustWarn = false;
6611     if (!OldDecl->isCXXClassMember()) {
6612       auto *VD = dyn_cast<VarDecl>(OldDecl);
6613       if (VD && !VD->getDescribedVarTemplate())
6614         JustWarn = true;
6615       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6616       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6617         JustWarn = true;
6618     }
6619 
6620     // We cannot change a declaration that's been used because IR has already
6621     // been emitted. Dllimported functions will still work though (modulo
6622     // address equality) as they can use the thunk.
6623     if (OldDecl->isUsed())
6624       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6625         JustWarn = false;
6626 
6627     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6628                                : diag::err_attribute_dll_redeclaration;
6629     S.Diag(NewDecl->getLocation(), DiagID)
6630         << NewDecl
6631         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6632     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6633     if (!JustWarn) {
6634       NewDecl->setInvalidDecl();
6635       return;
6636     }
6637   }
6638 
6639   // A redeclaration is not allowed to drop a dllimport attribute, the only
6640   // exceptions being inline function definitions (except for function
6641   // templates), local extern declarations, qualified friend declarations or
6642   // special MSVC extension: in the last case, the declaration is treated as if
6643   // it were marked dllexport.
6644   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6645   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6646   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6647     // Ignore static data because out-of-line definitions are diagnosed
6648     // separately.
6649     IsStaticDataMember = VD->isStaticDataMember();
6650     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6651                    VarDecl::DeclarationOnly;
6652   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6653     IsInline = FD->isInlined();
6654     IsQualifiedFriend = FD->getQualifier() &&
6655                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6656   }
6657 
6658   if (OldImportAttr && !HasNewAttr &&
6659       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6660       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6661     if (IsMicrosoftABI && IsDefinition) {
6662       S.Diag(NewDecl->getLocation(),
6663              diag::warn_redeclaration_without_import_attribute)
6664           << NewDecl;
6665       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6666       NewDecl->dropAttr<DLLImportAttr>();
6667       NewDecl->addAttr(
6668           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6669     } else {
6670       S.Diag(NewDecl->getLocation(),
6671              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6672           << NewDecl << OldImportAttr;
6673       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6674       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6675       OldDecl->dropAttr<DLLImportAttr>();
6676       NewDecl->dropAttr<DLLImportAttr>();
6677     }
6678   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6679     // In MinGW, seeing a function declared inline drops the dllimport
6680     // attribute.
6681     OldDecl->dropAttr<DLLImportAttr>();
6682     NewDecl->dropAttr<DLLImportAttr>();
6683     S.Diag(NewDecl->getLocation(),
6684            diag::warn_dllimport_dropped_from_inline_function)
6685         << NewDecl << OldImportAttr;
6686   }
6687 
6688   // A specialization of a class template member function is processed here
6689   // since it's a redeclaration. If the parent class is dllexport, the
6690   // specialization inherits that attribute. This doesn't happen automatically
6691   // since the parent class isn't instantiated until later.
6692   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6693     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6694         !NewImportAttr && !NewExportAttr) {
6695       if (const DLLExportAttr *ParentExportAttr =
6696               MD->getParent()->getAttr<DLLExportAttr>()) {
6697         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6698         NewAttr->setInherited(true);
6699         NewDecl->addAttr(NewAttr);
6700       }
6701     }
6702   }
6703 }
6704 
6705 /// Given that we are within the definition of the given function,
6706 /// will that definition behave like C99's 'inline', where the
6707 /// definition is discarded except for optimization purposes?
6708 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6709   // Try to avoid calling GetGVALinkageForFunction.
6710 
6711   // All cases of this require the 'inline' keyword.
6712   if (!FD->isInlined()) return false;
6713 
6714   // This is only possible in C++ with the gnu_inline attribute.
6715   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6716     return false;
6717 
6718   // Okay, go ahead and call the relatively-more-expensive function.
6719   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6720 }
6721 
6722 /// Determine whether a variable is extern "C" prior to attaching
6723 /// an initializer. We can't just call isExternC() here, because that
6724 /// will also compute and cache whether the declaration is externally
6725 /// visible, which might change when we attach the initializer.
6726 ///
6727 /// This can only be used if the declaration is known to not be a
6728 /// redeclaration of an internal linkage declaration.
6729 ///
6730 /// For instance:
6731 ///
6732 ///   auto x = []{};
6733 ///
6734 /// Attaching the initializer here makes this declaration not externally
6735 /// visible, because its type has internal linkage.
6736 ///
6737 /// FIXME: This is a hack.
6738 template<typename T>
6739 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6740   if (S.getLangOpts().CPlusPlus) {
6741     // In C++, the overloadable attribute negates the effects of extern "C".
6742     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6743       return false;
6744 
6745     // So do CUDA's host/device attributes.
6746     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6747                                  D->template hasAttr<CUDAHostAttr>()))
6748       return false;
6749   }
6750   return D->isExternC();
6751 }
6752 
6753 static bool shouldConsiderLinkage(const VarDecl *VD) {
6754   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6755   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6756       isa<OMPDeclareMapperDecl>(DC))
6757     return VD->hasExternalStorage();
6758   if (DC->isFileContext())
6759     return true;
6760   if (DC->isRecord())
6761     return false;
6762   if (isa<RequiresExprBodyDecl>(DC))
6763     return false;
6764   llvm_unreachable("Unexpected context");
6765 }
6766 
6767 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6768   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6769   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6770       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6771     return true;
6772   if (DC->isRecord())
6773     return false;
6774   llvm_unreachable("Unexpected context");
6775 }
6776 
6777 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6778                           ParsedAttr::Kind Kind) {
6779   // Check decl attributes on the DeclSpec.
6780   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6781     return true;
6782 
6783   // Walk the declarator structure, checking decl attributes that were in a type
6784   // position to the decl itself.
6785   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6786     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6787       return true;
6788   }
6789 
6790   // Finally, check attributes on the decl itself.
6791   return PD.getAttributes().hasAttribute(Kind);
6792 }
6793 
6794 /// Adjust the \c DeclContext for a function or variable that might be a
6795 /// function-local external declaration.
6796 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6797   if (!DC->isFunctionOrMethod())
6798     return false;
6799 
6800   // If this is a local extern function or variable declared within a function
6801   // template, don't add it into the enclosing namespace scope until it is
6802   // instantiated; it might have a dependent type right now.
6803   if (DC->isDependentContext())
6804     return true;
6805 
6806   // C++11 [basic.link]p7:
6807   //   When a block scope declaration of an entity with linkage is not found to
6808   //   refer to some other declaration, then that entity is a member of the
6809   //   innermost enclosing namespace.
6810   //
6811   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6812   // semantically-enclosing namespace, not a lexically-enclosing one.
6813   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6814     DC = DC->getParent();
6815   return true;
6816 }
6817 
6818 /// Returns true if given declaration has external C language linkage.
6819 static bool isDeclExternC(const Decl *D) {
6820   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6821     return FD->isExternC();
6822   if (const auto *VD = dyn_cast<VarDecl>(D))
6823     return VD->isExternC();
6824 
6825   llvm_unreachable("Unknown type of decl!");
6826 }
6827 
6828 /// Returns true if there hasn't been any invalid type diagnosed.
6829 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6830   DeclContext *DC = NewVD->getDeclContext();
6831   QualType R = NewVD->getType();
6832 
6833   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6834   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6835   // argument.
6836   if (R->isImageType() || R->isPipeType()) {
6837     Se.Diag(NewVD->getLocation(),
6838             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6839         << R;
6840     NewVD->setInvalidDecl();
6841     return false;
6842   }
6843 
6844   // OpenCL v1.2 s6.9.r:
6845   // The event type cannot be used to declare a program scope variable.
6846   // OpenCL v2.0 s6.9.q:
6847   // The clk_event_t and reserve_id_t types cannot be declared in program
6848   // scope.
6849   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6850     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6851       Se.Diag(NewVD->getLocation(),
6852               diag::err_invalid_type_for_program_scope_var)
6853           << R;
6854       NewVD->setInvalidDecl();
6855       return false;
6856     }
6857   }
6858 
6859   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6860   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6861                                                Se.getLangOpts())) {
6862     QualType NR = R.getCanonicalType();
6863     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6864            NR->isReferenceType()) {
6865       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6866           NR->isFunctionReferenceType()) {
6867         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6868             << NR->isReferenceType();
6869         NewVD->setInvalidDecl();
6870         return false;
6871       }
6872       NR = NR->getPointeeType();
6873     }
6874   }
6875 
6876   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6877                                                Se.getLangOpts())) {
6878     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6879     // half array type (unless the cl_khr_fp16 extension is enabled).
6880     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6881       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6882       NewVD->setInvalidDecl();
6883       return false;
6884     }
6885   }
6886 
6887   // OpenCL v1.2 s6.9.r:
6888   // The event type cannot be used with the __local, __constant and __global
6889   // address space qualifiers.
6890   if (R->isEventT()) {
6891     if (R.getAddressSpace() != LangAS::opencl_private) {
6892       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6893       NewVD->setInvalidDecl();
6894       return false;
6895     }
6896   }
6897 
6898   if (R->isSamplerT()) {
6899     // OpenCL v1.2 s6.9.b p4:
6900     // The sampler type cannot be used with the __local and __global address
6901     // space qualifiers.
6902     if (R.getAddressSpace() == LangAS::opencl_local ||
6903         R.getAddressSpace() == LangAS::opencl_global) {
6904       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6905       NewVD->setInvalidDecl();
6906     }
6907 
6908     // OpenCL v1.2 s6.12.14.1:
6909     // A global sampler must be declared with either the constant address
6910     // space qualifier or with the const qualifier.
6911     if (DC->isTranslationUnit() &&
6912         !(R.getAddressSpace() == LangAS::opencl_constant ||
6913           R.isConstQualified())) {
6914       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6915       NewVD->setInvalidDecl();
6916     }
6917     if (NewVD->isInvalidDecl())
6918       return false;
6919   }
6920 
6921   return true;
6922 }
6923 
6924 template <typename AttrTy>
6925 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6926   const TypedefNameDecl *TND = TT->getDecl();
6927   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6928     AttrTy *Clone = Attribute->clone(S.Context);
6929     Clone->setInherited(true);
6930     D->addAttr(Clone);
6931   }
6932 }
6933 
6934 NamedDecl *Sema::ActOnVariableDeclarator(
6935     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6936     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6937     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6938   QualType R = TInfo->getType();
6939   DeclarationName Name = GetNameForDeclarator(D).getName();
6940 
6941   IdentifierInfo *II = Name.getAsIdentifierInfo();
6942 
6943   if (D.isDecompositionDeclarator()) {
6944     // Take the name of the first declarator as our name for diagnostic
6945     // purposes.
6946     auto &Decomp = D.getDecompositionDeclarator();
6947     if (!Decomp.bindings().empty()) {
6948       II = Decomp.bindings()[0].Name;
6949       Name = II;
6950     }
6951   } else if (!II) {
6952     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6953     return nullptr;
6954   }
6955 
6956 
6957   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6958   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6959 
6960   // dllimport globals without explicit storage class are treated as extern. We
6961   // have to change the storage class this early to get the right DeclContext.
6962   if (SC == SC_None && !DC->isRecord() &&
6963       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6964       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6965     SC = SC_Extern;
6966 
6967   DeclContext *OriginalDC = DC;
6968   bool IsLocalExternDecl = SC == SC_Extern &&
6969                            adjustContextForLocalExternDecl(DC);
6970 
6971   if (SCSpec == DeclSpec::SCS_mutable) {
6972     // mutable can only appear on non-static class members, so it's always
6973     // an error here
6974     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6975     D.setInvalidType();
6976     SC = SC_None;
6977   }
6978 
6979   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6980       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6981                               D.getDeclSpec().getStorageClassSpecLoc())) {
6982     // In C++11, the 'register' storage class specifier is deprecated.
6983     // Suppress the warning in system macros, it's used in macros in some
6984     // popular C system headers, such as in glibc's htonl() macro.
6985     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6986          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6987                                    : diag::warn_deprecated_register)
6988       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6989   }
6990 
6991   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6992 
6993   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6994     // C99 6.9p2: The storage-class specifiers auto and register shall not
6995     // appear in the declaration specifiers in an external declaration.
6996     // Global Register+Asm is a GNU extension we support.
6997     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6998       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6999       D.setInvalidType();
7000     }
7001   }
7002 
7003   // If this variable has a VLA type and an initializer, try to
7004   // fold to a constant-sized type. This is otherwise invalid.
7005   if (D.hasInitializer() && R->isVariableArrayType())
7006     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7007                                     /*DiagID=*/0);
7008 
7009   bool IsMemberSpecialization = false;
7010   bool IsVariableTemplateSpecialization = false;
7011   bool IsPartialSpecialization = false;
7012   bool IsVariableTemplate = false;
7013   VarDecl *NewVD = nullptr;
7014   VarTemplateDecl *NewTemplate = nullptr;
7015   TemplateParameterList *TemplateParams = nullptr;
7016   if (!getLangOpts().CPlusPlus) {
7017     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7018                             II, R, TInfo, SC);
7019 
7020     if (R->getContainedDeducedType())
7021       ParsingInitForAutoVars.insert(NewVD);
7022 
7023     if (D.isInvalidType())
7024       NewVD->setInvalidDecl();
7025 
7026     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7027         NewVD->hasLocalStorage())
7028       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7029                             NTCUC_AutoVar, NTCUK_Destruct);
7030   } else {
7031     bool Invalid = false;
7032 
7033     if (DC->isRecord() && !CurContext->isRecord()) {
7034       // This is an out-of-line definition of a static data member.
7035       switch (SC) {
7036       case SC_None:
7037         break;
7038       case SC_Static:
7039         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7040              diag::err_static_out_of_line)
7041           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7042         break;
7043       case SC_Auto:
7044       case SC_Register:
7045       case SC_Extern:
7046         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7047         // to names of variables declared in a block or to function parameters.
7048         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7049         // of class members
7050 
7051         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7052              diag::err_storage_class_for_static_member)
7053           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7054         break;
7055       case SC_PrivateExtern:
7056         llvm_unreachable("C storage class in c++!");
7057       }
7058     }
7059 
7060     if (SC == SC_Static && CurContext->isRecord()) {
7061       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7062         // Walk up the enclosing DeclContexts to check for any that are
7063         // incompatible with static data members.
7064         const DeclContext *FunctionOrMethod = nullptr;
7065         const CXXRecordDecl *AnonStruct = nullptr;
7066         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7067           if (Ctxt->isFunctionOrMethod()) {
7068             FunctionOrMethod = Ctxt;
7069             break;
7070           }
7071           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7072           if (ParentDecl && !ParentDecl->getDeclName()) {
7073             AnonStruct = ParentDecl;
7074             break;
7075           }
7076         }
7077         if (FunctionOrMethod) {
7078           // C++ [class.static.data]p5: A local class shall not have static data
7079           // members.
7080           Diag(D.getIdentifierLoc(),
7081                diag::err_static_data_member_not_allowed_in_local_class)
7082             << Name << RD->getDeclName() << RD->getTagKind();
7083         } else if (AnonStruct) {
7084           // C++ [class.static.data]p4: Unnamed classes and classes contained
7085           // directly or indirectly within unnamed classes shall not contain
7086           // static data members.
7087           Diag(D.getIdentifierLoc(),
7088                diag::err_static_data_member_not_allowed_in_anon_struct)
7089             << Name << AnonStruct->getTagKind();
7090           Invalid = true;
7091         } else if (RD->isUnion()) {
7092           // C++98 [class.union]p1: If a union contains a static data member,
7093           // the program is ill-formed. C++11 drops this restriction.
7094           Diag(D.getIdentifierLoc(),
7095                getLangOpts().CPlusPlus11
7096                  ? diag::warn_cxx98_compat_static_data_member_in_union
7097                  : diag::ext_static_data_member_in_union) << Name;
7098         }
7099       }
7100     }
7101 
7102     // Match up the template parameter lists with the scope specifier, then
7103     // determine whether we have a template or a template specialization.
7104     bool InvalidScope = false;
7105     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7106         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7107         D.getCXXScopeSpec(),
7108         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7109             ? D.getName().TemplateId
7110             : nullptr,
7111         TemplateParamLists,
7112         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7113     Invalid |= InvalidScope;
7114 
7115     if (TemplateParams) {
7116       if (!TemplateParams->size() &&
7117           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7118         // There is an extraneous 'template<>' for this variable. Complain
7119         // about it, but allow the declaration of the variable.
7120         Diag(TemplateParams->getTemplateLoc(),
7121              diag::err_template_variable_noparams)
7122           << II
7123           << SourceRange(TemplateParams->getTemplateLoc(),
7124                          TemplateParams->getRAngleLoc());
7125         TemplateParams = nullptr;
7126       } else {
7127         // Check that we can declare a template here.
7128         if (CheckTemplateDeclScope(S, TemplateParams))
7129           return nullptr;
7130 
7131         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7132           // This is an explicit specialization or a partial specialization.
7133           IsVariableTemplateSpecialization = true;
7134           IsPartialSpecialization = TemplateParams->size() > 0;
7135         } else { // if (TemplateParams->size() > 0)
7136           // This is a template declaration.
7137           IsVariableTemplate = true;
7138 
7139           // Only C++1y supports variable templates (N3651).
7140           Diag(D.getIdentifierLoc(),
7141                getLangOpts().CPlusPlus14
7142                    ? diag::warn_cxx11_compat_variable_template
7143                    : diag::ext_variable_template);
7144         }
7145       }
7146     } else {
7147       // Check that we can declare a member specialization here.
7148       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7149           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7150         return nullptr;
7151       assert((Invalid ||
7152               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7153              "should have a 'template<>' for this decl");
7154     }
7155 
7156     if (IsVariableTemplateSpecialization) {
7157       SourceLocation TemplateKWLoc =
7158           TemplateParamLists.size() > 0
7159               ? TemplateParamLists[0]->getTemplateLoc()
7160               : SourceLocation();
7161       DeclResult Res = ActOnVarTemplateSpecialization(
7162           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7163           IsPartialSpecialization);
7164       if (Res.isInvalid())
7165         return nullptr;
7166       NewVD = cast<VarDecl>(Res.get());
7167       AddToScope = false;
7168     } else if (D.isDecompositionDeclarator()) {
7169       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7170                                         D.getIdentifierLoc(), R, TInfo, SC,
7171                                         Bindings);
7172     } else
7173       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7174                               D.getIdentifierLoc(), II, R, TInfo, SC);
7175 
7176     // If this is supposed to be a variable template, create it as such.
7177     if (IsVariableTemplate) {
7178       NewTemplate =
7179           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7180                                   TemplateParams, NewVD);
7181       NewVD->setDescribedVarTemplate(NewTemplate);
7182     }
7183 
7184     // If this decl has an auto type in need of deduction, make a note of the
7185     // Decl so we can diagnose uses of it in its own initializer.
7186     if (R->getContainedDeducedType())
7187       ParsingInitForAutoVars.insert(NewVD);
7188 
7189     if (D.isInvalidType() || Invalid) {
7190       NewVD->setInvalidDecl();
7191       if (NewTemplate)
7192         NewTemplate->setInvalidDecl();
7193     }
7194 
7195     SetNestedNameSpecifier(*this, NewVD, D);
7196 
7197     // If we have any template parameter lists that don't directly belong to
7198     // the variable (matching the scope specifier), store them.
7199     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7200     if (TemplateParamLists.size() > VDTemplateParamLists)
7201       NewVD->setTemplateParameterListsInfo(
7202           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7203   }
7204 
7205   if (D.getDeclSpec().isInlineSpecified()) {
7206     if (!getLangOpts().CPlusPlus) {
7207       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7208           << 0;
7209     } else if (CurContext->isFunctionOrMethod()) {
7210       // 'inline' is not allowed on block scope variable declaration.
7211       Diag(D.getDeclSpec().getInlineSpecLoc(),
7212            diag::err_inline_declaration_block_scope) << Name
7213         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7214     } else {
7215       Diag(D.getDeclSpec().getInlineSpecLoc(),
7216            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7217                                      : diag::ext_inline_variable);
7218       NewVD->setInlineSpecified();
7219     }
7220   }
7221 
7222   // Set the lexical context. If the declarator has a C++ scope specifier, the
7223   // lexical context will be different from the semantic context.
7224   NewVD->setLexicalDeclContext(CurContext);
7225   if (NewTemplate)
7226     NewTemplate->setLexicalDeclContext(CurContext);
7227 
7228   if (IsLocalExternDecl) {
7229     if (D.isDecompositionDeclarator())
7230       for (auto *B : Bindings)
7231         B->setLocalExternDecl();
7232     else
7233       NewVD->setLocalExternDecl();
7234   }
7235 
7236   bool EmitTLSUnsupportedError = false;
7237   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7238     // C++11 [dcl.stc]p4:
7239     //   When thread_local is applied to a variable of block scope the
7240     //   storage-class-specifier static is implied if it does not appear
7241     //   explicitly.
7242     // Core issue: 'static' is not implied if the variable is declared
7243     //   'extern'.
7244     if (NewVD->hasLocalStorage() &&
7245         (SCSpec != DeclSpec::SCS_unspecified ||
7246          TSCS != DeclSpec::TSCS_thread_local ||
7247          !DC->isFunctionOrMethod()))
7248       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7249            diag::err_thread_non_global)
7250         << DeclSpec::getSpecifierName(TSCS);
7251     else if (!Context.getTargetInfo().isTLSSupported()) {
7252       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7253           getLangOpts().SYCLIsDevice) {
7254         // Postpone error emission until we've collected attributes required to
7255         // figure out whether it's a host or device variable and whether the
7256         // error should be ignored.
7257         EmitTLSUnsupportedError = true;
7258         // We still need to mark the variable as TLS so it shows up in AST with
7259         // proper storage class for other tools to use even if we're not going
7260         // to emit any code for it.
7261         NewVD->setTSCSpec(TSCS);
7262       } else
7263         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7264              diag::err_thread_unsupported);
7265     } else
7266       NewVD->setTSCSpec(TSCS);
7267   }
7268 
7269   switch (D.getDeclSpec().getConstexprSpecifier()) {
7270   case ConstexprSpecKind::Unspecified:
7271     break;
7272 
7273   case ConstexprSpecKind::Consteval:
7274     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7275          diag::err_constexpr_wrong_decl_kind)
7276         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7277     LLVM_FALLTHROUGH;
7278 
7279   case ConstexprSpecKind::Constexpr:
7280     NewVD->setConstexpr(true);
7281     // C++1z [dcl.spec.constexpr]p1:
7282     //   A static data member declared with the constexpr specifier is
7283     //   implicitly an inline variable.
7284     if (NewVD->isStaticDataMember() &&
7285         (getLangOpts().CPlusPlus17 ||
7286          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7287       NewVD->setImplicitlyInline();
7288     break;
7289 
7290   case ConstexprSpecKind::Constinit:
7291     if (!NewVD->hasGlobalStorage())
7292       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7293            diag::err_constinit_local_variable);
7294     else
7295       NewVD->addAttr(ConstInitAttr::Create(
7296           Context, D.getDeclSpec().getConstexprSpecLoc(),
7297           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7298     break;
7299   }
7300 
7301   // C99 6.7.4p3
7302   //   An inline definition of a function with external linkage shall
7303   //   not contain a definition of a modifiable object with static or
7304   //   thread storage duration...
7305   // We only apply this when the function is required to be defined
7306   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7307   // that a local variable with thread storage duration still has to
7308   // be marked 'static'.  Also note that it's possible to get these
7309   // semantics in C++ using __attribute__((gnu_inline)).
7310   if (SC == SC_Static && S->getFnParent() != nullptr &&
7311       !NewVD->getType().isConstQualified()) {
7312     FunctionDecl *CurFD = getCurFunctionDecl();
7313     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7314       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7315            diag::warn_static_local_in_extern_inline);
7316       MaybeSuggestAddingStaticToDecl(CurFD);
7317     }
7318   }
7319 
7320   if (D.getDeclSpec().isModulePrivateSpecified()) {
7321     if (IsVariableTemplateSpecialization)
7322       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7323           << (IsPartialSpecialization ? 1 : 0)
7324           << FixItHint::CreateRemoval(
7325                  D.getDeclSpec().getModulePrivateSpecLoc());
7326     else if (IsMemberSpecialization)
7327       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7328         << 2
7329         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7330     else if (NewVD->hasLocalStorage())
7331       Diag(NewVD->getLocation(), diag::err_module_private_local)
7332           << 0 << NewVD
7333           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7334           << FixItHint::CreateRemoval(
7335                  D.getDeclSpec().getModulePrivateSpecLoc());
7336     else {
7337       NewVD->setModulePrivate();
7338       if (NewTemplate)
7339         NewTemplate->setModulePrivate();
7340       for (auto *B : Bindings)
7341         B->setModulePrivate();
7342     }
7343   }
7344 
7345   if (getLangOpts().OpenCL) {
7346     deduceOpenCLAddressSpace(NewVD);
7347 
7348     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7349     if (TSC != TSCS_unspecified) {
7350       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7351            diag::err_opencl_unknown_type_specifier)
7352           << getLangOpts().getOpenCLVersionString()
7353           << DeclSpec::getSpecifierName(TSC) << 1;
7354       NewVD->setInvalidDecl();
7355     }
7356   }
7357 
7358   // Handle attributes prior to checking for duplicates in MergeVarDecl
7359   ProcessDeclAttributes(S, NewVD, D);
7360 
7361   // FIXME: This is probably the wrong location to be doing this and we should
7362   // probably be doing this for more attributes (especially for function
7363   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7364   // the code to copy attributes would be generated by TableGen.
7365   if (R->isFunctionPointerType())
7366     if (const auto *TT = R->getAs<TypedefType>())
7367       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7368 
7369   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7370       getLangOpts().SYCLIsDevice) {
7371     if (EmitTLSUnsupportedError &&
7372         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7373          (getLangOpts().OpenMPIsDevice &&
7374           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7375       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7376            diag::err_thread_unsupported);
7377 
7378     if (EmitTLSUnsupportedError &&
7379         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7380       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7381     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7382     // storage [duration]."
7383     if (SC == SC_None && S->getFnParent() != nullptr &&
7384         (NewVD->hasAttr<CUDASharedAttr>() ||
7385          NewVD->hasAttr<CUDAConstantAttr>())) {
7386       NewVD->setStorageClass(SC_Static);
7387     }
7388   }
7389 
7390   // Ensure that dllimport globals without explicit storage class are treated as
7391   // extern. The storage class is set above using parsed attributes. Now we can
7392   // check the VarDecl itself.
7393   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7394          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7395          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7396 
7397   // In auto-retain/release, infer strong retension for variables of
7398   // retainable type.
7399   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7400     NewVD->setInvalidDecl();
7401 
7402   // Handle GNU asm-label extension (encoded as an attribute).
7403   if (Expr *E = (Expr*)D.getAsmLabel()) {
7404     // The parser guarantees this is a string.
7405     StringLiteral *SE = cast<StringLiteral>(E);
7406     StringRef Label = SE->getString();
7407     if (S->getFnParent() != nullptr) {
7408       switch (SC) {
7409       case SC_None:
7410       case SC_Auto:
7411         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7412         break;
7413       case SC_Register:
7414         // Local Named register
7415         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7416             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7417           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7418         break;
7419       case SC_Static:
7420       case SC_Extern:
7421       case SC_PrivateExtern:
7422         break;
7423       }
7424     } else if (SC == SC_Register) {
7425       // Global Named register
7426       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7427         const auto &TI = Context.getTargetInfo();
7428         bool HasSizeMismatch;
7429 
7430         if (!TI.isValidGCCRegisterName(Label))
7431           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7432         else if (!TI.validateGlobalRegisterVariable(Label,
7433                                                     Context.getTypeSize(R),
7434                                                     HasSizeMismatch))
7435           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7436         else if (HasSizeMismatch)
7437           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7438       }
7439 
7440       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7441         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7442         NewVD->setInvalidDecl(true);
7443       }
7444     }
7445 
7446     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7447                                         /*IsLiteralLabel=*/true,
7448                                         SE->getStrTokenLoc(0)));
7449   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7450     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7451       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7452     if (I != ExtnameUndeclaredIdentifiers.end()) {
7453       if (isDeclExternC(NewVD)) {
7454         NewVD->addAttr(I->second);
7455         ExtnameUndeclaredIdentifiers.erase(I);
7456       } else
7457         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7458             << /*Variable*/1 << NewVD;
7459     }
7460   }
7461 
7462   // Find the shadowed declaration before filtering for scope.
7463   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7464                                 ? getShadowedDeclaration(NewVD, Previous)
7465                                 : nullptr;
7466 
7467   // Don't consider existing declarations that are in a different
7468   // scope and are out-of-semantic-context declarations (if the new
7469   // declaration has linkage).
7470   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7471                        D.getCXXScopeSpec().isNotEmpty() ||
7472                        IsMemberSpecialization ||
7473                        IsVariableTemplateSpecialization);
7474 
7475   // Check whether the previous declaration is in the same block scope. This
7476   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7477   if (getLangOpts().CPlusPlus &&
7478       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7479     NewVD->setPreviousDeclInSameBlockScope(
7480         Previous.isSingleResult() && !Previous.isShadowed() &&
7481         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7482 
7483   if (!getLangOpts().CPlusPlus) {
7484     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7485   } else {
7486     // If this is an explicit specialization of a static data member, check it.
7487     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7488         CheckMemberSpecialization(NewVD, Previous))
7489       NewVD->setInvalidDecl();
7490 
7491     // Merge the decl with the existing one if appropriate.
7492     if (!Previous.empty()) {
7493       if (Previous.isSingleResult() &&
7494           isa<FieldDecl>(Previous.getFoundDecl()) &&
7495           D.getCXXScopeSpec().isSet()) {
7496         // The user tried to define a non-static data member
7497         // out-of-line (C++ [dcl.meaning]p1).
7498         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7499           << D.getCXXScopeSpec().getRange();
7500         Previous.clear();
7501         NewVD->setInvalidDecl();
7502       }
7503     } else if (D.getCXXScopeSpec().isSet()) {
7504       // No previous declaration in the qualifying scope.
7505       Diag(D.getIdentifierLoc(), diag::err_no_member)
7506         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7507         << D.getCXXScopeSpec().getRange();
7508       NewVD->setInvalidDecl();
7509     }
7510 
7511     if (!IsVariableTemplateSpecialization)
7512       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7513 
7514     if (NewTemplate) {
7515       VarTemplateDecl *PrevVarTemplate =
7516           NewVD->getPreviousDecl()
7517               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7518               : nullptr;
7519 
7520       // Check the template parameter list of this declaration, possibly
7521       // merging in the template parameter list from the previous variable
7522       // template declaration.
7523       if (CheckTemplateParameterList(
7524               TemplateParams,
7525               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7526                               : nullptr,
7527               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7528                DC->isDependentContext())
7529                   ? TPC_ClassTemplateMember
7530                   : TPC_VarTemplate))
7531         NewVD->setInvalidDecl();
7532 
7533       // If we are providing an explicit specialization of a static variable
7534       // template, make a note of that.
7535       if (PrevVarTemplate &&
7536           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7537         PrevVarTemplate->setMemberSpecialization();
7538     }
7539   }
7540 
7541   // Diagnose shadowed variables iff this isn't a redeclaration.
7542   if (ShadowedDecl && !D.isRedeclaration())
7543     CheckShadow(NewVD, ShadowedDecl, Previous);
7544 
7545   ProcessPragmaWeak(S, NewVD);
7546 
7547   // If this is the first declaration of an extern C variable, update
7548   // the map of such variables.
7549   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7550       isIncompleteDeclExternC(*this, NewVD))
7551     RegisterLocallyScopedExternCDecl(NewVD, S);
7552 
7553   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7554     MangleNumberingContext *MCtx;
7555     Decl *ManglingContextDecl;
7556     std::tie(MCtx, ManglingContextDecl) =
7557         getCurrentMangleNumberContext(NewVD->getDeclContext());
7558     if (MCtx) {
7559       Context.setManglingNumber(
7560           NewVD, MCtx->getManglingNumber(
7561                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7562       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7563     }
7564   }
7565 
7566   // Special handling of variable named 'main'.
7567   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7568       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7569       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7570 
7571     // C++ [basic.start.main]p3
7572     // A program that declares a variable main at global scope is ill-formed.
7573     if (getLangOpts().CPlusPlus)
7574       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7575 
7576     // In C, and external-linkage variable named main results in undefined
7577     // behavior.
7578     else if (NewVD->hasExternalFormalLinkage())
7579       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7580   }
7581 
7582   if (D.isRedeclaration() && !Previous.empty()) {
7583     NamedDecl *Prev = Previous.getRepresentativeDecl();
7584     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7585                                    D.isFunctionDefinition());
7586   }
7587 
7588   if (NewTemplate) {
7589     if (NewVD->isInvalidDecl())
7590       NewTemplate->setInvalidDecl();
7591     ActOnDocumentableDecl(NewTemplate);
7592     return NewTemplate;
7593   }
7594 
7595   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7596     CompleteMemberSpecialization(NewVD, Previous);
7597 
7598   return NewVD;
7599 }
7600 
7601 /// Enum describing the %select options in diag::warn_decl_shadow.
7602 enum ShadowedDeclKind {
7603   SDK_Local,
7604   SDK_Global,
7605   SDK_StaticMember,
7606   SDK_Field,
7607   SDK_Typedef,
7608   SDK_Using,
7609   SDK_StructuredBinding
7610 };
7611 
7612 /// Determine what kind of declaration we're shadowing.
7613 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7614                                                 const DeclContext *OldDC) {
7615   if (isa<TypeAliasDecl>(ShadowedDecl))
7616     return SDK_Using;
7617   else if (isa<TypedefDecl>(ShadowedDecl))
7618     return SDK_Typedef;
7619   else if (isa<BindingDecl>(ShadowedDecl))
7620     return SDK_StructuredBinding;
7621   else if (isa<RecordDecl>(OldDC))
7622     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7623 
7624   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7625 }
7626 
7627 /// Return the location of the capture if the given lambda captures the given
7628 /// variable \p VD, or an invalid source location otherwise.
7629 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7630                                          const VarDecl *VD) {
7631   for (const Capture &Capture : LSI->Captures) {
7632     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7633       return Capture.getLocation();
7634   }
7635   return SourceLocation();
7636 }
7637 
7638 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7639                                      const LookupResult &R) {
7640   // Only diagnose if we're shadowing an unambiguous field or variable.
7641   if (R.getResultKind() != LookupResult::Found)
7642     return false;
7643 
7644   // Return false if warning is ignored.
7645   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7646 }
7647 
7648 /// Return the declaration shadowed by the given variable \p D, or null
7649 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7650 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7651                                         const LookupResult &R) {
7652   if (!shouldWarnIfShadowedDecl(Diags, R))
7653     return nullptr;
7654 
7655   // Don't diagnose declarations at file scope.
7656   if (D->hasGlobalStorage())
7657     return nullptr;
7658 
7659   NamedDecl *ShadowedDecl = R.getFoundDecl();
7660   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7661                                                             : nullptr;
7662 }
7663 
7664 /// Return the declaration shadowed by the given typedef \p D, or null
7665 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7666 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7667                                         const LookupResult &R) {
7668   // Don't warn if typedef declaration is part of a class
7669   if (D->getDeclContext()->isRecord())
7670     return nullptr;
7671 
7672   if (!shouldWarnIfShadowedDecl(Diags, R))
7673     return nullptr;
7674 
7675   NamedDecl *ShadowedDecl = R.getFoundDecl();
7676   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7677 }
7678 
7679 /// Return the declaration shadowed by the given variable \p D, or null
7680 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7681 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7682                                         const LookupResult &R) {
7683   if (!shouldWarnIfShadowedDecl(Diags, R))
7684     return nullptr;
7685 
7686   NamedDecl *ShadowedDecl = R.getFoundDecl();
7687   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7688                                                             : nullptr;
7689 }
7690 
7691 /// Diagnose variable or built-in function shadowing.  Implements
7692 /// -Wshadow.
7693 ///
7694 /// This method is called whenever a VarDecl is added to a "useful"
7695 /// scope.
7696 ///
7697 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7698 /// \param R the lookup of the name
7699 ///
7700 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7701                        const LookupResult &R) {
7702   DeclContext *NewDC = D->getDeclContext();
7703 
7704   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7705     // Fields are not shadowed by variables in C++ static methods.
7706     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7707       if (MD->isStatic())
7708         return;
7709 
7710     // Fields shadowed by constructor parameters are a special case. Usually
7711     // the constructor initializes the field with the parameter.
7712     if (isa<CXXConstructorDecl>(NewDC))
7713       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7714         // Remember that this was shadowed so we can either warn about its
7715         // modification or its existence depending on warning settings.
7716         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7717         return;
7718       }
7719   }
7720 
7721   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7722     if (shadowedVar->isExternC()) {
7723       // For shadowing external vars, make sure that we point to the global
7724       // declaration, not a locally scoped extern declaration.
7725       for (auto I : shadowedVar->redecls())
7726         if (I->isFileVarDecl()) {
7727           ShadowedDecl = I;
7728           break;
7729         }
7730     }
7731 
7732   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7733 
7734   unsigned WarningDiag = diag::warn_decl_shadow;
7735   SourceLocation CaptureLoc;
7736   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7737       isa<CXXMethodDecl>(NewDC)) {
7738     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7739       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7740         if (RD->getLambdaCaptureDefault() == LCD_None) {
7741           // Try to avoid warnings for lambdas with an explicit capture list.
7742           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7743           // Warn only when the lambda captures the shadowed decl explicitly.
7744           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7745           if (CaptureLoc.isInvalid())
7746             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7747         } else {
7748           // Remember that this was shadowed so we can avoid the warning if the
7749           // shadowed decl isn't captured and the warning settings allow it.
7750           cast<LambdaScopeInfo>(getCurFunction())
7751               ->ShadowingDecls.push_back(
7752                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7753           return;
7754         }
7755       }
7756 
7757       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7758         // A variable can't shadow a local variable in an enclosing scope, if
7759         // they are separated by a non-capturing declaration context.
7760         for (DeclContext *ParentDC = NewDC;
7761              ParentDC && !ParentDC->Equals(OldDC);
7762              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7763           // Only block literals, captured statements, and lambda expressions
7764           // can capture; other scopes don't.
7765           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7766               !isLambdaCallOperator(ParentDC)) {
7767             return;
7768           }
7769         }
7770       }
7771     }
7772   }
7773 
7774   // Only warn about certain kinds of shadowing for class members.
7775   if (NewDC && NewDC->isRecord()) {
7776     // In particular, don't warn about shadowing non-class members.
7777     if (!OldDC->isRecord())
7778       return;
7779 
7780     // TODO: should we warn about static data members shadowing
7781     // static data members from base classes?
7782 
7783     // TODO: don't diagnose for inaccessible shadowed members.
7784     // This is hard to do perfectly because we might friend the
7785     // shadowing context, but that's just a false negative.
7786   }
7787 
7788 
7789   DeclarationName Name = R.getLookupName();
7790 
7791   // Emit warning and note.
7792   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7793     return;
7794   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7795   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7796   if (!CaptureLoc.isInvalid())
7797     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7798         << Name << /*explicitly*/ 1;
7799   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7800 }
7801 
7802 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7803 /// when these variables are captured by the lambda.
7804 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7805   for (const auto &Shadow : LSI->ShadowingDecls) {
7806     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7807     // Try to avoid the warning when the shadowed decl isn't captured.
7808     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7809     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7810     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7811                                        ? diag::warn_decl_shadow_uncaptured_local
7812                                        : diag::warn_decl_shadow)
7813         << Shadow.VD->getDeclName()
7814         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7815     if (!CaptureLoc.isInvalid())
7816       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7817           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7818     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7819   }
7820 }
7821 
7822 /// Check -Wshadow without the advantage of a previous lookup.
7823 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7824   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7825     return;
7826 
7827   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7828                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7829   LookupName(R, S);
7830   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7831     CheckShadow(D, ShadowedDecl, R);
7832 }
7833 
7834 /// Check if 'E', which is an expression that is about to be modified, refers
7835 /// to a constructor parameter that shadows a field.
7836 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7837   // Quickly ignore expressions that can't be shadowing ctor parameters.
7838   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7839     return;
7840   E = E->IgnoreParenImpCasts();
7841   auto *DRE = dyn_cast<DeclRefExpr>(E);
7842   if (!DRE)
7843     return;
7844   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7845   auto I = ShadowingDecls.find(D);
7846   if (I == ShadowingDecls.end())
7847     return;
7848   const NamedDecl *ShadowedDecl = I->second;
7849   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7850   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7851   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7852   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7853 
7854   // Avoid issuing multiple warnings about the same decl.
7855   ShadowingDecls.erase(I);
7856 }
7857 
7858 /// Check for conflict between this global or extern "C" declaration and
7859 /// previous global or extern "C" declarations. This is only used in C++.
7860 template<typename T>
7861 static bool checkGlobalOrExternCConflict(
7862     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7863   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7864   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7865 
7866   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7867     // The common case: this global doesn't conflict with any extern "C"
7868     // declaration.
7869     return false;
7870   }
7871 
7872   if (Prev) {
7873     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7874       // Both the old and new declarations have C language linkage. This is a
7875       // redeclaration.
7876       Previous.clear();
7877       Previous.addDecl(Prev);
7878       return true;
7879     }
7880 
7881     // This is a global, non-extern "C" declaration, and there is a previous
7882     // non-global extern "C" declaration. Diagnose if this is a variable
7883     // declaration.
7884     if (!isa<VarDecl>(ND))
7885       return false;
7886   } else {
7887     // The declaration is extern "C". Check for any declaration in the
7888     // translation unit which might conflict.
7889     if (IsGlobal) {
7890       // We have already performed the lookup into the translation unit.
7891       IsGlobal = false;
7892       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7893            I != E; ++I) {
7894         if (isa<VarDecl>(*I)) {
7895           Prev = *I;
7896           break;
7897         }
7898       }
7899     } else {
7900       DeclContext::lookup_result R =
7901           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7902       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7903            I != E; ++I) {
7904         if (isa<VarDecl>(*I)) {
7905           Prev = *I;
7906           break;
7907         }
7908         // FIXME: If we have any other entity with this name in global scope,
7909         // the declaration is ill-formed, but that is a defect: it breaks the
7910         // 'stat' hack, for instance. Only variables can have mangled name
7911         // clashes with extern "C" declarations, so only they deserve a
7912         // diagnostic.
7913       }
7914     }
7915 
7916     if (!Prev)
7917       return false;
7918   }
7919 
7920   // Use the first declaration's location to ensure we point at something which
7921   // is lexically inside an extern "C" linkage-spec.
7922   assert(Prev && "should have found a previous declaration to diagnose");
7923   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7924     Prev = FD->getFirstDecl();
7925   else
7926     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7927 
7928   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7929     << IsGlobal << ND;
7930   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7931     << IsGlobal;
7932   return false;
7933 }
7934 
7935 /// Apply special rules for handling extern "C" declarations. Returns \c true
7936 /// if we have found that this is a redeclaration of some prior entity.
7937 ///
7938 /// Per C++ [dcl.link]p6:
7939 ///   Two declarations [for a function or variable] with C language linkage
7940 ///   with the same name that appear in different scopes refer to the same
7941 ///   [entity]. An entity with C language linkage shall not be declared with
7942 ///   the same name as an entity in global scope.
7943 template<typename T>
7944 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7945                                                   LookupResult &Previous) {
7946   if (!S.getLangOpts().CPlusPlus) {
7947     // In C, when declaring a global variable, look for a corresponding 'extern'
7948     // variable declared in function scope. We don't need this in C++, because
7949     // we find local extern decls in the surrounding file-scope DeclContext.
7950     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7951       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7952         Previous.clear();
7953         Previous.addDecl(Prev);
7954         return true;
7955       }
7956     }
7957     return false;
7958   }
7959 
7960   // A declaration in the translation unit can conflict with an extern "C"
7961   // declaration.
7962   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7963     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7964 
7965   // An extern "C" declaration can conflict with a declaration in the
7966   // translation unit or can be a redeclaration of an extern "C" declaration
7967   // in another scope.
7968   if (isIncompleteDeclExternC(S,ND))
7969     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7970 
7971   // Neither global nor extern "C": nothing to do.
7972   return false;
7973 }
7974 
7975 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7976   // If the decl is already known invalid, don't check it.
7977   if (NewVD->isInvalidDecl())
7978     return;
7979 
7980   QualType T = NewVD->getType();
7981 
7982   // Defer checking an 'auto' type until its initializer is attached.
7983   if (T->isUndeducedType())
7984     return;
7985 
7986   if (NewVD->hasAttrs())
7987     CheckAlignasUnderalignment(NewVD);
7988 
7989   if (T->isObjCObjectType()) {
7990     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7991       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7992     T = Context.getObjCObjectPointerType(T);
7993     NewVD->setType(T);
7994   }
7995 
7996   // Emit an error if an address space was applied to decl with local storage.
7997   // This includes arrays of objects with address space qualifiers, but not
7998   // automatic variables that point to other address spaces.
7999   // ISO/IEC TR 18037 S5.1.2
8000   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8001       T.getAddressSpace() != LangAS::Default) {
8002     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8003     NewVD->setInvalidDecl();
8004     return;
8005   }
8006 
8007   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8008   // scope.
8009   if (getLangOpts().OpenCLVersion == 120 &&
8010       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8011                                             getLangOpts()) &&
8012       NewVD->isStaticLocal()) {
8013     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8014     NewVD->setInvalidDecl();
8015     return;
8016   }
8017 
8018   if (getLangOpts().OpenCL) {
8019     if (!diagnoseOpenCLTypes(*this, NewVD))
8020       return;
8021 
8022     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8023     if (NewVD->hasAttr<BlocksAttr>()) {
8024       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8025       return;
8026     }
8027 
8028     if (T->isBlockPointerType()) {
8029       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8030       // can't use 'extern' storage class.
8031       if (!T.isConstQualified()) {
8032         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8033             << 0 /*const*/;
8034         NewVD->setInvalidDecl();
8035         return;
8036       }
8037       if (NewVD->hasExternalStorage()) {
8038         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8039         NewVD->setInvalidDecl();
8040         return;
8041       }
8042     }
8043 
8044     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8045     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8046         NewVD->hasExternalStorage()) {
8047       if (!T->isSamplerT() && !T->isDependentType() &&
8048           !(T.getAddressSpace() == LangAS::opencl_constant ||
8049             (T.getAddressSpace() == LangAS::opencl_global &&
8050              getOpenCLOptions().areProgramScopeVariablesSupported(
8051                  getLangOpts())))) {
8052         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8053         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8054           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8055               << Scope << "global or constant";
8056         else
8057           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8058               << Scope << "constant";
8059         NewVD->setInvalidDecl();
8060         return;
8061       }
8062     } else {
8063       if (T.getAddressSpace() == LangAS::opencl_global) {
8064         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8065             << 1 /*is any function*/ << "global";
8066         NewVD->setInvalidDecl();
8067         return;
8068       }
8069       if (T.getAddressSpace() == LangAS::opencl_constant ||
8070           T.getAddressSpace() == LangAS::opencl_local) {
8071         FunctionDecl *FD = getCurFunctionDecl();
8072         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8073         // in functions.
8074         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8075           if (T.getAddressSpace() == LangAS::opencl_constant)
8076             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8077                 << 0 /*non-kernel only*/ << "constant";
8078           else
8079             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8080                 << 0 /*non-kernel only*/ << "local";
8081           NewVD->setInvalidDecl();
8082           return;
8083         }
8084         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8085         // in the outermost scope of a kernel function.
8086         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8087           if (!getCurScope()->isFunctionScope()) {
8088             if (T.getAddressSpace() == LangAS::opencl_constant)
8089               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8090                   << "constant";
8091             else
8092               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8093                   << "local";
8094             NewVD->setInvalidDecl();
8095             return;
8096           }
8097         }
8098       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8099                  // If we are parsing a template we didn't deduce an addr
8100                  // space yet.
8101                  T.getAddressSpace() != LangAS::Default) {
8102         // Do not allow other address spaces on automatic variable.
8103         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8104         NewVD->setInvalidDecl();
8105         return;
8106       }
8107     }
8108   }
8109 
8110   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8111       && !NewVD->hasAttr<BlocksAttr>()) {
8112     if (getLangOpts().getGC() != LangOptions::NonGC)
8113       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8114     else {
8115       assert(!getLangOpts().ObjCAutoRefCount);
8116       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8117     }
8118   }
8119 
8120   bool isVM = T->isVariablyModifiedType();
8121   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8122       NewVD->hasAttr<BlocksAttr>())
8123     setFunctionHasBranchProtectedScope();
8124 
8125   if ((isVM && NewVD->hasLinkage()) ||
8126       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8127     bool SizeIsNegative;
8128     llvm::APSInt Oversized;
8129     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8130         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8131     QualType FixedT;
8132     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8133       FixedT = FixedTInfo->getType();
8134     else if (FixedTInfo) {
8135       // Type and type-as-written are canonically different. We need to fix up
8136       // both types separately.
8137       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8138                                                    Oversized);
8139     }
8140     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8141       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8142       // FIXME: This won't give the correct result for
8143       // int a[10][n];
8144       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8145 
8146       if (NewVD->isFileVarDecl())
8147         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8148         << SizeRange;
8149       else if (NewVD->isStaticLocal())
8150         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8151         << SizeRange;
8152       else
8153         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8154         << SizeRange;
8155       NewVD->setInvalidDecl();
8156       return;
8157     }
8158 
8159     if (!FixedTInfo) {
8160       if (NewVD->isFileVarDecl())
8161         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8162       else
8163         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8164       NewVD->setInvalidDecl();
8165       return;
8166     }
8167 
8168     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8169     NewVD->setType(FixedT);
8170     NewVD->setTypeSourceInfo(FixedTInfo);
8171   }
8172 
8173   if (T->isVoidType()) {
8174     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8175     //                    of objects and functions.
8176     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8177       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8178         << T;
8179       NewVD->setInvalidDecl();
8180       return;
8181     }
8182   }
8183 
8184   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8185     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8186     NewVD->setInvalidDecl();
8187     return;
8188   }
8189 
8190   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8191     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8192     NewVD->setInvalidDecl();
8193     return;
8194   }
8195 
8196   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8197     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8198     NewVD->setInvalidDecl();
8199     return;
8200   }
8201 
8202   if (NewVD->isConstexpr() && !T->isDependentType() &&
8203       RequireLiteralType(NewVD->getLocation(), T,
8204                          diag::err_constexpr_var_non_literal)) {
8205     NewVD->setInvalidDecl();
8206     return;
8207   }
8208 
8209   // PPC MMA non-pointer types are not allowed as non-local variable types.
8210   if (Context.getTargetInfo().getTriple().isPPC64() &&
8211       !NewVD->isLocalVarDecl() &&
8212       CheckPPCMMAType(T, NewVD->getLocation())) {
8213     NewVD->setInvalidDecl();
8214     return;
8215   }
8216 }
8217 
8218 /// Perform semantic checking on a newly-created variable
8219 /// declaration.
8220 ///
8221 /// This routine performs all of the type-checking required for a
8222 /// variable declaration once it has been built. It is used both to
8223 /// check variables after they have been parsed and their declarators
8224 /// have been translated into a declaration, and to check variables
8225 /// that have been instantiated from a template.
8226 ///
8227 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8228 ///
8229 /// Returns true if the variable declaration is a redeclaration.
8230 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8231   CheckVariableDeclarationType(NewVD);
8232 
8233   // If the decl is already known invalid, don't check it.
8234   if (NewVD->isInvalidDecl())
8235     return false;
8236 
8237   // If we did not find anything by this name, look for a non-visible
8238   // extern "C" declaration with the same name.
8239   if (Previous.empty() &&
8240       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8241     Previous.setShadowed();
8242 
8243   if (!Previous.empty()) {
8244     MergeVarDecl(NewVD, Previous);
8245     return true;
8246   }
8247   return false;
8248 }
8249 
8250 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8251 /// and if so, check that it's a valid override and remember it.
8252 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8253   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8254 
8255   // Look for methods in base classes that this method might override.
8256   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8257                      /*DetectVirtual=*/false);
8258   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8259     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8260     DeclarationName Name = MD->getDeclName();
8261 
8262     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8263       // We really want to find the base class destructor here.
8264       QualType T = Context.getTypeDeclType(BaseRecord);
8265       CanQualType CT = Context.getCanonicalType(T);
8266       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8267     }
8268 
8269     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8270       CXXMethodDecl *BaseMD =
8271           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8272       if (!BaseMD || !BaseMD->isVirtual() ||
8273           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8274                      /*ConsiderCudaAttrs=*/true,
8275                      // C++2a [class.virtual]p2 does not consider requires
8276                      // clauses when overriding.
8277                      /*ConsiderRequiresClauses=*/false))
8278         continue;
8279 
8280       if (Overridden.insert(BaseMD).second) {
8281         MD->addOverriddenMethod(BaseMD);
8282         CheckOverridingFunctionReturnType(MD, BaseMD);
8283         CheckOverridingFunctionAttributes(MD, BaseMD);
8284         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8285         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8286       }
8287 
8288       // A method can only override one function from each base class. We
8289       // don't track indirectly overridden methods from bases of bases.
8290       return true;
8291     }
8292 
8293     return false;
8294   };
8295 
8296   DC->lookupInBases(VisitBase, Paths);
8297   return !Overridden.empty();
8298 }
8299 
8300 namespace {
8301   // Struct for holding all of the extra arguments needed by
8302   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8303   struct ActOnFDArgs {
8304     Scope *S;
8305     Declarator &D;
8306     MultiTemplateParamsArg TemplateParamLists;
8307     bool AddToScope;
8308   };
8309 } // end anonymous namespace
8310 
8311 namespace {
8312 
8313 // Callback to only accept typo corrections that have a non-zero edit distance.
8314 // Also only accept corrections that have the same parent decl.
8315 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8316  public:
8317   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8318                             CXXRecordDecl *Parent)
8319       : Context(Context), OriginalFD(TypoFD),
8320         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8321 
8322   bool ValidateCandidate(const TypoCorrection &candidate) override {
8323     if (candidate.getEditDistance() == 0)
8324       return false;
8325 
8326     SmallVector<unsigned, 1> MismatchedParams;
8327     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8328                                           CDeclEnd = candidate.end();
8329          CDecl != CDeclEnd; ++CDecl) {
8330       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8331 
8332       if (FD && !FD->hasBody() &&
8333           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8334         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8335           CXXRecordDecl *Parent = MD->getParent();
8336           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8337             return true;
8338         } else if (!ExpectedParent) {
8339           return true;
8340         }
8341       }
8342     }
8343 
8344     return false;
8345   }
8346 
8347   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8348     return std::make_unique<DifferentNameValidatorCCC>(*this);
8349   }
8350 
8351  private:
8352   ASTContext &Context;
8353   FunctionDecl *OriginalFD;
8354   CXXRecordDecl *ExpectedParent;
8355 };
8356 
8357 } // end anonymous namespace
8358 
8359 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8360   TypoCorrectedFunctionDefinitions.insert(F);
8361 }
8362 
8363 /// Generate diagnostics for an invalid function redeclaration.
8364 ///
8365 /// This routine handles generating the diagnostic messages for an invalid
8366 /// function redeclaration, including finding possible similar declarations
8367 /// or performing typo correction if there are no previous declarations with
8368 /// the same name.
8369 ///
8370 /// Returns a NamedDecl iff typo correction was performed and substituting in
8371 /// the new declaration name does not cause new errors.
8372 static NamedDecl *DiagnoseInvalidRedeclaration(
8373     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8374     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8375   DeclarationName Name = NewFD->getDeclName();
8376   DeclContext *NewDC = NewFD->getDeclContext();
8377   SmallVector<unsigned, 1> MismatchedParams;
8378   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8379   TypoCorrection Correction;
8380   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8381   unsigned DiagMsg =
8382     IsLocalFriend ? diag::err_no_matching_local_friend :
8383     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8384     diag::err_member_decl_does_not_match;
8385   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8386                     IsLocalFriend ? Sema::LookupLocalFriendName
8387                                   : Sema::LookupOrdinaryName,
8388                     Sema::ForVisibleRedeclaration);
8389 
8390   NewFD->setInvalidDecl();
8391   if (IsLocalFriend)
8392     SemaRef.LookupName(Prev, S);
8393   else
8394     SemaRef.LookupQualifiedName(Prev, NewDC);
8395   assert(!Prev.isAmbiguous() &&
8396          "Cannot have an ambiguity in previous-declaration lookup");
8397   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8398   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8399                                 MD ? MD->getParent() : nullptr);
8400   if (!Prev.empty()) {
8401     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8402          Func != FuncEnd; ++Func) {
8403       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8404       if (FD &&
8405           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8406         // Add 1 to the index so that 0 can mean the mismatch didn't
8407         // involve a parameter
8408         unsigned ParamNum =
8409             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8410         NearMatches.push_back(std::make_pair(FD, ParamNum));
8411       }
8412     }
8413   // If the qualified name lookup yielded nothing, try typo correction
8414   } else if ((Correction = SemaRef.CorrectTypo(
8415                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8416                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8417                   IsLocalFriend ? nullptr : NewDC))) {
8418     // Set up everything for the call to ActOnFunctionDeclarator
8419     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8420                               ExtraArgs.D.getIdentifierLoc());
8421     Previous.clear();
8422     Previous.setLookupName(Correction.getCorrection());
8423     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8424                                     CDeclEnd = Correction.end();
8425          CDecl != CDeclEnd; ++CDecl) {
8426       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8427       if (FD && !FD->hasBody() &&
8428           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8429         Previous.addDecl(FD);
8430       }
8431     }
8432     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8433 
8434     NamedDecl *Result;
8435     // Retry building the function declaration with the new previous
8436     // declarations, and with errors suppressed.
8437     {
8438       // Trap errors.
8439       Sema::SFINAETrap Trap(SemaRef);
8440 
8441       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8442       // pieces need to verify the typo-corrected C++ declaration and hopefully
8443       // eliminate the need for the parameter pack ExtraArgs.
8444       Result = SemaRef.ActOnFunctionDeclarator(
8445           ExtraArgs.S, ExtraArgs.D,
8446           Correction.getCorrectionDecl()->getDeclContext(),
8447           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8448           ExtraArgs.AddToScope);
8449 
8450       if (Trap.hasErrorOccurred())
8451         Result = nullptr;
8452     }
8453 
8454     if (Result) {
8455       // Determine which correction we picked.
8456       Decl *Canonical = Result->getCanonicalDecl();
8457       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8458            I != E; ++I)
8459         if ((*I)->getCanonicalDecl() == Canonical)
8460           Correction.setCorrectionDecl(*I);
8461 
8462       // Let Sema know about the correction.
8463       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8464       SemaRef.diagnoseTypo(
8465           Correction,
8466           SemaRef.PDiag(IsLocalFriend
8467                           ? diag::err_no_matching_local_friend_suggest
8468                           : diag::err_member_decl_does_not_match_suggest)
8469             << Name << NewDC << IsDefinition);
8470       return Result;
8471     }
8472 
8473     // Pretend the typo correction never occurred
8474     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8475                               ExtraArgs.D.getIdentifierLoc());
8476     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8477     Previous.clear();
8478     Previous.setLookupName(Name);
8479   }
8480 
8481   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8482       << Name << NewDC << IsDefinition << NewFD->getLocation();
8483 
8484   bool NewFDisConst = false;
8485   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8486     NewFDisConst = NewMD->isConst();
8487 
8488   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8489        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8490        NearMatch != NearMatchEnd; ++NearMatch) {
8491     FunctionDecl *FD = NearMatch->first;
8492     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8493     bool FDisConst = MD && MD->isConst();
8494     bool IsMember = MD || !IsLocalFriend;
8495 
8496     // FIXME: These notes are poorly worded for the local friend case.
8497     if (unsigned Idx = NearMatch->second) {
8498       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8499       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8500       if (Loc.isInvalid()) Loc = FD->getLocation();
8501       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8502                                  : diag::note_local_decl_close_param_match)
8503         << Idx << FDParam->getType()
8504         << NewFD->getParamDecl(Idx - 1)->getType();
8505     } else if (FDisConst != NewFDisConst) {
8506       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8507           << NewFDisConst << FD->getSourceRange().getEnd();
8508     } else
8509       SemaRef.Diag(FD->getLocation(),
8510                    IsMember ? diag::note_member_def_close_match
8511                             : diag::note_local_decl_close_match);
8512   }
8513   return nullptr;
8514 }
8515 
8516 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8517   switch (D.getDeclSpec().getStorageClassSpec()) {
8518   default: llvm_unreachable("Unknown storage class!");
8519   case DeclSpec::SCS_auto:
8520   case DeclSpec::SCS_register:
8521   case DeclSpec::SCS_mutable:
8522     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8523                  diag::err_typecheck_sclass_func);
8524     D.getMutableDeclSpec().ClearStorageClassSpecs();
8525     D.setInvalidType();
8526     break;
8527   case DeclSpec::SCS_unspecified: break;
8528   case DeclSpec::SCS_extern:
8529     if (D.getDeclSpec().isExternInLinkageSpec())
8530       return SC_None;
8531     return SC_Extern;
8532   case DeclSpec::SCS_static: {
8533     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8534       // C99 6.7.1p5:
8535       //   The declaration of an identifier for a function that has
8536       //   block scope shall have no explicit storage-class specifier
8537       //   other than extern
8538       // See also (C++ [dcl.stc]p4).
8539       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8540                    diag::err_static_block_func);
8541       break;
8542     } else
8543       return SC_Static;
8544   }
8545   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8546   }
8547 
8548   // No explicit storage class has already been returned
8549   return SC_None;
8550 }
8551 
8552 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8553                                            DeclContext *DC, QualType &R,
8554                                            TypeSourceInfo *TInfo,
8555                                            StorageClass SC,
8556                                            bool &IsVirtualOkay) {
8557   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8558   DeclarationName Name = NameInfo.getName();
8559 
8560   FunctionDecl *NewFD = nullptr;
8561   bool isInline = D.getDeclSpec().isInlineSpecified();
8562 
8563   if (!SemaRef.getLangOpts().CPlusPlus) {
8564     // Determine whether the function was written with a
8565     // prototype. This true when:
8566     //   - there is a prototype in the declarator, or
8567     //   - the type R of the function is some kind of typedef or other non-
8568     //     attributed reference to a type name (which eventually refers to a
8569     //     function type).
8570     bool HasPrototype =
8571       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8572       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8573 
8574     NewFD = FunctionDecl::Create(
8575         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8576         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8577         ConstexprSpecKind::Unspecified,
8578         /*TrailingRequiresClause=*/nullptr);
8579     if (D.isInvalidType())
8580       NewFD->setInvalidDecl();
8581 
8582     return NewFD;
8583   }
8584 
8585   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8586 
8587   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8588   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8589     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8590                  diag::err_constexpr_wrong_decl_kind)
8591         << static_cast<int>(ConstexprKind);
8592     ConstexprKind = ConstexprSpecKind::Unspecified;
8593     D.getMutableDeclSpec().ClearConstexprSpec();
8594   }
8595   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8596 
8597   // Check that the return type is not an abstract class type.
8598   // For record types, this is done by the AbstractClassUsageDiagnoser once
8599   // the class has been completely parsed.
8600   if (!DC->isRecord() &&
8601       SemaRef.RequireNonAbstractType(
8602           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8603           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8604     D.setInvalidType();
8605 
8606   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8607     // This is a C++ constructor declaration.
8608     assert(DC->isRecord() &&
8609            "Constructors can only be declared in a member context");
8610 
8611     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8612     return CXXConstructorDecl::Create(
8613         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8614         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8615         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8616         InheritedConstructor(), TrailingRequiresClause);
8617 
8618   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8619     // This is a C++ destructor declaration.
8620     if (DC->isRecord()) {
8621       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8622       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8623       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8624           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8625           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8626           /*isImplicitlyDeclared=*/false, ConstexprKind,
8627           TrailingRequiresClause);
8628 
8629       // If the destructor needs an implicit exception specification, set it
8630       // now. FIXME: It'd be nice to be able to create the right type to start
8631       // with, but the type needs to reference the destructor declaration.
8632       if (SemaRef.getLangOpts().CPlusPlus11)
8633         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8634 
8635       IsVirtualOkay = true;
8636       return NewDD;
8637 
8638     } else {
8639       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8640       D.setInvalidType();
8641 
8642       // Create a FunctionDecl to satisfy the function definition parsing
8643       // code path.
8644       return FunctionDecl::Create(
8645           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8646           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8647           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8648     }
8649 
8650   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8651     if (!DC->isRecord()) {
8652       SemaRef.Diag(D.getIdentifierLoc(),
8653            diag::err_conv_function_not_member);
8654       return nullptr;
8655     }
8656 
8657     SemaRef.CheckConversionDeclarator(D, R, SC);
8658     if (D.isInvalidType())
8659       return nullptr;
8660 
8661     IsVirtualOkay = true;
8662     return CXXConversionDecl::Create(
8663         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8664         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8665         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8666         TrailingRequiresClause);
8667 
8668   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8669     if (TrailingRequiresClause)
8670       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8671                    diag::err_trailing_requires_clause_on_deduction_guide)
8672           << TrailingRequiresClause->getSourceRange();
8673     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8674 
8675     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8676                                          ExplicitSpecifier, NameInfo, R, TInfo,
8677                                          D.getEndLoc());
8678   } else if (DC->isRecord()) {
8679     // If the name of the function is the same as the name of the record,
8680     // then this must be an invalid constructor that has a return type.
8681     // (The parser checks for a return type and makes the declarator a
8682     // constructor if it has no return type).
8683     if (Name.getAsIdentifierInfo() &&
8684         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8685       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8686         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8687         << SourceRange(D.getIdentifierLoc());
8688       return nullptr;
8689     }
8690 
8691     // This is a C++ method declaration.
8692     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8693         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8694         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8695         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8696     IsVirtualOkay = !Ret->isStatic();
8697     return Ret;
8698   } else {
8699     bool isFriend =
8700         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8701     if (!isFriend && SemaRef.CurContext->isRecord())
8702       return nullptr;
8703 
8704     // Determine whether the function was written with a
8705     // prototype. This true when:
8706     //   - we're in C++ (where every function has a prototype),
8707     return FunctionDecl::Create(
8708         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8709         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8710         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8711   }
8712 }
8713 
8714 enum OpenCLParamType {
8715   ValidKernelParam,
8716   PtrPtrKernelParam,
8717   PtrKernelParam,
8718   InvalidAddrSpacePtrKernelParam,
8719   InvalidKernelParam,
8720   RecordKernelParam
8721 };
8722 
8723 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8724   // Size dependent types are just typedefs to normal integer types
8725   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8726   // integers other than by their names.
8727   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8728 
8729   // Remove typedefs one by one until we reach a typedef
8730   // for a size dependent type.
8731   QualType DesugaredTy = Ty;
8732   do {
8733     ArrayRef<StringRef> Names(SizeTypeNames);
8734     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8735     if (Names.end() != Match)
8736       return true;
8737 
8738     Ty = DesugaredTy;
8739     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8740   } while (DesugaredTy != Ty);
8741 
8742   return false;
8743 }
8744 
8745 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8746   if (PT->isDependentType())
8747     return InvalidKernelParam;
8748 
8749   if (PT->isPointerType() || PT->isReferenceType()) {
8750     QualType PointeeType = PT->getPointeeType();
8751     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8752         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8753         PointeeType.getAddressSpace() == LangAS::Default)
8754       return InvalidAddrSpacePtrKernelParam;
8755 
8756     if (PointeeType->isPointerType()) {
8757       // This is a pointer to pointer parameter.
8758       // Recursively check inner type.
8759       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8760       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8761           ParamKind == InvalidKernelParam)
8762         return ParamKind;
8763 
8764       return PtrPtrKernelParam;
8765     }
8766 
8767     // C++ for OpenCL v1.0 s2.4:
8768     // Moreover the types used in parameters of the kernel functions must be:
8769     // Standard layout types for pointer parameters. The same applies to
8770     // reference if an implementation supports them in kernel parameters.
8771     if (S.getLangOpts().OpenCLCPlusPlus &&
8772         !S.getOpenCLOptions().isAvailableOption(
8773             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8774         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8775         !PointeeType->isStandardLayoutType())
8776       return InvalidKernelParam;
8777 
8778     return PtrKernelParam;
8779   }
8780 
8781   // OpenCL v1.2 s6.9.k:
8782   // Arguments to kernel functions in a program cannot be declared with the
8783   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8784   // uintptr_t or a struct and/or union that contain fields declared to be one
8785   // of these built-in scalar types.
8786   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8787     return InvalidKernelParam;
8788 
8789   if (PT->isImageType())
8790     return PtrKernelParam;
8791 
8792   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8793     return InvalidKernelParam;
8794 
8795   // OpenCL extension spec v1.2 s9.5:
8796   // This extension adds support for half scalar and vector types as built-in
8797   // types that can be used for arithmetic operations, conversions etc.
8798   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8799       PT->isHalfType())
8800     return InvalidKernelParam;
8801 
8802   // Look into an array argument to check if it has a forbidden type.
8803   if (PT->isArrayType()) {
8804     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8805     // Call ourself to check an underlying type of an array. Since the
8806     // getPointeeOrArrayElementType returns an innermost type which is not an
8807     // array, this recursive call only happens once.
8808     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8809   }
8810 
8811   // C++ for OpenCL v1.0 s2.4:
8812   // Moreover the types used in parameters of the kernel functions must be:
8813   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8814   // types) for parameters passed by value;
8815   if (S.getLangOpts().OpenCLCPlusPlus &&
8816       !S.getOpenCLOptions().isAvailableOption(
8817           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8818       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8819     return InvalidKernelParam;
8820 
8821   if (PT->isRecordType())
8822     return RecordKernelParam;
8823 
8824   return ValidKernelParam;
8825 }
8826 
8827 static void checkIsValidOpenCLKernelParameter(
8828   Sema &S,
8829   Declarator &D,
8830   ParmVarDecl *Param,
8831   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8832   QualType PT = Param->getType();
8833 
8834   // Cache the valid types we encounter to avoid rechecking structs that are
8835   // used again
8836   if (ValidTypes.count(PT.getTypePtr()))
8837     return;
8838 
8839   switch (getOpenCLKernelParameterType(S, PT)) {
8840   case PtrPtrKernelParam:
8841     // OpenCL v3.0 s6.11.a:
8842     // A kernel function argument cannot be declared as a pointer to a pointer
8843     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8844     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8845       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8846       D.setInvalidType();
8847       return;
8848     }
8849 
8850     ValidTypes.insert(PT.getTypePtr());
8851     return;
8852 
8853   case InvalidAddrSpacePtrKernelParam:
8854     // OpenCL v1.0 s6.5:
8855     // __kernel function arguments declared to be a pointer of a type can point
8856     // to one of the following address spaces only : __global, __local or
8857     // __constant.
8858     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8859     D.setInvalidType();
8860     return;
8861 
8862     // OpenCL v1.2 s6.9.k:
8863     // Arguments to kernel functions in a program cannot be declared with the
8864     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8865     // uintptr_t or a struct and/or union that contain fields declared to be
8866     // one of these built-in scalar types.
8867 
8868   case InvalidKernelParam:
8869     // OpenCL v1.2 s6.8 n:
8870     // A kernel function argument cannot be declared
8871     // of event_t type.
8872     // Do not diagnose half type since it is diagnosed as invalid argument
8873     // type for any function elsewhere.
8874     if (!PT->isHalfType()) {
8875       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8876 
8877       // Explain what typedefs are involved.
8878       const TypedefType *Typedef = nullptr;
8879       while ((Typedef = PT->getAs<TypedefType>())) {
8880         SourceLocation Loc = Typedef->getDecl()->getLocation();
8881         // SourceLocation may be invalid for a built-in type.
8882         if (Loc.isValid())
8883           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8884         PT = Typedef->desugar();
8885       }
8886     }
8887 
8888     D.setInvalidType();
8889     return;
8890 
8891   case PtrKernelParam:
8892   case ValidKernelParam:
8893     ValidTypes.insert(PT.getTypePtr());
8894     return;
8895 
8896   case RecordKernelParam:
8897     break;
8898   }
8899 
8900   // Track nested structs we will inspect
8901   SmallVector<const Decl *, 4> VisitStack;
8902 
8903   // Track where we are in the nested structs. Items will migrate from
8904   // VisitStack to HistoryStack as we do the DFS for bad field.
8905   SmallVector<const FieldDecl *, 4> HistoryStack;
8906   HistoryStack.push_back(nullptr);
8907 
8908   // At this point we already handled everything except of a RecordType or
8909   // an ArrayType of a RecordType.
8910   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8911   const RecordType *RecTy =
8912       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8913   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8914 
8915   VisitStack.push_back(RecTy->getDecl());
8916   assert(VisitStack.back() && "First decl null?");
8917 
8918   do {
8919     const Decl *Next = VisitStack.pop_back_val();
8920     if (!Next) {
8921       assert(!HistoryStack.empty());
8922       // Found a marker, we have gone up a level
8923       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8924         ValidTypes.insert(Hist->getType().getTypePtr());
8925 
8926       continue;
8927     }
8928 
8929     // Adds everything except the original parameter declaration (which is not a
8930     // field itself) to the history stack.
8931     const RecordDecl *RD;
8932     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8933       HistoryStack.push_back(Field);
8934 
8935       QualType FieldTy = Field->getType();
8936       // Other field types (known to be valid or invalid) are handled while we
8937       // walk around RecordDecl::fields().
8938       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8939              "Unexpected type.");
8940       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8941 
8942       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8943     } else {
8944       RD = cast<RecordDecl>(Next);
8945     }
8946 
8947     // Add a null marker so we know when we've gone back up a level
8948     VisitStack.push_back(nullptr);
8949 
8950     for (const auto *FD : RD->fields()) {
8951       QualType QT = FD->getType();
8952 
8953       if (ValidTypes.count(QT.getTypePtr()))
8954         continue;
8955 
8956       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8957       if (ParamType == ValidKernelParam)
8958         continue;
8959 
8960       if (ParamType == RecordKernelParam) {
8961         VisitStack.push_back(FD);
8962         continue;
8963       }
8964 
8965       // OpenCL v1.2 s6.9.p:
8966       // Arguments to kernel functions that are declared to be a struct or union
8967       // do not allow OpenCL objects to be passed as elements of the struct or
8968       // union.
8969       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8970           ParamType == InvalidAddrSpacePtrKernelParam) {
8971         S.Diag(Param->getLocation(),
8972                diag::err_record_with_pointers_kernel_param)
8973           << PT->isUnionType()
8974           << PT;
8975       } else {
8976         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8977       }
8978 
8979       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8980           << OrigRecDecl->getDeclName();
8981 
8982       // We have an error, now let's go back up through history and show where
8983       // the offending field came from
8984       for (ArrayRef<const FieldDecl *>::const_iterator
8985                I = HistoryStack.begin() + 1,
8986                E = HistoryStack.end();
8987            I != E; ++I) {
8988         const FieldDecl *OuterField = *I;
8989         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8990           << OuterField->getType();
8991       }
8992 
8993       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8994         << QT->isPointerType()
8995         << QT;
8996       D.setInvalidType();
8997       return;
8998     }
8999   } while (!VisitStack.empty());
9000 }
9001 
9002 /// Find the DeclContext in which a tag is implicitly declared if we see an
9003 /// elaborated type specifier in the specified context, and lookup finds
9004 /// nothing.
9005 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9006   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9007     DC = DC->getParent();
9008   return DC;
9009 }
9010 
9011 /// Find the Scope in which a tag is implicitly declared if we see an
9012 /// elaborated type specifier in the specified context, and lookup finds
9013 /// nothing.
9014 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9015   while (S->isClassScope() ||
9016          (LangOpts.CPlusPlus &&
9017           S->isFunctionPrototypeScope()) ||
9018          ((S->getFlags() & Scope::DeclScope) == 0) ||
9019          (S->getEntity() && S->getEntity()->isTransparentContext()))
9020     S = S->getParent();
9021   return S;
9022 }
9023 
9024 NamedDecl*
9025 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9026                               TypeSourceInfo *TInfo, LookupResult &Previous,
9027                               MultiTemplateParamsArg TemplateParamListsRef,
9028                               bool &AddToScope) {
9029   QualType R = TInfo->getType();
9030 
9031   assert(R->isFunctionType());
9032   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9033     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9034 
9035   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9036   for (TemplateParameterList *TPL : TemplateParamListsRef)
9037     TemplateParamLists.push_back(TPL);
9038   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9039     if (!TemplateParamLists.empty() &&
9040         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9041       TemplateParamLists.back() = Invented;
9042     else
9043       TemplateParamLists.push_back(Invented);
9044   }
9045 
9046   // TODO: consider using NameInfo for diagnostic.
9047   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9048   DeclarationName Name = NameInfo.getName();
9049   StorageClass SC = getFunctionStorageClass(*this, D);
9050 
9051   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9052     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9053          diag::err_invalid_thread)
9054       << DeclSpec::getSpecifierName(TSCS);
9055 
9056   if (D.isFirstDeclarationOfMember())
9057     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9058                            D.getIdentifierLoc());
9059 
9060   bool isFriend = false;
9061   FunctionTemplateDecl *FunctionTemplate = nullptr;
9062   bool isMemberSpecialization = false;
9063   bool isFunctionTemplateSpecialization = false;
9064 
9065   bool isDependentClassScopeExplicitSpecialization = false;
9066   bool HasExplicitTemplateArgs = false;
9067   TemplateArgumentListInfo TemplateArgs;
9068 
9069   bool isVirtualOkay = false;
9070 
9071   DeclContext *OriginalDC = DC;
9072   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9073 
9074   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9075                                               isVirtualOkay);
9076   if (!NewFD) return nullptr;
9077 
9078   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9079     NewFD->setTopLevelDeclInObjCContainer();
9080 
9081   // Set the lexical context. If this is a function-scope declaration, or has a
9082   // C++ scope specifier, or is the object of a friend declaration, the lexical
9083   // context will be different from the semantic context.
9084   NewFD->setLexicalDeclContext(CurContext);
9085 
9086   if (IsLocalExternDecl)
9087     NewFD->setLocalExternDecl();
9088 
9089   if (getLangOpts().CPlusPlus) {
9090     bool isInline = D.getDeclSpec().isInlineSpecified();
9091     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9092     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9093     isFriend = D.getDeclSpec().isFriendSpecified();
9094     if (isFriend && !isInline && D.isFunctionDefinition()) {
9095       // C++ [class.friend]p5
9096       //   A function can be defined in a friend declaration of a
9097       //   class . . . . Such a function is implicitly inline.
9098       NewFD->setImplicitlyInline();
9099     }
9100 
9101     // If this is a method defined in an __interface, and is not a constructor
9102     // or an overloaded operator, then set the pure flag (isVirtual will already
9103     // return true).
9104     if (const CXXRecordDecl *Parent =
9105           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9106       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9107         NewFD->setPure(true);
9108 
9109       // C++ [class.union]p2
9110       //   A union can have member functions, but not virtual functions.
9111       if (isVirtual && Parent->isUnion()) {
9112         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9113         NewFD->setInvalidDecl();
9114       }
9115     }
9116 
9117     SetNestedNameSpecifier(*this, NewFD, D);
9118     isMemberSpecialization = false;
9119     isFunctionTemplateSpecialization = false;
9120     if (D.isInvalidType())
9121       NewFD->setInvalidDecl();
9122 
9123     // Match up the template parameter lists with the scope specifier, then
9124     // determine whether we have a template or a template specialization.
9125     bool Invalid = false;
9126     TemplateParameterList *TemplateParams =
9127         MatchTemplateParametersToScopeSpecifier(
9128             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9129             D.getCXXScopeSpec(),
9130             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9131                 ? D.getName().TemplateId
9132                 : nullptr,
9133             TemplateParamLists, isFriend, isMemberSpecialization,
9134             Invalid);
9135     if (TemplateParams) {
9136       // Check that we can declare a template here.
9137       if (CheckTemplateDeclScope(S, TemplateParams))
9138         NewFD->setInvalidDecl();
9139 
9140       if (TemplateParams->size() > 0) {
9141         // This is a function template
9142 
9143         // A destructor cannot be a template.
9144         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9145           Diag(NewFD->getLocation(), diag::err_destructor_template);
9146           NewFD->setInvalidDecl();
9147         }
9148 
9149         // If we're adding a template to a dependent context, we may need to
9150         // rebuilding some of the types used within the template parameter list,
9151         // now that we know what the current instantiation is.
9152         if (DC->isDependentContext()) {
9153           ContextRAII SavedContext(*this, DC);
9154           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9155             Invalid = true;
9156         }
9157 
9158         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9159                                                         NewFD->getLocation(),
9160                                                         Name, TemplateParams,
9161                                                         NewFD);
9162         FunctionTemplate->setLexicalDeclContext(CurContext);
9163         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9164 
9165         // For source fidelity, store the other template param lists.
9166         if (TemplateParamLists.size() > 1) {
9167           NewFD->setTemplateParameterListsInfo(Context,
9168               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9169                   .drop_back(1));
9170         }
9171       } else {
9172         // This is a function template specialization.
9173         isFunctionTemplateSpecialization = true;
9174         // For source fidelity, store all the template param lists.
9175         if (TemplateParamLists.size() > 0)
9176           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9177 
9178         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9179         if (isFriend) {
9180           // We want to remove the "template<>", found here.
9181           SourceRange RemoveRange = TemplateParams->getSourceRange();
9182 
9183           // If we remove the template<> and the name is not a
9184           // template-id, we're actually silently creating a problem:
9185           // the friend declaration will refer to an untemplated decl,
9186           // and clearly the user wants a template specialization.  So
9187           // we need to insert '<>' after the name.
9188           SourceLocation InsertLoc;
9189           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9190             InsertLoc = D.getName().getSourceRange().getEnd();
9191             InsertLoc = getLocForEndOfToken(InsertLoc);
9192           }
9193 
9194           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9195             << Name << RemoveRange
9196             << FixItHint::CreateRemoval(RemoveRange)
9197             << FixItHint::CreateInsertion(InsertLoc, "<>");
9198         }
9199       }
9200     } else {
9201       // Check that we can declare a template here.
9202       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9203           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9204         NewFD->setInvalidDecl();
9205 
9206       // All template param lists were matched against the scope specifier:
9207       // this is NOT (an explicit specialization of) a template.
9208       if (TemplateParamLists.size() > 0)
9209         // For source fidelity, store all the template param lists.
9210         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9211     }
9212 
9213     if (Invalid) {
9214       NewFD->setInvalidDecl();
9215       if (FunctionTemplate)
9216         FunctionTemplate->setInvalidDecl();
9217     }
9218 
9219     // C++ [dcl.fct.spec]p5:
9220     //   The virtual specifier shall only be used in declarations of
9221     //   nonstatic class member functions that appear within a
9222     //   member-specification of a class declaration; see 10.3.
9223     //
9224     if (isVirtual && !NewFD->isInvalidDecl()) {
9225       if (!isVirtualOkay) {
9226         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9227              diag::err_virtual_non_function);
9228       } else if (!CurContext->isRecord()) {
9229         // 'virtual' was specified outside of the class.
9230         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9231              diag::err_virtual_out_of_class)
9232           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9233       } else if (NewFD->getDescribedFunctionTemplate()) {
9234         // C++ [temp.mem]p3:
9235         //  A member function template shall not be virtual.
9236         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9237              diag::err_virtual_member_function_template)
9238           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9239       } else {
9240         // Okay: Add virtual to the method.
9241         NewFD->setVirtualAsWritten(true);
9242       }
9243 
9244       if (getLangOpts().CPlusPlus14 &&
9245           NewFD->getReturnType()->isUndeducedType())
9246         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9247     }
9248 
9249     if (getLangOpts().CPlusPlus14 &&
9250         (NewFD->isDependentContext() ||
9251          (isFriend && CurContext->isDependentContext())) &&
9252         NewFD->getReturnType()->isUndeducedType()) {
9253       // If the function template is referenced directly (for instance, as a
9254       // member of the current instantiation), pretend it has a dependent type.
9255       // This is not really justified by the standard, but is the only sane
9256       // thing to do.
9257       // FIXME: For a friend function, we have not marked the function as being
9258       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9259       const FunctionProtoType *FPT =
9260           NewFD->getType()->castAs<FunctionProtoType>();
9261       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9262       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9263                                              FPT->getExtProtoInfo()));
9264     }
9265 
9266     // C++ [dcl.fct.spec]p3:
9267     //  The inline specifier shall not appear on a block scope function
9268     //  declaration.
9269     if (isInline && !NewFD->isInvalidDecl()) {
9270       if (CurContext->isFunctionOrMethod()) {
9271         // 'inline' is not allowed on block scope function declaration.
9272         Diag(D.getDeclSpec().getInlineSpecLoc(),
9273              diag::err_inline_declaration_block_scope) << Name
9274           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9275       }
9276     }
9277 
9278     // C++ [dcl.fct.spec]p6:
9279     //  The explicit specifier shall be used only in the declaration of a
9280     //  constructor or conversion function within its class definition;
9281     //  see 12.3.1 and 12.3.2.
9282     if (hasExplicit && !NewFD->isInvalidDecl() &&
9283         !isa<CXXDeductionGuideDecl>(NewFD)) {
9284       if (!CurContext->isRecord()) {
9285         // 'explicit' was specified outside of the class.
9286         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9287              diag::err_explicit_out_of_class)
9288             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9289       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9290                  !isa<CXXConversionDecl>(NewFD)) {
9291         // 'explicit' was specified on a function that wasn't a constructor
9292         // or conversion function.
9293         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9294              diag::err_explicit_non_ctor_or_conv_function)
9295             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9296       }
9297     }
9298 
9299     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9300     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9301       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9302       // are implicitly inline.
9303       NewFD->setImplicitlyInline();
9304 
9305       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9306       // be either constructors or to return a literal type. Therefore,
9307       // destructors cannot be declared constexpr.
9308       if (isa<CXXDestructorDecl>(NewFD) &&
9309           (!getLangOpts().CPlusPlus20 ||
9310            ConstexprKind == ConstexprSpecKind::Consteval)) {
9311         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9312             << static_cast<int>(ConstexprKind);
9313         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9314                                     ? ConstexprSpecKind::Unspecified
9315                                     : ConstexprSpecKind::Constexpr);
9316       }
9317       // C++20 [dcl.constexpr]p2: An allocation function, or a
9318       // deallocation function shall not be declared with the consteval
9319       // specifier.
9320       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9321           (NewFD->getOverloadedOperator() == OO_New ||
9322            NewFD->getOverloadedOperator() == OO_Array_New ||
9323            NewFD->getOverloadedOperator() == OO_Delete ||
9324            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9325         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9326              diag::err_invalid_consteval_decl_kind)
9327             << NewFD;
9328         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9329       }
9330     }
9331 
9332     // If __module_private__ was specified, mark the function accordingly.
9333     if (D.getDeclSpec().isModulePrivateSpecified()) {
9334       if (isFunctionTemplateSpecialization) {
9335         SourceLocation ModulePrivateLoc
9336           = D.getDeclSpec().getModulePrivateSpecLoc();
9337         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9338           << 0
9339           << FixItHint::CreateRemoval(ModulePrivateLoc);
9340       } else {
9341         NewFD->setModulePrivate();
9342         if (FunctionTemplate)
9343           FunctionTemplate->setModulePrivate();
9344       }
9345     }
9346 
9347     if (isFriend) {
9348       if (FunctionTemplate) {
9349         FunctionTemplate->setObjectOfFriendDecl();
9350         FunctionTemplate->setAccess(AS_public);
9351       }
9352       NewFD->setObjectOfFriendDecl();
9353       NewFD->setAccess(AS_public);
9354     }
9355 
9356     // If a function is defined as defaulted or deleted, mark it as such now.
9357     // We'll do the relevant checks on defaulted / deleted functions later.
9358     switch (D.getFunctionDefinitionKind()) {
9359     case FunctionDefinitionKind::Declaration:
9360     case FunctionDefinitionKind::Definition:
9361       break;
9362 
9363     case FunctionDefinitionKind::Defaulted:
9364       NewFD->setDefaulted();
9365       break;
9366 
9367     case FunctionDefinitionKind::Deleted:
9368       NewFD->setDeletedAsWritten();
9369       break;
9370     }
9371 
9372     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9373         D.isFunctionDefinition()) {
9374       // C++ [class.mfct]p2:
9375       //   A member function may be defined (8.4) in its class definition, in
9376       //   which case it is an inline member function (7.1.2)
9377       NewFD->setImplicitlyInline();
9378     }
9379 
9380     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9381         !CurContext->isRecord()) {
9382       // C++ [class.static]p1:
9383       //   A data or function member of a class may be declared static
9384       //   in a class definition, in which case it is a static member of
9385       //   the class.
9386 
9387       // Complain about the 'static' specifier if it's on an out-of-line
9388       // member function definition.
9389 
9390       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9391       // member function template declaration and class member template
9392       // declaration (MSVC versions before 2015), warn about this.
9393       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9394            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9395              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9396            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9397            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9398         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9399     }
9400 
9401     // C++11 [except.spec]p15:
9402     //   A deallocation function with no exception-specification is treated
9403     //   as if it were specified with noexcept(true).
9404     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9405     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9406          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9407         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9408       NewFD->setType(Context.getFunctionType(
9409           FPT->getReturnType(), FPT->getParamTypes(),
9410           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9411   }
9412 
9413   // Filter out previous declarations that don't match the scope.
9414   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9415                        D.getCXXScopeSpec().isNotEmpty() ||
9416                        isMemberSpecialization ||
9417                        isFunctionTemplateSpecialization);
9418 
9419   // Handle GNU asm-label extension (encoded as an attribute).
9420   if (Expr *E = (Expr*) D.getAsmLabel()) {
9421     // The parser guarantees this is a string.
9422     StringLiteral *SE = cast<StringLiteral>(E);
9423     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9424                                         /*IsLiteralLabel=*/true,
9425                                         SE->getStrTokenLoc(0)));
9426   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9427     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9428       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9429     if (I != ExtnameUndeclaredIdentifiers.end()) {
9430       if (isDeclExternC(NewFD)) {
9431         NewFD->addAttr(I->second);
9432         ExtnameUndeclaredIdentifiers.erase(I);
9433       } else
9434         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9435             << /*Variable*/0 << NewFD;
9436     }
9437   }
9438 
9439   // Copy the parameter declarations from the declarator D to the function
9440   // declaration NewFD, if they are available.  First scavenge them into Params.
9441   SmallVector<ParmVarDecl*, 16> Params;
9442   unsigned FTIIdx;
9443   if (D.isFunctionDeclarator(FTIIdx)) {
9444     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9445 
9446     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9447     // function that takes no arguments, not a function that takes a
9448     // single void argument.
9449     // We let through "const void" here because Sema::GetTypeForDeclarator
9450     // already checks for that case.
9451     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9452       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9453         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9454         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9455         Param->setDeclContext(NewFD);
9456         Params.push_back(Param);
9457 
9458         if (Param->isInvalidDecl())
9459           NewFD->setInvalidDecl();
9460       }
9461     }
9462 
9463     if (!getLangOpts().CPlusPlus) {
9464       // In C, find all the tag declarations from the prototype and move them
9465       // into the function DeclContext. Remove them from the surrounding tag
9466       // injection context of the function, which is typically but not always
9467       // the TU.
9468       DeclContext *PrototypeTagContext =
9469           getTagInjectionContext(NewFD->getLexicalDeclContext());
9470       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9471         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9472 
9473         // We don't want to reparent enumerators. Look at their parent enum
9474         // instead.
9475         if (!TD) {
9476           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9477             TD = cast<EnumDecl>(ECD->getDeclContext());
9478         }
9479         if (!TD)
9480           continue;
9481         DeclContext *TagDC = TD->getLexicalDeclContext();
9482         if (!TagDC->containsDecl(TD))
9483           continue;
9484         TagDC->removeDecl(TD);
9485         TD->setDeclContext(NewFD);
9486         NewFD->addDecl(TD);
9487 
9488         // Preserve the lexical DeclContext if it is not the surrounding tag
9489         // injection context of the FD. In this example, the semantic context of
9490         // E will be f and the lexical context will be S, while both the
9491         // semantic and lexical contexts of S will be f:
9492         //   void f(struct S { enum E { a } f; } s);
9493         if (TagDC != PrototypeTagContext)
9494           TD->setLexicalDeclContext(TagDC);
9495       }
9496     }
9497   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9498     // When we're declaring a function with a typedef, typeof, etc as in the
9499     // following example, we'll need to synthesize (unnamed)
9500     // parameters for use in the declaration.
9501     //
9502     // @code
9503     // typedef void fn(int);
9504     // fn f;
9505     // @endcode
9506 
9507     // Synthesize a parameter for each argument type.
9508     for (const auto &AI : FT->param_types()) {
9509       ParmVarDecl *Param =
9510           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9511       Param->setScopeInfo(0, Params.size());
9512       Params.push_back(Param);
9513     }
9514   } else {
9515     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9516            "Should not need args for typedef of non-prototype fn");
9517   }
9518 
9519   // Finally, we know we have the right number of parameters, install them.
9520   NewFD->setParams(Params);
9521 
9522   if (D.getDeclSpec().isNoreturnSpecified())
9523     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9524                                            D.getDeclSpec().getNoreturnSpecLoc(),
9525                                            AttributeCommonInfo::AS_Keyword));
9526 
9527   // Functions returning a variably modified type violate C99 6.7.5.2p2
9528   // because all functions have linkage.
9529   if (!NewFD->isInvalidDecl() &&
9530       NewFD->getReturnType()->isVariablyModifiedType()) {
9531     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9532     NewFD->setInvalidDecl();
9533   }
9534 
9535   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9536   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9537       !NewFD->hasAttr<SectionAttr>())
9538     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9539         Context, PragmaClangTextSection.SectionName,
9540         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9541 
9542   // Apply an implicit SectionAttr if #pragma code_seg is active.
9543   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9544       !NewFD->hasAttr<SectionAttr>()) {
9545     NewFD->addAttr(SectionAttr::CreateImplicit(
9546         Context, CodeSegStack.CurrentValue->getString(),
9547         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9548         SectionAttr::Declspec_allocate));
9549     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9550                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9551                          ASTContext::PSF_Read,
9552                      NewFD))
9553       NewFD->dropAttr<SectionAttr>();
9554   }
9555 
9556   // Apply an implicit CodeSegAttr from class declspec or
9557   // apply an implicit SectionAttr from #pragma code_seg if active.
9558   if (!NewFD->hasAttr<CodeSegAttr>()) {
9559     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9560                                                                  D.isFunctionDefinition())) {
9561       NewFD->addAttr(SAttr);
9562     }
9563   }
9564 
9565   // Handle attributes.
9566   ProcessDeclAttributes(S, NewFD, D);
9567 
9568   if (getLangOpts().OpenCL) {
9569     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9570     // type declaration will generate a compilation error.
9571     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9572     if (AddressSpace != LangAS::Default) {
9573       Diag(NewFD->getLocation(),
9574            diag::err_opencl_return_value_with_address_space);
9575       NewFD->setInvalidDecl();
9576     }
9577   }
9578 
9579   if (!getLangOpts().CPlusPlus) {
9580     // Perform semantic checking on the function declaration.
9581     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9582       CheckMain(NewFD, D.getDeclSpec());
9583 
9584     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9585       CheckMSVCRTEntryPoint(NewFD);
9586 
9587     if (!NewFD->isInvalidDecl())
9588       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9589                                                   isMemberSpecialization));
9590     else if (!Previous.empty())
9591       // Recover gracefully from an invalid redeclaration.
9592       D.setRedeclaration(true);
9593     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9594             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9595            "previous declaration set still overloaded");
9596 
9597     // Diagnose no-prototype function declarations with calling conventions that
9598     // don't support variadic calls. Only do this in C and do it after merging
9599     // possibly prototyped redeclarations.
9600     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9601     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9602       CallingConv CC = FT->getExtInfo().getCC();
9603       if (!supportsVariadicCall(CC)) {
9604         // Windows system headers sometimes accidentally use stdcall without
9605         // (void) parameters, so we relax this to a warning.
9606         int DiagID =
9607             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9608         Diag(NewFD->getLocation(), DiagID)
9609             << FunctionType::getNameForCallConv(CC);
9610       }
9611     }
9612 
9613    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9614        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9615      checkNonTrivialCUnion(NewFD->getReturnType(),
9616                            NewFD->getReturnTypeSourceRange().getBegin(),
9617                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9618   } else {
9619     // C++11 [replacement.functions]p3:
9620     //  The program's definitions shall not be specified as inline.
9621     //
9622     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9623     //
9624     // Suppress the diagnostic if the function is __attribute__((used)), since
9625     // that forces an external definition to be emitted.
9626     if (D.getDeclSpec().isInlineSpecified() &&
9627         NewFD->isReplaceableGlobalAllocationFunction() &&
9628         !NewFD->hasAttr<UsedAttr>())
9629       Diag(D.getDeclSpec().getInlineSpecLoc(),
9630            diag::ext_operator_new_delete_declared_inline)
9631         << NewFD->getDeclName();
9632 
9633     // If the declarator is a template-id, translate the parser's template
9634     // argument list into our AST format.
9635     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9636       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9637       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9638       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9639       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9640                                          TemplateId->NumArgs);
9641       translateTemplateArguments(TemplateArgsPtr,
9642                                  TemplateArgs);
9643 
9644       HasExplicitTemplateArgs = true;
9645 
9646       if (NewFD->isInvalidDecl()) {
9647         HasExplicitTemplateArgs = false;
9648       } else if (FunctionTemplate) {
9649         // Function template with explicit template arguments.
9650         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9651           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9652 
9653         HasExplicitTemplateArgs = false;
9654       } else {
9655         assert((isFunctionTemplateSpecialization ||
9656                 D.getDeclSpec().isFriendSpecified()) &&
9657                "should have a 'template<>' for this decl");
9658         // "friend void foo<>(int);" is an implicit specialization decl.
9659         isFunctionTemplateSpecialization = true;
9660       }
9661     } else if (isFriend && isFunctionTemplateSpecialization) {
9662       // This combination is only possible in a recovery case;  the user
9663       // wrote something like:
9664       //   template <> friend void foo(int);
9665       // which we're recovering from as if the user had written:
9666       //   friend void foo<>(int);
9667       // Go ahead and fake up a template id.
9668       HasExplicitTemplateArgs = true;
9669       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9670       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9671     }
9672 
9673     // We do not add HD attributes to specializations here because
9674     // they may have different constexpr-ness compared to their
9675     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9676     // may end up with different effective targets. Instead, a
9677     // specialization inherits its target attributes from its template
9678     // in the CheckFunctionTemplateSpecialization() call below.
9679     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9680       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9681 
9682     // If it's a friend (and only if it's a friend), it's possible
9683     // that either the specialized function type or the specialized
9684     // template is dependent, and therefore matching will fail.  In
9685     // this case, don't check the specialization yet.
9686     if (isFunctionTemplateSpecialization && isFriend &&
9687         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9688          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9689              TemplateArgs.arguments()))) {
9690       assert(HasExplicitTemplateArgs &&
9691              "friend function specialization without template args");
9692       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9693                                                        Previous))
9694         NewFD->setInvalidDecl();
9695     } else if (isFunctionTemplateSpecialization) {
9696       if (CurContext->isDependentContext() && CurContext->isRecord()
9697           && !isFriend) {
9698         isDependentClassScopeExplicitSpecialization = true;
9699       } else if (!NewFD->isInvalidDecl() &&
9700                  CheckFunctionTemplateSpecialization(
9701                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9702                      Previous))
9703         NewFD->setInvalidDecl();
9704 
9705       // C++ [dcl.stc]p1:
9706       //   A storage-class-specifier shall not be specified in an explicit
9707       //   specialization (14.7.3)
9708       FunctionTemplateSpecializationInfo *Info =
9709           NewFD->getTemplateSpecializationInfo();
9710       if (Info && SC != SC_None) {
9711         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9712           Diag(NewFD->getLocation(),
9713                diag::err_explicit_specialization_inconsistent_storage_class)
9714             << SC
9715             << FixItHint::CreateRemoval(
9716                                       D.getDeclSpec().getStorageClassSpecLoc());
9717 
9718         else
9719           Diag(NewFD->getLocation(),
9720                diag::ext_explicit_specialization_storage_class)
9721             << FixItHint::CreateRemoval(
9722                                       D.getDeclSpec().getStorageClassSpecLoc());
9723       }
9724     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9725       if (CheckMemberSpecialization(NewFD, Previous))
9726           NewFD->setInvalidDecl();
9727     }
9728 
9729     // Perform semantic checking on the function declaration.
9730     if (!isDependentClassScopeExplicitSpecialization) {
9731       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9732         CheckMain(NewFD, D.getDeclSpec());
9733 
9734       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9735         CheckMSVCRTEntryPoint(NewFD);
9736 
9737       if (!NewFD->isInvalidDecl())
9738         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9739                                                     isMemberSpecialization));
9740       else if (!Previous.empty())
9741         // Recover gracefully from an invalid redeclaration.
9742         D.setRedeclaration(true);
9743     }
9744 
9745     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9746             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9747            "previous declaration set still overloaded");
9748 
9749     NamedDecl *PrincipalDecl = (FunctionTemplate
9750                                 ? cast<NamedDecl>(FunctionTemplate)
9751                                 : NewFD);
9752 
9753     if (isFriend && NewFD->getPreviousDecl()) {
9754       AccessSpecifier Access = AS_public;
9755       if (!NewFD->isInvalidDecl())
9756         Access = NewFD->getPreviousDecl()->getAccess();
9757 
9758       NewFD->setAccess(Access);
9759       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9760     }
9761 
9762     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9763         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9764       PrincipalDecl->setNonMemberOperator();
9765 
9766     // If we have a function template, check the template parameter
9767     // list. This will check and merge default template arguments.
9768     if (FunctionTemplate) {
9769       FunctionTemplateDecl *PrevTemplate =
9770                                      FunctionTemplate->getPreviousDecl();
9771       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9772                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9773                                     : nullptr,
9774                             D.getDeclSpec().isFriendSpecified()
9775                               ? (D.isFunctionDefinition()
9776                                    ? TPC_FriendFunctionTemplateDefinition
9777                                    : TPC_FriendFunctionTemplate)
9778                               : (D.getCXXScopeSpec().isSet() &&
9779                                  DC && DC->isRecord() &&
9780                                  DC->isDependentContext())
9781                                   ? TPC_ClassTemplateMember
9782                                   : TPC_FunctionTemplate);
9783     }
9784 
9785     if (NewFD->isInvalidDecl()) {
9786       // Ignore all the rest of this.
9787     } else if (!D.isRedeclaration()) {
9788       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9789                                        AddToScope };
9790       // Fake up an access specifier if it's supposed to be a class member.
9791       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9792         NewFD->setAccess(AS_public);
9793 
9794       // Qualified decls generally require a previous declaration.
9795       if (D.getCXXScopeSpec().isSet()) {
9796         // ...with the major exception of templated-scope or
9797         // dependent-scope friend declarations.
9798 
9799         // TODO: we currently also suppress this check in dependent
9800         // contexts because (1) the parameter depth will be off when
9801         // matching friend templates and (2) we might actually be
9802         // selecting a friend based on a dependent factor.  But there
9803         // are situations where these conditions don't apply and we
9804         // can actually do this check immediately.
9805         //
9806         // Unless the scope is dependent, it's always an error if qualified
9807         // redeclaration lookup found nothing at all. Diagnose that now;
9808         // nothing will diagnose that error later.
9809         if (isFriend &&
9810             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9811              (!Previous.empty() && CurContext->isDependentContext()))) {
9812           // ignore these
9813         } else if (NewFD->isCPUDispatchMultiVersion() ||
9814                    NewFD->isCPUSpecificMultiVersion()) {
9815           // ignore this, we allow the redeclaration behavior here to create new
9816           // versions of the function.
9817         } else {
9818           // The user tried to provide an out-of-line definition for a
9819           // function that is a member of a class or namespace, but there
9820           // was no such member function declared (C++ [class.mfct]p2,
9821           // C++ [namespace.memdef]p2). For example:
9822           //
9823           // class X {
9824           //   void f() const;
9825           // };
9826           //
9827           // void X::f() { } // ill-formed
9828           //
9829           // Complain about this problem, and attempt to suggest close
9830           // matches (e.g., those that differ only in cv-qualifiers and
9831           // whether the parameter types are references).
9832 
9833           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9834                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9835             AddToScope = ExtraArgs.AddToScope;
9836             return Result;
9837           }
9838         }
9839 
9840         // Unqualified local friend declarations are required to resolve
9841         // to something.
9842       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9843         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9844                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9845           AddToScope = ExtraArgs.AddToScope;
9846           return Result;
9847         }
9848       }
9849     } else if (!D.isFunctionDefinition() &&
9850                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9851                !isFriend && !isFunctionTemplateSpecialization &&
9852                !isMemberSpecialization) {
9853       // An out-of-line member function declaration must also be a
9854       // definition (C++ [class.mfct]p2).
9855       // Note that this is not the case for explicit specializations of
9856       // function templates or member functions of class templates, per
9857       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9858       // extension for compatibility with old SWIG code which likes to
9859       // generate them.
9860       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9861         << D.getCXXScopeSpec().getRange();
9862     }
9863   }
9864 
9865   // If this is the first declaration of a library builtin function, add
9866   // attributes as appropriate.
9867   if (!D.isRedeclaration() &&
9868       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9869     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9870       if (unsigned BuiltinID = II->getBuiltinID()) {
9871         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9872           // Validate the type matches unless this builtin is specified as
9873           // matching regardless of its declared type.
9874           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9875             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9876           } else {
9877             ASTContext::GetBuiltinTypeError Error;
9878             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9879             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9880 
9881             if (!Error && !BuiltinType.isNull() &&
9882                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9883                     NewFD->getType(), BuiltinType))
9884               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9885           }
9886         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9887                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9888           // FIXME: We should consider this a builtin only in the std namespace.
9889           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9890         }
9891       }
9892     }
9893   }
9894 
9895   ProcessPragmaWeak(S, NewFD);
9896   checkAttributesAfterMerging(*this, *NewFD);
9897 
9898   AddKnownFunctionAttributes(NewFD);
9899 
9900   if (NewFD->hasAttr<OverloadableAttr>() &&
9901       !NewFD->getType()->getAs<FunctionProtoType>()) {
9902     Diag(NewFD->getLocation(),
9903          diag::err_attribute_overloadable_no_prototype)
9904       << NewFD;
9905 
9906     // Turn this into a variadic function with no parameters.
9907     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9908     FunctionProtoType::ExtProtoInfo EPI(
9909         Context.getDefaultCallingConvention(true, false));
9910     EPI.Variadic = true;
9911     EPI.ExtInfo = FT->getExtInfo();
9912 
9913     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9914     NewFD->setType(R);
9915   }
9916 
9917   // If there's a #pragma GCC visibility in scope, and this isn't a class
9918   // member, set the visibility of this function.
9919   if (!DC->isRecord() && NewFD->isExternallyVisible())
9920     AddPushedVisibilityAttribute(NewFD);
9921 
9922   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9923   // marking the function.
9924   AddCFAuditedAttribute(NewFD);
9925 
9926   // If this is a function definition, check if we have to apply optnone due to
9927   // a pragma.
9928   if(D.isFunctionDefinition())
9929     AddRangeBasedOptnone(NewFD);
9930 
9931   // If this is the first declaration of an extern C variable, update
9932   // the map of such variables.
9933   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9934       isIncompleteDeclExternC(*this, NewFD))
9935     RegisterLocallyScopedExternCDecl(NewFD, S);
9936 
9937   // Set this FunctionDecl's range up to the right paren.
9938   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9939 
9940   if (D.isRedeclaration() && !Previous.empty()) {
9941     NamedDecl *Prev = Previous.getRepresentativeDecl();
9942     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9943                                    isMemberSpecialization ||
9944                                        isFunctionTemplateSpecialization,
9945                                    D.isFunctionDefinition());
9946   }
9947 
9948   if (getLangOpts().CUDA) {
9949     IdentifierInfo *II = NewFD->getIdentifier();
9950     if (II && II->isStr(getCudaConfigureFuncName()) &&
9951         !NewFD->isInvalidDecl() &&
9952         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9953       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9954         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9955             << getCudaConfigureFuncName();
9956       Context.setcudaConfigureCallDecl(NewFD);
9957     }
9958 
9959     // Variadic functions, other than a *declaration* of printf, are not allowed
9960     // in device-side CUDA code, unless someone passed
9961     // -fcuda-allow-variadic-functions.
9962     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9963         (NewFD->hasAttr<CUDADeviceAttr>() ||
9964          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9965         !(II && II->isStr("printf") && NewFD->isExternC() &&
9966           !D.isFunctionDefinition())) {
9967       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9968     }
9969   }
9970 
9971   MarkUnusedFileScopedDecl(NewFD);
9972 
9973 
9974 
9975   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9976     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9977     if (SC == SC_Static) {
9978       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9979       D.setInvalidType();
9980     }
9981 
9982     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9983     if (!NewFD->getReturnType()->isVoidType()) {
9984       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9985       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9986           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9987                                 : FixItHint());
9988       D.setInvalidType();
9989     }
9990 
9991     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9992     for (auto Param : NewFD->parameters())
9993       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9994 
9995     if (getLangOpts().OpenCLCPlusPlus) {
9996       if (DC->isRecord()) {
9997         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9998         D.setInvalidType();
9999       }
10000       if (FunctionTemplate) {
10001         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10002         D.setInvalidType();
10003       }
10004     }
10005   }
10006 
10007   if (getLangOpts().CPlusPlus) {
10008     if (FunctionTemplate) {
10009       if (NewFD->isInvalidDecl())
10010         FunctionTemplate->setInvalidDecl();
10011       return FunctionTemplate;
10012     }
10013 
10014     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10015       CompleteMemberSpecialization(NewFD, Previous);
10016   }
10017 
10018   for (const ParmVarDecl *Param : NewFD->parameters()) {
10019     QualType PT = Param->getType();
10020 
10021     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10022     // types.
10023     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10024       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10025         QualType ElemTy = PipeTy->getElementType();
10026           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10027             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10028             D.setInvalidType();
10029           }
10030       }
10031     }
10032   }
10033 
10034   // Here we have an function template explicit specialization at class scope.
10035   // The actual specialization will be postponed to template instatiation
10036   // time via the ClassScopeFunctionSpecializationDecl node.
10037   if (isDependentClassScopeExplicitSpecialization) {
10038     ClassScopeFunctionSpecializationDecl *NewSpec =
10039                          ClassScopeFunctionSpecializationDecl::Create(
10040                                 Context, CurContext, NewFD->getLocation(),
10041                                 cast<CXXMethodDecl>(NewFD),
10042                                 HasExplicitTemplateArgs, TemplateArgs);
10043     CurContext->addDecl(NewSpec);
10044     AddToScope = false;
10045   }
10046 
10047   // Diagnose availability attributes. Availability cannot be used on functions
10048   // that are run during load/unload.
10049   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10050     if (NewFD->hasAttr<ConstructorAttr>()) {
10051       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10052           << 1;
10053       NewFD->dropAttr<AvailabilityAttr>();
10054     }
10055     if (NewFD->hasAttr<DestructorAttr>()) {
10056       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10057           << 2;
10058       NewFD->dropAttr<AvailabilityAttr>();
10059     }
10060   }
10061 
10062   // Diagnose no_builtin attribute on function declaration that are not a
10063   // definition.
10064   // FIXME: We should really be doing this in
10065   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10066   // the FunctionDecl and at this point of the code
10067   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10068   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10069   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10070     switch (D.getFunctionDefinitionKind()) {
10071     case FunctionDefinitionKind::Defaulted:
10072     case FunctionDefinitionKind::Deleted:
10073       Diag(NBA->getLocation(),
10074            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10075           << NBA->getSpelling();
10076       break;
10077     case FunctionDefinitionKind::Declaration:
10078       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10079           << NBA->getSpelling();
10080       break;
10081     case FunctionDefinitionKind::Definition:
10082       break;
10083     }
10084 
10085   return NewFD;
10086 }
10087 
10088 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10089 /// when __declspec(code_seg) "is applied to a class, all member functions of
10090 /// the class and nested classes -- this includes compiler-generated special
10091 /// member functions -- are put in the specified segment."
10092 /// The actual behavior is a little more complicated. The Microsoft compiler
10093 /// won't check outer classes if there is an active value from #pragma code_seg.
10094 /// The CodeSeg is always applied from the direct parent but only from outer
10095 /// classes when the #pragma code_seg stack is empty. See:
10096 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10097 /// available since MS has removed the page.
10098 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10099   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10100   if (!Method)
10101     return nullptr;
10102   const CXXRecordDecl *Parent = Method->getParent();
10103   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10104     Attr *NewAttr = SAttr->clone(S.getASTContext());
10105     NewAttr->setImplicit(true);
10106     return NewAttr;
10107   }
10108 
10109   // The Microsoft compiler won't check outer classes for the CodeSeg
10110   // when the #pragma code_seg stack is active.
10111   if (S.CodeSegStack.CurrentValue)
10112    return nullptr;
10113 
10114   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10115     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10116       Attr *NewAttr = SAttr->clone(S.getASTContext());
10117       NewAttr->setImplicit(true);
10118       return NewAttr;
10119     }
10120   }
10121   return nullptr;
10122 }
10123 
10124 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10125 /// containing class. Otherwise it will return implicit SectionAttr if the
10126 /// function is a definition and there is an active value on CodeSegStack
10127 /// (from the current #pragma code-seg value).
10128 ///
10129 /// \param FD Function being declared.
10130 /// \param IsDefinition Whether it is a definition or just a declarartion.
10131 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10132 ///          nullptr if no attribute should be added.
10133 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10134                                                        bool IsDefinition) {
10135   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10136     return A;
10137   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10138       CodeSegStack.CurrentValue)
10139     return SectionAttr::CreateImplicit(
10140         getASTContext(), CodeSegStack.CurrentValue->getString(),
10141         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10142         SectionAttr::Declspec_allocate);
10143   return nullptr;
10144 }
10145 
10146 /// Determines if we can perform a correct type check for \p D as a
10147 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10148 /// best-effort check.
10149 ///
10150 /// \param NewD The new declaration.
10151 /// \param OldD The old declaration.
10152 /// \param NewT The portion of the type of the new declaration to check.
10153 /// \param OldT The portion of the type of the old declaration to check.
10154 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10155                                           QualType NewT, QualType OldT) {
10156   if (!NewD->getLexicalDeclContext()->isDependentContext())
10157     return true;
10158 
10159   // For dependently-typed local extern declarations and friends, we can't
10160   // perform a correct type check in general until instantiation:
10161   //
10162   //   int f();
10163   //   template<typename T> void g() { T f(); }
10164   //
10165   // (valid if g() is only instantiated with T = int).
10166   if (NewT->isDependentType() &&
10167       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10168     return false;
10169 
10170   // Similarly, if the previous declaration was a dependent local extern
10171   // declaration, we don't really know its type yet.
10172   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10173     return false;
10174 
10175   return true;
10176 }
10177 
10178 /// Checks if the new declaration declared in dependent context must be
10179 /// put in the same redeclaration chain as the specified declaration.
10180 ///
10181 /// \param D Declaration that is checked.
10182 /// \param PrevDecl Previous declaration found with proper lookup method for the
10183 ///                 same declaration name.
10184 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10185 ///          belongs to.
10186 ///
10187 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10188   if (!D->getLexicalDeclContext()->isDependentContext())
10189     return true;
10190 
10191   // Don't chain dependent friend function definitions until instantiation, to
10192   // permit cases like
10193   //
10194   //   void func();
10195   //   template<typename T> class C1 { friend void func() {} };
10196   //   template<typename T> class C2 { friend void func() {} };
10197   //
10198   // ... which is valid if only one of C1 and C2 is ever instantiated.
10199   //
10200   // FIXME: This need only apply to function definitions. For now, we proxy
10201   // this by checking for a file-scope function. We do not want this to apply
10202   // to friend declarations nominating member functions, because that gets in
10203   // the way of access checks.
10204   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10205     return false;
10206 
10207   auto *VD = dyn_cast<ValueDecl>(D);
10208   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10209   return !VD || !PrevVD ||
10210          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10211                                         PrevVD->getType());
10212 }
10213 
10214 /// Check the target attribute of the function for MultiVersion
10215 /// validity.
10216 ///
10217 /// Returns true if there was an error, false otherwise.
10218 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10219   const auto *TA = FD->getAttr<TargetAttr>();
10220   assert(TA && "MultiVersion Candidate requires a target attribute");
10221   ParsedTargetAttr ParseInfo = TA->parse();
10222   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10223   enum ErrType { Feature = 0, Architecture = 1 };
10224 
10225   if (!ParseInfo.Architecture.empty() &&
10226       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10227     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10228         << Architecture << ParseInfo.Architecture;
10229     return true;
10230   }
10231 
10232   for (const auto &Feat : ParseInfo.Features) {
10233     auto BareFeat = StringRef{Feat}.substr(1);
10234     if (Feat[0] == '-') {
10235       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10236           << Feature << ("no-" + BareFeat).str();
10237       return true;
10238     }
10239 
10240     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10241         !TargetInfo.isValidFeatureName(BareFeat)) {
10242       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10243           << Feature << BareFeat;
10244       return true;
10245     }
10246   }
10247   return false;
10248 }
10249 
10250 // Provide a white-list of attributes that are allowed to be combined with
10251 // multiversion functions.
10252 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10253                                            MultiVersionKind MVType) {
10254   // Note: this list/diagnosis must match the list in
10255   // checkMultiversionAttributesAllSame.
10256   switch (Kind) {
10257   default:
10258     return false;
10259   case attr::Used:
10260     return MVType == MultiVersionKind::Target;
10261   case attr::NonNull:
10262   case attr::NoThrow:
10263     return true;
10264   }
10265 }
10266 
10267 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10268                                                  const FunctionDecl *FD,
10269                                                  const FunctionDecl *CausedFD,
10270                                                  MultiVersionKind MVType) {
10271   const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) {
10272     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10273         << static_cast<unsigned>(MVType) << A;
10274     if (CausedFD)
10275       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10276     return true;
10277   };
10278 
10279   for (const Attr *A : FD->attrs()) {
10280     switch (A->getKind()) {
10281     case attr::CPUDispatch:
10282     case attr::CPUSpecific:
10283       if (MVType != MultiVersionKind::CPUDispatch &&
10284           MVType != MultiVersionKind::CPUSpecific)
10285         return Diagnose(S, A);
10286       break;
10287     case attr::Target:
10288       if (MVType != MultiVersionKind::Target)
10289         return Diagnose(S, A);
10290       break;
10291     case attr::TargetClones:
10292       if (MVType != MultiVersionKind::TargetClones)
10293         return Diagnose(S, A);
10294       break;
10295     default:
10296       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10297         return Diagnose(S, A);
10298       break;
10299     }
10300   }
10301   return false;
10302 }
10303 
10304 bool Sema::areMultiversionVariantFunctionsCompatible(
10305     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10306     const PartialDiagnostic &NoProtoDiagID,
10307     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10308     const PartialDiagnosticAt &NoSupportDiagIDAt,
10309     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10310     bool ConstexprSupported, bool CLinkageMayDiffer) {
10311   enum DoesntSupport {
10312     FuncTemplates = 0,
10313     VirtFuncs = 1,
10314     DeducedReturn = 2,
10315     Constructors = 3,
10316     Destructors = 4,
10317     DeletedFuncs = 5,
10318     DefaultedFuncs = 6,
10319     ConstexprFuncs = 7,
10320     ConstevalFuncs = 8,
10321     Lambda = 9,
10322   };
10323   enum Different {
10324     CallingConv = 0,
10325     ReturnType = 1,
10326     ConstexprSpec = 2,
10327     InlineSpec = 3,
10328     Linkage = 4,
10329     LanguageLinkage = 5,
10330   };
10331 
10332   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10333       !OldFD->getType()->getAs<FunctionProtoType>()) {
10334     Diag(OldFD->getLocation(), NoProtoDiagID);
10335     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10336     return true;
10337   }
10338 
10339   if (NoProtoDiagID.getDiagID() != 0 &&
10340       !NewFD->getType()->getAs<FunctionProtoType>())
10341     return Diag(NewFD->getLocation(), NoProtoDiagID);
10342 
10343   if (!TemplatesSupported &&
10344       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10345     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10346            << FuncTemplates;
10347 
10348   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10349     if (NewCXXFD->isVirtual())
10350       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10351              << VirtFuncs;
10352 
10353     if (isa<CXXConstructorDecl>(NewCXXFD))
10354       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10355              << Constructors;
10356 
10357     if (isa<CXXDestructorDecl>(NewCXXFD))
10358       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10359              << Destructors;
10360   }
10361 
10362   if (NewFD->isDeleted())
10363     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10364            << DeletedFuncs;
10365 
10366   if (NewFD->isDefaulted())
10367     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10368            << DefaultedFuncs;
10369 
10370   if (!ConstexprSupported && NewFD->isConstexpr())
10371     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10372            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10373 
10374   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10375   const auto *NewType = cast<FunctionType>(NewQType);
10376   QualType NewReturnType = NewType->getReturnType();
10377 
10378   if (NewReturnType->isUndeducedType())
10379     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10380            << DeducedReturn;
10381 
10382   // Ensure the return type is identical.
10383   if (OldFD) {
10384     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10385     const auto *OldType = cast<FunctionType>(OldQType);
10386     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10387     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10388 
10389     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10390       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10391 
10392     QualType OldReturnType = OldType->getReturnType();
10393 
10394     if (OldReturnType != NewReturnType)
10395       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10396 
10397     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10398       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10399 
10400     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10401       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10402 
10403     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10404       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10405 
10406     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10407       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10408 
10409     if (CheckEquivalentExceptionSpec(
10410             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10411             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10412       return true;
10413   }
10414   return false;
10415 }
10416 
10417 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10418                                              const FunctionDecl *NewFD,
10419                                              bool CausesMV,
10420                                              MultiVersionKind MVType) {
10421   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10422     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10423     if (OldFD)
10424       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10425     return true;
10426   }
10427 
10428   bool IsCPUSpecificCPUDispatchMVType =
10429       MVType == MultiVersionKind::CPUDispatch ||
10430       MVType == MultiVersionKind::CPUSpecific;
10431 
10432   if (CausesMV && OldFD &&
10433       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10434     return true;
10435 
10436   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10437     return true;
10438 
10439   // Only allow transition to MultiVersion if it hasn't been used.
10440   if (OldFD && CausesMV && OldFD->isUsed(false))
10441     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10442 
10443   return S.areMultiversionVariantFunctionsCompatible(
10444       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10445       PartialDiagnosticAt(NewFD->getLocation(),
10446                           S.PDiag(diag::note_multiversioning_caused_here)),
10447       PartialDiagnosticAt(NewFD->getLocation(),
10448                           S.PDiag(diag::err_multiversion_doesnt_support)
10449                               << static_cast<unsigned>(MVType)),
10450       PartialDiagnosticAt(NewFD->getLocation(),
10451                           S.PDiag(diag::err_multiversion_diff)),
10452       /*TemplatesSupported=*/false,
10453       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10454       /*CLinkageMayDiffer=*/false);
10455 }
10456 
10457 /// Check the validity of a multiversion function declaration that is the
10458 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10459 ///
10460 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10461 ///
10462 /// Returns true if there was an error, false otherwise.
10463 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10464                                            MultiVersionKind MVType,
10465                                            const TargetAttr *TA) {
10466   assert(MVType != MultiVersionKind::None &&
10467          "Function lacks multiversion attribute");
10468 
10469   // Target only causes MV if it is default, otherwise this is a normal
10470   // function.
10471   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10472     return false;
10473 
10474   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10475     FD->setInvalidDecl();
10476     return true;
10477   }
10478 
10479   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10480     FD->setInvalidDecl();
10481     return true;
10482   }
10483 
10484   FD->setIsMultiVersion();
10485   return false;
10486 }
10487 
10488 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10489   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10490     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10491       return true;
10492   }
10493 
10494   return false;
10495 }
10496 
10497 static bool CheckTargetCausesMultiVersioning(
10498     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10499     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10500     LookupResult &Previous) {
10501   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10502   ParsedTargetAttr NewParsed = NewTA->parse();
10503   // Sort order doesn't matter, it just needs to be consistent.
10504   llvm::sort(NewParsed.Features);
10505 
10506   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10507   // to change, this is a simple redeclaration.
10508   if (!NewTA->isDefaultVersion() &&
10509       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10510     return false;
10511 
10512   // Otherwise, this decl causes MultiVersioning.
10513   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10514     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10515     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10516     NewFD->setInvalidDecl();
10517     return true;
10518   }
10519 
10520   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10521                                        MultiVersionKind::Target)) {
10522     NewFD->setInvalidDecl();
10523     return true;
10524   }
10525 
10526   if (CheckMultiVersionValue(S, NewFD)) {
10527     NewFD->setInvalidDecl();
10528     return true;
10529   }
10530 
10531   // If this is 'default', permit the forward declaration.
10532   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10533     Redeclaration = true;
10534     OldDecl = OldFD;
10535     OldFD->setIsMultiVersion();
10536     NewFD->setIsMultiVersion();
10537     return false;
10538   }
10539 
10540   if (CheckMultiVersionValue(S, OldFD)) {
10541     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10542     NewFD->setInvalidDecl();
10543     return true;
10544   }
10545 
10546   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10547 
10548   if (OldParsed == NewParsed) {
10549     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10550     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10551     NewFD->setInvalidDecl();
10552     return true;
10553   }
10554 
10555   for (const auto *FD : OldFD->redecls()) {
10556     const auto *CurTA = FD->getAttr<TargetAttr>();
10557     // We allow forward declarations before ANY multiversioning attributes, but
10558     // nothing after the fact.
10559     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10560         (!CurTA || CurTA->isInherited())) {
10561       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10562           << 0;
10563       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10564       NewFD->setInvalidDecl();
10565       return true;
10566     }
10567   }
10568 
10569   OldFD->setIsMultiVersion();
10570   NewFD->setIsMultiVersion();
10571   Redeclaration = false;
10572   MergeTypeWithPrevious = false;
10573   OldDecl = nullptr;
10574   Previous.clear();
10575   return false;
10576 }
10577 
10578 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10579                                         MultiVersionKind New) {
10580   if (Old == New || Old == MultiVersionKind::None ||
10581       New == MultiVersionKind::None)
10582     return true;
10583 
10584   return (Old == MultiVersionKind::CPUDispatch &&
10585           New == MultiVersionKind::CPUSpecific) ||
10586          (Old == MultiVersionKind::CPUSpecific &&
10587           New == MultiVersionKind::CPUDispatch);
10588 }
10589 
10590 /// Check the validity of a new function declaration being added to an existing
10591 /// multiversioned declaration collection.
10592 static bool CheckMultiVersionAdditionalDecl(
10593     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10594     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10595     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10596     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10597     bool &MergeTypeWithPrevious, LookupResult &Previous) {
10598 
10599   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10600   // Disallow mixing of multiversioning types.
10601   if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) {
10602     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10603     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10604     NewFD->setInvalidDecl();
10605     return true;
10606   }
10607 
10608   ParsedTargetAttr NewParsed;
10609   if (NewTA) {
10610     NewParsed = NewTA->parse();
10611     llvm::sort(NewParsed.Features);
10612   }
10613 
10614   bool UseMemberUsingDeclRules =
10615       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10616 
10617   // Next, check ALL non-overloads to see if this is a redeclaration of a
10618   // previous member of the MultiVersion set.
10619   for (NamedDecl *ND : Previous) {
10620     FunctionDecl *CurFD = ND->getAsFunction();
10621     if (!CurFD)
10622       continue;
10623     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10624       continue;
10625 
10626     switch (NewMVType) {
10627     case MultiVersionKind::None:
10628       assert(OldMVType == MultiVersionKind::TargetClones &&
10629              "Only target_clones can be omitted in subsequent declarations");
10630       break;
10631     case MultiVersionKind::Target: {
10632       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10633       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10634         NewFD->setIsMultiVersion();
10635         Redeclaration = true;
10636         OldDecl = ND;
10637         return false;
10638       }
10639 
10640       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10641       if (CurParsed == NewParsed) {
10642         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10643         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10644         NewFD->setInvalidDecl();
10645         return true;
10646       }
10647       break;
10648     }
10649     case MultiVersionKind::TargetClones: {
10650       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10651       Redeclaration = true;
10652       OldDecl = CurFD;
10653       MergeTypeWithPrevious = true;
10654       NewFD->setIsMultiVersion();
10655 
10656       if (CurClones && NewClones &&
10657           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10658            !std::equal(CurClones->featuresStrs_begin(),
10659                        CurClones->featuresStrs_end(),
10660                        NewClones->featuresStrs_begin()))) {
10661         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10662         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10663         NewFD->setInvalidDecl();
10664         return true;
10665       }
10666 
10667       return false;
10668     }
10669     case MultiVersionKind::CPUSpecific:
10670     case MultiVersionKind::CPUDispatch: {
10671       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10672       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10673       // Handle CPUDispatch/CPUSpecific versions.
10674       // Only 1 CPUDispatch function is allowed, this will make it go through
10675       // the redeclaration errors.
10676       if (NewMVType == MultiVersionKind::CPUDispatch &&
10677           CurFD->hasAttr<CPUDispatchAttr>()) {
10678         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10679             std::equal(
10680                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10681                 NewCPUDisp->cpus_begin(),
10682                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10683                   return Cur->getName() == New->getName();
10684                 })) {
10685           NewFD->setIsMultiVersion();
10686           Redeclaration = true;
10687           OldDecl = ND;
10688           return false;
10689         }
10690 
10691         // If the declarations don't match, this is an error condition.
10692         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10693         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10694         NewFD->setInvalidDecl();
10695         return true;
10696       }
10697       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10698 
10699         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10700             std::equal(
10701                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10702                 NewCPUSpec->cpus_begin(),
10703                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10704                   return Cur->getName() == New->getName();
10705                 })) {
10706           NewFD->setIsMultiVersion();
10707           Redeclaration = true;
10708           OldDecl = ND;
10709           return false;
10710         }
10711 
10712         // Only 1 version of CPUSpecific is allowed for each CPU.
10713         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10714           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10715             if (CurII == NewII) {
10716               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10717                   << NewII;
10718               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10719               NewFD->setInvalidDecl();
10720               return true;
10721             }
10722           }
10723         }
10724       }
10725       break;
10726     }
10727     }
10728   }
10729 
10730   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10731   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10732   // handled in the attribute adding step.
10733   if (NewMVType == MultiVersionKind::Target &&
10734       CheckMultiVersionValue(S, NewFD)) {
10735     NewFD->setInvalidDecl();
10736     return true;
10737   }
10738 
10739   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10740                                        !OldFD->isMultiVersion(), NewMVType)) {
10741     NewFD->setInvalidDecl();
10742     return true;
10743   }
10744 
10745   // Permit forward declarations in the case where these two are compatible.
10746   if (!OldFD->isMultiVersion()) {
10747     OldFD->setIsMultiVersion();
10748     NewFD->setIsMultiVersion();
10749     Redeclaration = true;
10750     OldDecl = OldFD;
10751     return false;
10752   }
10753 
10754   NewFD->setIsMultiVersion();
10755   Redeclaration = false;
10756   MergeTypeWithPrevious = false;
10757   OldDecl = nullptr;
10758   Previous.clear();
10759   return false;
10760 }
10761 
10762 /// Check the validity of a mulitversion function declaration.
10763 /// Also sets the multiversion'ness' of the function itself.
10764 ///
10765 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10766 ///
10767 /// Returns true if there was an error, false otherwise.
10768 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10769                                       bool &Redeclaration, NamedDecl *&OldDecl,
10770                                       bool &MergeTypeWithPrevious,
10771                                       LookupResult &Previous) {
10772   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10773   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10774   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10775   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10776   MultiVersionKind MVType = NewFD->getMultiVersionKind();
10777 
10778   // Main isn't allowed to become a multiversion function, however it IS
10779   // permitted to have 'main' be marked with the 'target' optimization hint.
10780   if (NewFD->isMain()) {
10781     if (MVType != MultiVersionKind::None &&
10782         !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10783       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10784       NewFD->setInvalidDecl();
10785       return true;
10786     }
10787     return false;
10788   }
10789 
10790   if (!OldDecl || !OldDecl->getAsFunction() ||
10791       OldDecl->getDeclContext()->getRedeclContext() !=
10792           NewFD->getDeclContext()->getRedeclContext()) {
10793     // If there's no previous declaration, AND this isn't attempting to cause
10794     // multiversioning, this isn't an error condition.
10795     if (MVType == MultiVersionKind::None)
10796       return false;
10797     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10798   }
10799 
10800   FunctionDecl *OldFD = OldDecl->getAsFunction();
10801 
10802   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10803     return false;
10804 
10805   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10806   // for target_clones.
10807   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None &&
10808       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10809     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10810         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10811     NewFD->setInvalidDecl();
10812     return true;
10813   }
10814 
10815   if (!OldFD->isMultiVersion()) {
10816     switch (MVType) {
10817     case MultiVersionKind::Target:
10818       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10819                                               Redeclaration, OldDecl,
10820                                               MergeTypeWithPrevious, Previous);
10821     case MultiVersionKind::TargetClones:
10822       if (OldFD->isUsed(false)) {
10823         NewFD->setInvalidDecl();
10824         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10825       }
10826       OldFD->setIsMultiVersion();
10827       break;
10828     case MultiVersionKind::CPUDispatch:
10829     case MultiVersionKind::CPUSpecific:
10830     case MultiVersionKind::None:
10831       break;
10832     }
10833   }
10834   // Handle the target potentially causes multiversioning case.
10835   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10836     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10837                                             Redeclaration, OldDecl,
10838                                             MergeTypeWithPrevious, Previous);
10839 
10840   // At this point, we have a multiversion function decl (in OldFD) AND an
10841   // appropriate attribute in the current function decl.  Resolve that these are
10842   // still compatible with previous declarations.
10843   return CheckMultiVersionAdditionalDecl(
10844       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones,
10845       Redeclaration, OldDecl, MergeTypeWithPrevious, Previous);
10846 }
10847 
10848 /// Perform semantic checking of a new function declaration.
10849 ///
10850 /// Performs semantic analysis of the new function declaration
10851 /// NewFD. This routine performs all semantic checking that does not
10852 /// require the actual declarator involved in the declaration, and is
10853 /// used both for the declaration of functions as they are parsed
10854 /// (called via ActOnDeclarator) and for the declaration of functions
10855 /// that have been instantiated via C++ template instantiation (called
10856 /// via InstantiateDecl).
10857 ///
10858 /// \param IsMemberSpecialization whether this new function declaration is
10859 /// a member specialization (that replaces any definition provided by the
10860 /// previous declaration).
10861 ///
10862 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10863 ///
10864 /// \returns true if the function declaration is a redeclaration.
10865 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10866                                     LookupResult &Previous,
10867                                     bool IsMemberSpecialization) {
10868   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10869          "Variably modified return types are not handled here");
10870 
10871   // Determine whether the type of this function should be merged with
10872   // a previous visible declaration. This never happens for functions in C++,
10873   // and always happens in C if the previous declaration was visible.
10874   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10875                                !Previous.isShadowed();
10876 
10877   bool Redeclaration = false;
10878   NamedDecl *OldDecl = nullptr;
10879   bool MayNeedOverloadableChecks = false;
10880 
10881   // Merge or overload the declaration with an existing declaration of
10882   // the same name, if appropriate.
10883   if (!Previous.empty()) {
10884     // Determine whether NewFD is an overload of PrevDecl or
10885     // a declaration that requires merging. If it's an overload,
10886     // there's no more work to do here; we'll just add the new
10887     // function to the scope.
10888     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10889       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10890       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10891         Redeclaration = true;
10892         OldDecl = Candidate;
10893       }
10894     } else {
10895       MayNeedOverloadableChecks = true;
10896       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10897                             /*NewIsUsingDecl*/ false)) {
10898       case Ovl_Match:
10899         Redeclaration = true;
10900         break;
10901 
10902       case Ovl_NonFunction:
10903         Redeclaration = true;
10904         break;
10905 
10906       case Ovl_Overload:
10907         Redeclaration = false;
10908         break;
10909       }
10910     }
10911   }
10912 
10913   // Check for a previous extern "C" declaration with this name.
10914   if (!Redeclaration &&
10915       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10916     if (!Previous.empty()) {
10917       // This is an extern "C" declaration with the same name as a previous
10918       // declaration, and thus redeclares that entity...
10919       Redeclaration = true;
10920       OldDecl = Previous.getFoundDecl();
10921       MergeTypeWithPrevious = false;
10922 
10923       // ... except in the presence of __attribute__((overloadable)).
10924       if (OldDecl->hasAttr<OverloadableAttr>() ||
10925           NewFD->hasAttr<OverloadableAttr>()) {
10926         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10927           MayNeedOverloadableChecks = true;
10928           Redeclaration = false;
10929           OldDecl = nullptr;
10930         }
10931       }
10932     }
10933   }
10934 
10935   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10936                                 MergeTypeWithPrevious, Previous))
10937     return Redeclaration;
10938 
10939   // PPC MMA non-pointer types are not allowed as function return types.
10940   if (Context.getTargetInfo().getTriple().isPPC64() &&
10941       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10942     NewFD->setInvalidDecl();
10943   }
10944 
10945   // C++11 [dcl.constexpr]p8:
10946   //   A constexpr specifier for a non-static member function that is not
10947   //   a constructor declares that member function to be const.
10948   //
10949   // This needs to be delayed until we know whether this is an out-of-line
10950   // definition of a static member function.
10951   //
10952   // This rule is not present in C++1y, so we produce a backwards
10953   // compatibility warning whenever it happens in C++11.
10954   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10955   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10956       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10957       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10958     CXXMethodDecl *OldMD = nullptr;
10959     if (OldDecl)
10960       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10961     if (!OldMD || !OldMD->isStatic()) {
10962       const FunctionProtoType *FPT =
10963         MD->getType()->castAs<FunctionProtoType>();
10964       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10965       EPI.TypeQuals.addConst();
10966       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10967                                           FPT->getParamTypes(), EPI));
10968 
10969       // Warn that we did this, if we're not performing template instantiation.
10970       // In that case, we'll have warned already when the template was defined.
10971       if (!inTemplateInstantiation()) {
10972         SourceLocation AddConstLoc;
10973         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10974                 .IgnoreParens().getAs<FunctionTypeLoc>())
10975           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10976 
10977         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10978           << FixItHint::CreateInsertion(AddConstLoc, " const");
10979       }
10980     }
10981   }
10982 
10983   if (Redeclaration) {
10984     // NewFD and OldDecl represent declarations that need to be
10985     // merged.
10986     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10987       NewFD->setInvalidDecl();
10988       return Redeclaration;
10989     }
10990 
10991     Previous.clear();
10992     Previous.addDecl(OldDecl);
10993 
10994     if (FunctionTemplateDecl *OldTemplateDecl =
10995             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10996       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10997       FunctionTemplateDecl *NewTemplateDecl
10998         = NewFD->getDescribedFunctionTemplate();
10999       assert(NewTemplateDecl && "Template/non-template mismatch");
11000 
11001       // The call to MergeFunctionDecl above may have created some state in
11002       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11003       // can add it as a redeclaration.
11004       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11005 
11006       NewFD->setPreviousDeclaration(OldFD);
11007       if (NewFD->isCXXClassMember()) {
11008         NewFD->setAccess(OldTemplateDecl->getAccess());
11009         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11010       }
11011 
11012       // If this is an explicit specialization of a member that is a function
11013       // template, mark it as a member specialization.
11014       if (IsMemberSpecialization &&
11015           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11016         NewTemplateDecl->setMemberSpecialization();
11017         assert(OldTemplateDecl->isMemberSpecialization());
11018         // Explicit specializations of a member template do not inherit deleted
11019         // status from the parent member template that they are specializing.
11020         if (OldFD->isDeleted()) {
11021           // FIXME: This assert will not hold in the presence of modules.
11022           assert(OldFD->getCanonicalDecl() == OldFD);
11023           // FIXME: We need an update record for this AST mutation.
11024           OldFD->setDeletedAsWritten(false);
11025         }
11026       }
11027 
11028     } else {
11029       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11030         auto *OldFD = cast<FunctionDecl>(OldDecl);
11031         // This needs to happen first so that 'inline' propagates.
11032         NewFD->setPreviousDeclaration(OldFD);
11033         if (NewFD->isCXXClassMember())
11034           NewFD->setAccess(OldFD->getAccess());
11035       }
11036     }
11037   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11038              !NewFD->getAttr<OverloadableAttr>()) {
11039     assert((Previous.empty() ||
11040             llvm::any_of(Previous,
11041                          [](const NamedDecl *ND) {
11042                            return ND->hasAttr<OverloadableAttr>();
11043                          })) &&
11044            "Non-redecls shouldn't happen without overloadable present");
11045 
11046     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11047       const auto *FD = dyn_cast<FunctionDecl>(ND);
11048       return FD && !FD->hasAttr<OverloadableAttr>();
11049     });
11050 
11051     if (OtherUnmarkedIter != Previous.end()) {
11052       Diag(NewFD->getLocation(),
11053            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11054       Diag((*OtherUnmarkedIter)->getLocation(),
11055            diag::note_attribute_overloadable_prev_overload)
11056           << false;
11057 
11058       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11059     }
11060   }
11061 
11062   if (LangOpts.OpenMP)
11063     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11064 
11065   // Semantic checking for this function declaration (in isolation).
11066 
11067   if (getLangOpts().CPlusPlus) {
11068     // C++-specific checks.
11069     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11070       CheckConstructor(Constructor);
11071     } else if (CXXDestructorDecl *Destructor =
11072                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11073       CXXRecordDecl *Record = Destructor->getParent();
11074       QualType ClassType = Context.getTypeDeclType(Record);
11075 
11076       // FIXME: Shouldn't we be able to perform this check even when the class
11077       // type is dependent? Both gcc and edg can handle that.
11078       if (!ClassType->isDependentType()) {
11079         DeclarationName Name
11080           = Context.DeclarationNames.getCXXDestructorName(
11081                                         Context.getCanonicalType(ClassType));
11082         if (NewFD->getDeclName() != Name) {
11083           Diag(NewFD->getLocation(), diag::err_destructor_name);
11084           NewFD->setInvalidDecl();
11085           return Redeclaration;
11086         }
11087       }
11088     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11089       if (auto *TD = Guide->getDescribedFunctionTemplate())
11090         CheckDeductionGuideTemplate(TD);
11091 
11092       // A deduction guide is not on the list of entities that can be
11093       // explicitly specialized.
11094       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11095         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11096             << /*explicit specialization*/ 1;
11097     }
11098 
11099     // Find any virtual functions that this function overrides.
11100     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11101       if (!Method->isFunctionTemplateSpecialization() &&
11102           !Method->getDescribedFunctionTemplate() &&
11103           Method->isCanonicalDecl()) {
11104         AddOverriddenMethods(Method->getParent(), Method);
11105       }
11106       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11107         // C++2a [class.virtual]p6
11108         // A virtual method shall not have a requires-clause.
11109         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11110              diag::err_constrained_virtual_method);
11111 
11112       if (Method->isStatic())
11113         checkThisInStaticMemberFunctionType(Method);
11114     }
11115 
11116     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11117       ActOnConversionDeclarator(Conversion);
11118 
11119     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11120     if (NewFD->isOverloadedOperator() &&
11121         CheckOverloadedOperatorDeclaration(NewFD)) {
11122       NewFD->setInvalidDecl();
11123       return Redeclaration;
11124     }
11125 
11126     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11127     if (NewFD->getLiteralIdentifier() &&
11128         CheckLiteralOperatorDeclaration(NewFD)) {
11129       NewFD->setInvalidDecl();
11130       return Redeclaration;
11131     }
11132 
11133     // In C++, check default arguments now that we have merged decls. Unless
11134     // the lexical context is the class, because in this case this is done
11135     // during delayed parsing anyway.
11136     if (!CurContext->isRecord())
11137       CheckCXXDefaultArguments(NewFD);
11138 
11139     // If this function is declared as being extern "C", then check to see if
11140     // the function returns a UDT (class, struct, or union type) that is not C
11141     // compatible, and if it does, warn the user.
11142     // But, issue any diagnostic on the first declaration only.
11143     if (Previous.empty() && NewFD->isExternC()) {
11144       QualType R = NewFD->getReturnType();
11145       if (R->isIncompleteType() && !R->isVoidType())
11146         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11147             << NewFD << R;
11148       else if (!R.isPODType(Context) && !R->isVoidType() &&
11149                !R->isObjCObjectPointerType())
11150         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11151     }
11152 
11153     // C++1z [dcl.fct]p6:
11154     //   [...] whether the function has a non-throwing exception-specification
11155     //   [is] part of the function type
11156     //
11157     // This results in an ABI break between C++14 and C++17 for functions whose
11158     // declared type includes an exception-specification in a parameter or
11159     // return type. (Exception specifications on the function itself are OK in
11160     // most cases, and exception specifications are not permitted in most other
11161     // contexts where they could make it into a mangling.)
11162     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11163       auto HasNoexcept = [&](QualType T) -> bool {
11164         // Strip off declarator chunks that could be between us and a function
11165         // type. We don't need to look far, exception specifications are very
11166         // restricted prior to C++17.
11167         if (auto *RT = T->getAs<ReferenceType>())
11168           T = RT->getPointeeType();
11169         else if (T->isAnyPointerType())
11170           T = T->getPointeeType();
11171         else if (auto *MPT = T->getAs<MemberPointerType>())
11172           T = MPT->getPointeeType();
11173         if (auto *FPT = T->getAs<FunctionProtoType>())
11174           if (FPT->isNothrow())
11175             return true;
11176         return false;
11177       };
11178 
11179       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11180       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11181       for (QualType T : FPT->param_types())
11182         AnyNoexcept |= HasNoexcept(T);
11183       if (AnyNoexcept)
11184         Diag(NewFD->getLocation(),
11185              diag::warn_cxx17_compat_exception_spec_in_signature)
11186             << NewFD;
11187     }
11188 
11189     if (!Redeclaration && LangOpts.CUDA)
11190       checkCUDATargetOverload(NewFD, Previous);
11191   }
11192   return Redeclaration;
11193 }
11194 
11195 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11196   // C++11 [basic.start.main]p3:
11197   //   A program that [...] declares main to be inline, static or
11198   //   constexpr is ill-formed.
11199   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11200   //   appear in a declaration of main.
11201   // static main is not an error under C99, but we should warn about it.
11202   // We accept _Noreturn main as an extension.
11203   if (FD->getStorageClass() == SC_Static)
11204     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11205          ? diag::err_static_main : diag::warn_static_main)
11206       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11207   if (FD->isInlineSpecified())
11208     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11209       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11210   if (DS.isNoreturnSpecified()) {
11211     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11212     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11213     Diag(NoreturnLoc, diag::ext_noreturn_main);
11214     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11215       << FixItHint::CreateRemoval(NoreturnRange);
11216   }
11217   if (FD->isConstexpr()) {
11218     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11219         << FD->isConsteval()
11220         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11221     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11222   }
11223 
11224   if (getLangOpts().OpenCL) {
11225     Diag(FD->getLocation(), diag::err_opencl_no_main)
11226         << FD->hasAttr<OpenCLKernelAttr>();
11227     FD->setInvalidDecl();
11228     return;
11229   }
11230 
11231   QualType T = FD->getType();
11232   assert(T->isFunctionType() && "function decl is not of function type");
11233   const FunctionType* FT = T->castAs<FunctionType>();
11234 
11235   // Set default calling convention for main()
11236   if (FT->getCallConv() != CC_C) {
11237     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11238     FD->setType(QualType(FT, 0));
11239     T = Context.getCanonicalType(FD->getType());
11240   }
11241 
11242   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11243     // In C with GNU extensions we allow main() to have non-integer return
11244     // type, but we should warn about the extension, and we disable the
11245     // implicit-return-zero rule.
11246 
11247     // GCC in C mode accepts qualified 'int'.
11248     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11249       FD->setHasImplicitReturnZero(true);
11250     else {
11251       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11252       SourceRange RTRange = FD->getReturnTypeSourceRange();
11253       if (RTRange.isValid())
11254         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11255             << FixItHint::CreateReplacement(RTRange, "int");
11256     }
11257   } else {
11258     // In C and C++, main magically returns 0 if you fall off the end;
11259     // set the flag which tells us that.
11260     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11261 
11262     // All the standards say that main() should return 'int'.
11263     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11264       FD->setHasImplicitReturnZero(true);
11265     else {
11266       // Otherwise, this is just a flat-out error.
11267       SourceRange RTRange = FD->getReturnTypeSourceRange();
11268       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11269           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11270                                 : FixItHint());
11271       FD->setInvalidDecl(true);
11272     }
11273   }
11274 
11275   // Treat protoless main() as nullary.
11276   if (isa<FunctionNoProtoType>(FT)) return;
11277 
11278   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11279   unsigned nparams = FTP->getNumParams();
11280   assert(FD->getNumParams() == nparams);
11281 
11282   bool HasExtraParameters = (nparams > 3);
11283 
11284   if (FTP->isVariadic()) {
11285     Diag(FD->getLocation(), diag::ext_variadic_main);
11286     // FIXME: if we had information about the location of the ellipsis, we
11287     // could add a FixIt hint to remove it as a parameter.
11288   }
11289 
11290   // Darwin passes an undocumented fourth argument of type char**.  If
11291   // other platforms start sprouting these, the logic below will start
11292   // getting shifty.
11293   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11294     HasExtraParameters = false;
11295 
11296   if (HasExtraParameters) {
11297     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11298     FD->setInvalidDecl(true);
11299     nparams = 3;
11300   }
11301 
11302   // FIXME: a lot of the following diagnostics would be improved
11303   // if we had some location information about types.
11304 
11305   QualType CharPP =
11306     Context.getPointerType(Context.getPointerType(Context.CharTy));
11307   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11308 
11309   for (unsigned i = 0; i < nparams; ++i) {
11310     QualType AT = FTP->getParamType(i);
11311 
11312     bool mismatch = true;
11313 
11314     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11315       mismatch = false;
11316     else if (Expected[i] == CharPP) {
11317       // As an extension, the following forms are okay:
11318       //   char const **
11319       //   char const * const *
11320       //   char * const *
11321 
11322       QualifierCollector qs;
11323       const PointerType* PT;
11324       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11325           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11326           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11327                               Context.CharTy)) {
11328         qs.removeConst();
11329         mismatch = !qs.empty();
11330       }
11331     }
11332 
11333     if (mismatch) {
11334       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11335       // TODO: suggest replacing given type with expected type
11336       FD->setInvalidDecl(true);
11337     }
11338   }
11339 
11340   if (nparams == 1 && !FD->isInvalidDecl()) {
11341     Diag(FD->getLocation(), diag::warn_main_one_arg);
11342   }
11343 
11344   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11345     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11346     FD->setInvalidDecl();
11347   }
11348 }
11349 
11350 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11351 
11352   // Default calling convention for main and wmain is __cdecl
11353   if (FD->getName() == "main" || FD->getName() == "wmain")
11354     return false;
11355 
11356   // Default calling convention for MinGW is __cdecl
11357   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11358   if (T.isWindowsGNUEnvironment())
11359     return false;
11360 
11361   // Default calling convention for WinMain, wWinMain and DllMain
11362   // is __stdcall on 32 bit Windows
11363   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11364     return true;
11365 
11366   return false;
11367 }
11368 
11369 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11370   QualType T = FD->getType();
11371   assert(T->isFunctionType() && "function decl is not of function type");
11372   const FunctionType *FT = T->castAs<FunctionType>();
11373 
11374   // Set an implicit return of 'zero' if the function can return some integral,
11375   // enumeration, pointer or nullptr type.
11376   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11377       FT->getReturnType()->isAnyPointerType() ||
11378       FT->getReturnType()->isNullPtrType())
11379     // DllMain is exempt because a return value of zero means it failed.
11380     if (FD->getName() != "DllMain")
11381       FD->setHasImplicitReturnZero(true);
11382 
11383   // Explicity specified calling conventions are applied to MSVC entry points
11384   if (!hasExplicitCallingConv(T)) {
11385     if (isDefaultStdCall(FD, *this)) {
11386       if (FT->getCallConv() != CC_X86StdCall) {
11387         FT = Context.adjustFunctionType(
11388             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11389         FD->setType(QualType(FT, 0));
11390       }
11391     } else if (FT->getCallConv() != CC_C) {
11392       FT = Context.adjustFunctionType(FT,
11393                                       FT->getExtInfo().withCallingConv(CC_C));
11394       FD->setType(QualType(FT, 0));
11395     }
11396   }
11397 
11398   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11399     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11400     FD->setInvalidDecl();
11401   }
11402 }
11403 
11404 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11405   // FIXME: Need strict checking.  In C89, we need to check for
11406   // any assignment, increment, decrement, function-calls, or
11407   // commas outside of a sizeof.  In C99, it's the same list,
11408   // except that the aforementioned are allowed in unevaluated
11409   // expressions.  Everything else falls under the
11410   // "may accept other forms of constant expressions" exception.
11411   //
11412   // Regular C++ code will not end up here (exceptions: language extensions,
11413   // OpenCL C++ etc), so the constant expression rules there don't matter.
11414   if (Init->isValueDependent()) {
11415     assert(Init->containsErrors() &&
11416            "Dependent code should only occur in error-recovery path.");
11417     return true;
11418   }
11419   const Expr *Culprit;
11420   if (Init->isConstantInitializer(Context, false, &Culprit))
11421     return false;
11422   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11423     << Culprit->getSourceRange();
11424   return true;
11425 }
11426 
11427 namespace {
11428   // Visits an initialization expression to see if OrigDecl is evaluated in
11429   // its own initialization and throws a warning if it does.
11430   class SelfReferenceChecker
11431       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11432     Sema &S;
11433     Decl *OrigDecl;
11434     bool isRecordType;
11435     bool isPODType;
11436     bool isReferenceType;
11437 
11438     bool isInitList;
11439     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11440 
11441   public:
11442     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11443 
11444     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11445                                                     S(S), OrigDecl(OrigDecl) {
11446       isPODType = false;
11447       isRecordType = false;
11448       isReferenceType = false;
11449       isInitList = false;
11450       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11451         isPODType = VD->getType().isPODType(S.Context);
11452         isRecordType = VD->getType()->isRecordType();
11453         isReferenceType = VD->getType()->isReferenceType();
11454       }
11455     }
11456 
11457     // For most expressions, just call the visitor.  For initializer lists,
11458     // track the index of the field being initialized since fields are
11459     // initialized in order allowing use of previously initialized fields.
11460     void CheckExpr(Expr *E) {
11461       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11462       if (!InitList) {
11463         Visit(E);
11464         return;
11465       }
11466 
11467       // Track and increment the index here.
11468       isInitList = true;
11469       InitFieldIndex.push_back(0);
11470       for (auto Child : InitList->children()) {
11471         CheckExpr(cast<Expr>(Child));
11472         ++InitFieldIndex.back();
11473       }
11474       InitFieldIndex.pop_back();
11475     }
11476 
11477     // Returns true if MemberExpr is checked and no further checking is needed.
11478     // Returns false if additional checking is required.
11479     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11480       llvm::SmallVector<FieldDecl*, 4> Fields;
11481       Expr *Base = E;
11482       bool ReferenceField = false;
11483 
11484       // Get the field members used.
11485       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11486         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11487         if (!FD)
11488           return false;
11489         Fields.push_back(FD);
11490         if (FD->getType()->isReferenceType())
11491           ReferenceField = true;
11492         Base = ME->getBase()->IgnoreParenImpCasts();
11493       }
11494 
11495       // Keep checking only if the base Decl is the same.
11496       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11497       if (!DRE || DRE->getDecl() != OrigDecl)
11498         return false;
11499 
11500       // A reference field can be bound to an unininitialized field.
11501       if (CheckReference && !ReferenceField)
11502         return true;
11503 
11504       // Convert FieldDecls to their index number.
11505       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11506       for (const FieldDecl *I : llvm::reverse(Fields))
11507         UsedFieldIndex.push_back(I->getFieldIndex());
11508 
11509       // See if a warning is needed by checking the first difference in index
11510       // numbers.  If field being used has index less than the field being
11511       // initialized, then the use is safe.
11512       for (auto UsedIter = UsedFieldIndex.begin(),
11513                 UsedEnd = UsedFieldIndex.end(),
11514                 OrigIter = InitFieldIndex.begin(),
11515                 OrigEnd = InitFieldIndex.end();
11516            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11517         if (*UsedIter < *OrigIter)
11518           return true;
11519         if (*UsedIter > *OrigIter)
11520           break;
11521       }
11522 
11523       // TODO: Add a different warning which will print the field names.
11524       HandleDeclRefExpr(DRE);
11525       return true;
11526     }
11527 
11528     // For most expressions, the cast is directly above the DeclRefExpr.
11529     // For conditional operators, the cast can be outside the conditional
11530     // operator if both expressions are DeclRefExpr's.
11531     void HandleValue(Expr *E) {
11532       E = E->IgnoreParens();
11533       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11534         HandleDeclRefExpr(DRE);
11535         return;
11536       }
11537 
11538       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11539         Visit(CO->getCond());
11540         HandleValue(CO->getTrueExpr());
11541         HandleValue(CO->getFalseExpr());
11542         return;
11543       }
11544 
11545       if (BinaryConditionalOperator *BCO =
11546               dyn_cast<BinaryConditionalOperator>(E)) {
11547         Visit(BCO->getCond());
11548         HandleValue(BCO->getFalseExpr());
11549         return;
11550       }
11551 
11552       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11553         HandleValue(OVE->getSourceExpr());
11554         return;
11555       }
11556 
11557       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11558         if (BO->getOpcode() == BO_Comma) {
11559           Visit(BO->getLHS());
11560           HandleValue(BO->getRHS());
11561           return;
11562         }
11563       }
11564 
11565       if (isa<MemberExpr>(E)) {
11566         if (isInitList) {
11567           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11568                                       false /*CheckReference*/))
11569             return;
11570         }
11571 
11572         Expr *Base = E->IgnoreParenImpCasts();
11573         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11574           // Check for static member variables and don't warn on them.
11575           if (!isa<FieldDecl>(ME->getMemberDecl()))
11576             return;
11577           Base = ME->getBase()->IgnoreParenImpCasts();
11578         }
11579         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11580           HandleDeclRefExpr(DRE);
11581         return;
11582       }
11583 
11584       Visit(E);
11585     }
11586 
11587     // Reference types not handled in HandleValue are handled here since all
11588     // uses of references are bad, not just r-value uses.
11589     void VisitDeclRefExpr(DeclRefExpr *E) {
11590       if (isReferenceType)
11591         HandleDeclRefExpr(E);
11592     }
11593 
11594     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11595       if (E->getCastKind() == CK_LValueToRValue) {
11596         HandleValue(E->getSubExpr());
11597         return;
11598       }
11599 
11600       Inherited::VisitImplicitCastExpr(E);
11601     }
11602 
11603     void VisitMemberExpr(MemberExpr *E) {
11604       if (isInitList) {
11605         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11606           return;
11607       }
11608 
11609       // Don't warn on arrays since they can be treated as pointers.
11610       if (E->getType()->canDecayToPointerType()) return;
11611 
11612       // Warn when a non-static method call is followed by non-static member
11613       // field accesses, which is followed by a DeclRefExpr.
11614       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11615       bool Warn = (MD && !MD->isStatic());
11616       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11617       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11618         if (!isa<FieldDecl>(ME->getMemberDecl()))
11619           Warn = false;
11620         Base = ME->getBase()->IgnoreParenImpCasts();
11621       }
11622 
11623       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11624         if (Warn)
11625           HandleDeclRefExpr(DRE);
11626         return;
11627       }
11628 
11629       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11630       // Visit that expression.
11631       Visit(Base);
11632     }
11633 
11634     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11635       Expr *Callee = E->getCallee();
11636 
11637       if (isa<UnresolvedLookupExpr>(Callee))
11638         return Inherited::VisitCXXOperatorCallExpr(E);
11639 
11640       Visit(Callee);
11641       for (auto Arg: E->arguments())
11642         HandleValue(Arg->IgnoreParenImpCasts());
11643     }
11644 
11645     void VisitUnaryOperator(UnaryOperator *E) {
11646       // For POD record types, addresses of its own members are well-defined.
11647       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11648           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11649         if (!isPODType)
11650           HandleValue(E->getSubExpr());
11651         return;
11652       }
11653 
11654       if (E->isIncrementDecrementOp()) {
11655         HandleValue(E->getSubExpr());
11656         return;
11657       }
11658 
11659       Inherited::VisitUnaryOperator(E);
11660     }
11661 
11662     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11663 
11664     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11665       if (E->getConstructor()->isCopyConstructor()) {
11666         Expr *ArgExpr = E->getArg(0);
11667         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11668           if (ILE->getNumInits() == 1)
11669             ArgExpr = ILE->getInit(0);
11670         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11671           if (ICE->getCastKind() == CK_NoOp)
11672             ArgExpr = ICE->getSubExpr();
11673         HandleValue(ArgExpr);
11674         return;
11675       }
11676       Inherited::VisitCXXConstructExpr(E);
11677     }
11678 
11679     void VisitCallExpr(CallExpr *E) {
11680       // Treat std::move as a use.
11681       if (E->isCallToStdMove()) {
11682         HandleValue(E->getArg(0));
11683         return;
11684       }
11685 
11686       Inherited::VisitCallExpr(E);
11687     }
11688 
11689     void VisitBinaryOperator(BinaryOperator *E) {
11690       if (E->isCompoundAssignmentOp()) {
11691         HandleValue(E->getLHS());
11692         Visit(E->getRHS());
11693         return;
11694       }
11695 
11696       Inherited::VisitBinaryOperator(E);
11697     }
11698 
11699     // A custom visitor for BinaryConditionalOperator is needed because the
11700     // regular visitor would check the condition and true expression separately
11701     // but both point to the same place giving duplicate diagnostics.
11702     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11703       Visit(E->getCond());
11704       Visit(E->getFalseExpr());
11705     }
11706 
11707     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11708       Decl* ReferenceDecl = DRE->getDecl();
11709       if (OrigDecl != ReferenceDecl) return;
11710       unsigned diag;
11711       if (isReferenceType) {
11712         diag = diag::warn_uninit_self_reference_in_reference_init;
11713       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11714         diag = diag::warn_static_self_reference_in_init;
11715       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11716                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11717                  DRE->getDecl()->getType()->isRecordType()) {
11718         diag = diag::warn_uninit_self_reference_in_init;
11719       } else {
11720         // Local variables will be handled by the CFG analysis.
11721         return;
11722       }
11723 
11724       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11725                             S.PDiag(diag)
11726                                 << DRE->getDecl() << OrigDecl->getLocation()
11727                                 << DRE->getSourceRange());
11728     }
11729   };
11730 
11731   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11732   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11733                                  bool DirectInit) {
11734     // Parameters arguments are occassionially constructed with itself,
11735     // for instance, in recursive functions.  Skip them.
11736     if (isa<ParmVarDecl>(OrigDecl))
11737       return;
11738 
11739     E = E->IgnoreParens();
11740 
11741     // Skip checking T a = a where T is not a record or reference type.
11742     // Doing so is a way to silence uninitialized warnings.
11743     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11744       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11745         if (ICE->getCastKind() == CK_LValueToRValue)
11746           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11747             if (DRE->getDecl() == OrigDecl)
11748               return;
11749 
11750     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11751   }
11752 } // end anonymous namespace
11753 
11754 namespace {
11755   // Simple wrapper to add the name of a variable or (if no variable is
11756   // available) a DeclarationName into a diagnostic.
11757   struct VarDeclOrName {
11758     VarDecl *VDecl;
11759     DeclarationName Name;
11760 
11761     friend const Sema::SemaDiagnosticBuilder &
11762     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11763       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11764     }
11765   };
11766 } // end anonymous namespace
11767 
11768 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11769                                             DeclarationName Name, QualType Type,
11770                                             TypeSourceInfo *TSI,
11771                                             SourceRange Range, bool DirectInit,
11772                                             Expr *Init) {
11773   bool IsInitCapture = !VDecl;
11774   assert((!VDecl || !VDecl->isInitCapture()) &&
11775          "init captures are expected to be deduced prior to initialization");
11776 
11777   VarDeclOrName VN{VDecl, Name};
11778 
11779   DeducedType *Deduced = Type->getContainedDeducedType();
11780   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11781 
11782   // C++11 [dcl.spec.auto]p3
11783   if (!Init) {
11784     assert(VDecl && "no init for init capture deduction?");
11785 
11786     // Except for class argument deduction, and then for an initializing
11787     // declaration only, i.e. no static at class scope or extern.
11788     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11789         VDecl->hasExternalStorage() ||
11790         VDecl->isStaticDataMember()) {
11791       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11792         << VDecl->getDeclName() << Type;
11793       return QualType();
11794     }
11795   }
11796 
11797   ArrayRef<Expr*> DeduceInits;
11798   if (Init)
11799     DeduceInits = Init;
11800 
11801   if (DirectInit) {
11802     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11803       DeduceInits = PL->exprs();
11804   }
11805 
11806   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11807     assert(VDecl && "non-auto type for init capture deduction?");
11808     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11809     InitializationKind Kind = InitializationKind::CreateForInit(
11810         VDecl->getLocation(), DirectInit, Init);
11811     // FIXME: Initialization should not be taking a mutable list of inits.
11812     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11813     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11814                                                        InitsCopy);
11815   }
11816 
11817   if (DirectInit) {
11818     if (auto *IL = dyn_cast<InitListExpr>(Init))
11819       DeduceInits = IL->inits();
11820   }
11821 
11822   // Deduction only works if we have exactly one source expression.
11823   if (DeduceInits.empty()) {
11824     // It isn't possible to write this directly, but it is possible to
11825     // end up in this situation with "auto x(some_pack...);"
11826     Diag(Init->getBeginLoc(), IsInitCapture
11827                                   ? diag::err_init_capture_no_expression
11828                                   : diag::err_auto_var_init_no_expression)
11829         << VN << Type << Range;
11830     return QualType();
11831   }
11832 
11833   if (DeduceInits.size() > 1) {
11834     Diag(DeduceInits[1]->getBeginLoc(),
11835          IsInitCapture ? diag::err_init_capture_multiple_expressions
11836                        : diag::err_auto_var_init_multiple_expressions)
11837         << VN << Type << Range;
11838     return QualType();
11839   }
11840 
11841   Expr *DeduceInit = DeduceInits[0];
11842   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11843     Diag(Init->getBeginLoc(), IsInitCapture
11844                                   ? diag::err_init_capture_paren_braces
11845                                   : diag::err_auto_var_init_paren_braces)
11846         << isa<InitListExpr>(Init) << VN << Type << Range;
11847     return QualType();
11848   }
11849 
11850   // Expressions default to 'id' when we're in a debugger.
11851   bool DefaultedAnyToId = false;
11852   if (getLangOpts().DebuggerCastResultToId &&
11853       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11854     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11855     if (Result.isInvalid()) {
11856       return QualType();
11857     }
11858     Init = Result.get();
11859     DefaultedAnyToId = true;
11860   }
11861 
11862   // C++ [dcl.decomp]p1:
11863   //   If the assignment-expression [...] has array type A and no ref-qualifier
11864   //   is present, e has type cv A
11865   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11866       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11867       DeduceInit->getType()->isConstantArrayType())
11868     return Context.getQualifiedType(DeduceInit->getType(),
11869                                     Type.getQualifiers());
11870 
11871   QualType DeducedType;
11872   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11873     if (!IsInitCapture)
11874       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11875     else if (isa<InitListExpr>(Init))
11876       Diag(Range.getBegin(),
11877            diag::err_init_capture_deduction_failure_from_init_list)
11878           << VN
11879           << (DeduceInit->getType().isNull() ? TSI->getType()
11880                                              : DeduceInit->getType())
11881           << DeduceInit->getSourceRange();
11882     else
11883       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11884           << VN << TSI->getType()
11885           << (DeduceInit->getType().isNull() ? TSI->getType()
11886                                              : DeduceInit->getType())
11887           << DeduceInit->getSourceRange();
11888   }
11889 
11890   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11891   // 'id' instead of a specific object type prevents most of our usual
11892   // checks.
11893   // We only want to warn outside of template instantiations, though:
11894   // inside a template, the 'id' could have come from a parameter.
11895   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11896       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11897     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11898     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11899   }
11900 
11901   return DeducedType;
11902 }
11903 
11904 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11905                                          Expr *Init) {
11906   assert(!Init || !Init->containsErrors());
11907   QualType DeducedType = deduceVarTypeFromInitializer(
11908       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11909       VDecl->getSourceRange(), DirectInit, Init);
11910   if (DeducedType.isNull()) {
11911     VDecl->setInvalidDecl();
11912     return true;
11913   }
11914 
11915   VDecl->setType(DeducedType);
11916   assert(VDecl->isLinkageValid());
11917 
11918   // In ARC, infer lifetime.
11919   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11920     VDecl->setInvalidDecl();
11921 
11922   if (getLangOpts().OpenCL)
11923     deduceOpenCLAddressSpace(VDecl);
11924 
11925   // If this is a redeclaration, check that the type we just deduced matches
11926   // the previously declared type.
11927   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11928     // We never need to merge the type, because we cannot form an incomplete
11929     // array of auto, nor deduce such a type.
11930     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11931   }
11932 
11933   // Check the deduced type is valid for a variable declaration.
11934   CheckVariableDeclarationType(VDecl);
11935   return VDecl->isInvalidDecl();
11936 }
11937 
11938 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11939                                               SourceLocation Loc) {
11940   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11941     Init = EWC->getSubExpr();
11942 
11943   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11944     Init = CE->getSubExpr();
11945 
11946   QualType InitType = Init->getType();
11947   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11948           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11949          "shouldn't be called if type doesn't have a non-trivial C struct");
11950   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11951     for (auto I : ILE->inits()) {
11952       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11953           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11954         continue;
11955       SourceLocation SL = I->getExprLoc();
11956       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11957     }
11958     return;
11959   }
11960 
11961   if (isa<ImplicitValueInitExpr>(Init)) {
11962     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11963       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11964                             NTCUK_Init);
11965   } else {
11966     // Assume all other explicit initializers involving copying some existing
11967     // object.
11968     // TODO: ignore any explicit initializers where we can guarantee
11969     // copy-elision.
11970     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11971       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11972   }
11973 }
11974 
11975 namespace {
11976 
11977 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11978   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11979   // in the source code or implicitly by the compiler if it is in a union
11980   // defined in a system header and has non-trivial ObjC ownership
11981   // qualifications. We don't want those fields to participate in determining
11982   // whether the containing union is non-trivial.
11983   return FD->hasAttr<UnavailableAttr>();
11984 }
11985 
11986 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11987     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11988                                     void> {
11989   using Super =
11990       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11991                                     void>;
11992 
11993   DiagNonTrivalCUnionDefaultInitializeVisitor(
11994       QualType OrigTy, SourceLocation OrigLoc,
11995       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11996       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11997 
11998   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11999                      const FieldDecl *FD, bool InNonTrivialUnion) {
12000     if (const auto *AT = S.Context.getAsArrayType(QT))
12001       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12002                                      InNonTrivialUnion);
12003     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12004   }
12005 
12006   void visitARCStrong(QualType QT, const FieldDecl *FD,
12007                       bool InNonTrivialUnion) {
12008     if (InNonTrivialUnion)
12009       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12010           << 1 << 0 << QT << FD->getName();
12011   }
12012 
12013   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12014     if (InNonTrivialUnion)
12015       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12016           << 1 << 0 << QT << FD->getName();
12017   }
12018 
12019   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12020     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12021     if (RD->isUnion()) {
12022       if (OrigLoc.isValid()) {
12023         bool IsUnion = false;
12024         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12025           IsUnion = OrigRD->isUnion();
12026         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12027             << 0 << OrigTy << IsUnion << UseContext;
12028         // Reset OrigLoc so that this diagnostic is emitted only once.
12029         OrigLoc = SourceLocation();
12030       }
12031       InNonTrivialUnion = true;
12032     }
12033 
12034     if (InNonTrivialUnion)
12035       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12036           << 0 << 0 << QT.getUnqualifiedType() << "";
12037 
12038     for (const FieldDecl *FD : RD->fields())
12039       if (!shouldIgnoreForRecordTriviality(FD))
12040         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12041   }
12042 
12043   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12044 
12045   // The non-trivial C union type or the struct/union type that contains a
12046   // non-trivial C union.
12047   QualType OrigTy;
12048   SourceLocation OrigLoc;
12049   Sema::NonTrivialCUnionContext UseContext;
12050   Sema &S;
12051 };
12052 
12053 struct DiagNonTrivalCUnionDestructedTypeVisitor
12054     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12055   using Super =
12056       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12057 
12058   DiagNonTrivalCUnionDestructedTypeVisitor(
12059       QualType OrigTy, SourceLocation OrigLoc,
12060       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12061       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12062 
12063   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12064                      const FieldDecl *FD, bool InNonTrivialUnion) {
12065     if (const auto *AT = S.Context.getAsArrayType(QT))
12066       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12067                                      InNonTrivialUnion);
12068     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12069   }
12070 
12071   void visitARCStrong(QualType QT, const FieldDecl *FD,
12072                       bool InNonTrivialUnion) {
12073     if (InNonTrivialUnion)
12074       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12075           << 1 << 1 << QT << FD->getName();
12076   }
12077 
12078   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12079     if (InNonTrivialUnion)
12080       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12081           << 1 << 1 << QT << FD->getName();
12082   }
12083 
12084   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12085     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12086     if (RD->isUnion()) {
12087       if (OrigLoc.isValid()) {
12088         bool IsUnion = false;
12089         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12090           IsUnion = OrigRD->isUnion();
12091         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12092             << 1 << OrigTy << IsUnion << UseContext;
12093         // Reset OrigLoc so that this diagnostic is emitted only once.
12094         OrigLoc = SourceLocation();
12095       }
12096       InNonTrivialUnion = true;
12097     }
12098 
12099     if (InNonTrivialUnion)
12100       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12101           << 0 << 1 << QT.getUnqualifiedType() << "";
12102 
12103     for (const FieldDecl *FD : RD->fields())
12104       if (!shouldIgnoreForRecordTriviality(FD))
12105         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12106   }
12107 
12108   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12109   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12110                           bool InNonTrivialUnion) {}
12111 
12112   // The non-trivial C union type or the struct/union type that contains a
12113   // non-trivial C union.
12114   QualType OrigTy;
12115   SourceLocation OrigLoc;
12116   Sema::NonTrivialCUnionContext UseContext;
12117   Sema &S;
12118 };
12119 
12120 struct DiagNonTrivalCUnionCopyVisitor
12121     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12122   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12123 
12124   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12125                                  Sema::NonTrivialCUnionContext UseContext,
12126                                  Sema &S)
12127       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12128 
12129   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12130                      const FieldDecl *FD, bool InNonTrivialUnion) {
12131     if (const auto *AT = S.Context.getAsArrayType(QT))
12132       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12133                                      InNonTrivialUnion);
12134     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12135   }
12136 
12137   void visitARCStrong(QualType QT, const FieldDecl *FD,
12138                       bool InNonTrivialUnion) {
12139     if (InNonTrivialUnion)
12140       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12141           << 1 << 2 << QT << FD->getName();
12142   }
12143 
12144   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12145     if (InNonTrivialUnion)
12146       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12147           << 1 << 2 << QT << FD->getName();
12148   }
12149 
12150   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12151     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12152     if (RD->isUnion()) {
12153       if (OrigLoc.isValid()) {
12154         bool IsUnion = false;
12155         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12156           IsUnion = OrigRD->isUnion();
12157         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12158             << 2 << OrigTy << IsUnion << UseContext;
12159         // Reset OrigLoc so that this diagnostic is emitted only once.
12160         OrigLoc = SourceLocation();
12161       }
12162       InNonTrivialUnion = true;
12163     }
12164 
12165     if (InNonTrivialUnion)
12166       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12167           << 0 << 2 << QT.getUnqualifiedType() << "";
12168 
12169     for (const FieldDecl *FD : RD->fields())
12170       if (!shouldIgnoreForRecordTriviality(FD))
12171         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12172   }
12173 
12174   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12175                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12176   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12177   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12178                             bool InNonTrivialUnion) {}
12179 
12180   // The non-trivial C union type or the struct/union type that contains a
12181   // non-trivial C union.
12182   QualType OrigTy;
12183   SourceLocation OrigLoc;
12184   Sema::NonTrivialCUnionContext UseContext;
12185   Sema &S;
12186 };
12187 
12188 } // namespace
12189 
12190 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12191                                  NonTrivialCUnionContext UseContext,
12192                                  unsigned NonTrivialKind) {
12193   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12194           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12195           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12196          "shouldn't be called if type doesn't have a non-trivial C union");
12197 
12198   if ((NonTrivialKind & NTCUK_Init) &&
12199       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12200     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12201         .visit(QT, nullptr, false);
12202   if ((NonTrivialKind & NTCUK_Destruct) &&
12203       QT.hasNonTrivialToPrimitiveDestructCUnion())
12204     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12205         .visit(QT, nullptr, false);
12206   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12207     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12208         .visit(QT, nullptr, false);
12209 }
12210 
12211 /// AddInitializerToDecl - Adds the initializer Init to the
12212 /// declaration dcl. If DirectInit is true, this is C++ direct
12213 /// initialization rather than copy initialization.
12214 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12215   // If there is no declaration, there was an error parsing it.  Just ignore
12216   // the initializer.
12217   if (!RealDecl || RealDecl->isInvalidDecl()) {
12218     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12219     return;
12220   }
12221 
12222   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12223     // Pure-specifiers are handled in ActOnPureSpecifier.
12224     Diag(Method->getLocation(), diag::err_member_function_initialization)
12225       << Method->getDeclName() << Init->getSourceRange();
12226     Method->setInvalidDecl();
12227     return;
12228   }
12229 
12230   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12231   if (!VDecl) {
12232     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12233     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12234     RealDecl->setInvalidDecl();
12235     return;
12236   }
12237 
12238   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12239   if (VDecl->getType()->isUndeducedType()) {
12240     // Attempt typo correction early so that the type of the init expression can
12241     // be deduced based on the chosen correction if the original init contains a
12242     // TypoExpr.
12243     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12244     if (!Res.isUsable()) {
12245       // There are unresolved typos in Init, just drop them.
12246       // FIXME: improve the recovery strategy to preserve the Init.
12247       RealDecl->setInvalidDecl();
12248       return;
12249     }
12250     if (Res.get()->containsErrors()) {
12251       // Invalidate the decl as we don't know the type for recovery-expr yet.
12252       RealDecl->setInvalidDecl();
12253       VDecl->setInit(Res.get());
12254       return;
12255     }
12256     Init = Res.get();
12257 
12258     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12259       return;
12260   }
12261 
12262   // dllimport cannot be used on variable definitions.
12263   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12264     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12265     VDecl->setInvalidDecl();
12266     return;
12267   }
12268 
12269   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12270     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12271     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12272     VDecl->setInvalidDecl();
12273     return;
12274   }
12275 
12276   if (!VDecl->getType()->isDependentType()) {
12277     // A definition must end up with a complete type, which means it must be
12278     // complete with the restriction that an array type might be completed by
12279     // the initializer; note that later code assumes this restriction.
12280     QualType BaseDeclType = VDecl->getType();
12281     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12282       BaseDeclType = Array->getElementType();
12283     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12284                             diag::err_typecheck_decl_incomplete_type)) {
12285       RealDecl->setInvalidDecl();
12286       return;
12287     }
12288 
12289     // The variable can not have an abstract class type.
12290     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12291                                diag::err_abstract_type_in_decl,
12292                                AbstractVariableType))
12293       VDecl->setInvalidDecl();
12294   }
12295 
12296   // If adding the initializer will turn this declaration into a definition,
12297   // and we already have a definition for this variable, diagnose or otherwise
12298   // handle the situation.
12299   if (VarDecl *Def = VDecl->getDefinition())
12300     if (Def != VDecl &&
12301         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12302         !VDecl->isThisDeclarationADemotedDefinition() &&
12303         checkVarDeclRedefinition(Def, VDecl))
12304       return;
12305 
12306   if (getLangOpts().CPlusPlus) {
12307     // C++ [class.static.data]p4
12308     //   If a static data member is of const integral or const
12309     //   enumeration type, its declaration in the class definition can
12310     //   specify a constant-initializer which shall be an integral
12311     //   constant expression (5.19). In that case, the member can appear
12312     //   in integral constant expressions. The member shall still be
12313     //   defined in a namespace scope if it is used in the program and the
12314     //   namespace scope definition shall not contain an initializer.
12315     //
12316     // We already performed a redefinition check above, but for static
12317     // data members we also need to check whether there was an in-class
12318     // declaration with an initializer.
12319     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12320       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12321           << VDecl->getDeclName();
12322       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12323            diag::note_previous_initializer)
12324           << 0;
12325       return;
12326     }
12327 
12328     if (VDecl->hasLocalStorage())
12329       setFunctionHasBranchProtectedScope();
12330 
12331     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12332       VDecl->setInvalidDecl();
12333       return;
12334     }
12335   }
12336 
12337   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12338   // a kernel function cannot be initialized."
12339   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12340     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12341     VDecl->setInvalidDecl();
12342     return;
12343   }
12344 
12345   // The LoaderUninitialized attribute acts as a definition (of undef).
12346   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12347     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12348     VDecl->setInvalidDecl();
12349     return;
12350   }
12351 
12352   // Get the decls type and save a reference for later, since
12353   // CheckInitializerTypes may change it.
12354   QualType DclT = VDecl->getType(), SavT = DclT;
12355 
12356   // Expressions default to 'id' when we're in a debugger
12357   // and we are assigning it to a variable of Objective-C pointer type.
12358   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12359       Init->getType() == Context.UnknownAnyTy) {
12360     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12361     if (Result.isInvalid()) {
12362       VDecl->setInvalidDecl();
12363       return;
12364     }
12365     Init = Result.get();
12366   }
12367 
12368   // Perform the initialization.
12369   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12370   if (!VDecl->isInvalidDecl()) {
12371     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12372     InitializationKind Kind = InitializationKind::CreateForInit(
12373         VDecl->getLocation(), DirectInit, Init);
12374 
12375     MultiExprArg Args = Init;
12376     if (CXXDirectInit)
12377       Args = MultiExprArg(CXXDirectInit->getExprs(),
12378                           CXXDirectInit->getNumExprs());
12379 
12380     // Try to correct any TypoExprs in the initialization arguments.
12381     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12382       ExprResult Res = CorrectDelayedTyposInExpr(
12383           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12384           [this, Entity, Kind](Expr *E) {
12385             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12386             return Init.Failed() ? ExprError() : E;
12387           });
12388       if (Res.isInvalid()) {
12389         VDecl->setInvalidDecl();
12390       } else if (Res.get() != Args[Idx]) {
12391         Args[Idx] = Res.get();
12392       }
12393     }
12394     if (VDecl->isInvalidDecl())
12395       return;
12396 
12397     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12398                                    /*TopLevelOfInitList=*/false,
12399                                    /*TreatUnavailableAsInvalid=*/false);
12400     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12401     if (Result.isInvalid()) {
12402       // If the provided initializer fails to initialize the var decl,
12403       // we attach a recovery expr for better recovery.
12404       auto RecoveryExpr =
12405           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12406       if (RecoveryExpr.get())
12407         VDecl->setInit(RecoveryExpr.get());
12408       return;
12409     }
12410 
12411     Init = Result.getAs<Expr>();
12412   }
12413 
12414   // Check for self-references within variable initializers.
12415   // Variables declared within a function/method body (except for references)
12416   // are handled by a dataflow analysis.
12417   // This is undefined behavior in C++, but valid in C.
12418   if (getLangOpts().CPlusPlus)
12419     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12420         VDecl->getType()->isReferenceType())
12421       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12422 
12423   // If the type changed, it means we had an incomplete type that was
12424   // completed by the initializer. For example:
12425   //   int ary[] = { 1, 3, 5 };
12426   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12427   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12428     VDecl->setType(DclT);
12429 
12430   if (!VDecl->isInvalidDecl()) {
12431     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12432 
12433     if (VDecl->hasAttr<BlocksAttr>())
12434       checkRetainCycles(VDecl, Init);
12435 
12436     // It is safe to assign a weak reference into a strong variable.
12437     // Although this code can still have problems:
12438     //   id x = self.weakProp;
12439     //   id y = self.weakProp;
12440     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12441     // paths through the function. This should be revisited if
12442     // -Wrepeated-use-of-weak is made flow-sensitive.
12443     if (FunctionScopeInfo *FSI = getCurFunction())
12444       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12445            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12446           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12447                            Init->getBeginLoc()))
12448         FSI->markSafeWeakUse(Init);
12449   }
12450 
12451   // The initialization is usually a full-expression.
12452   //
12453   // FIXME: If this is a braced initialization of an aggregate, it is not
12454   // an expression, and each individual field initializer is a separate
12455   // full-expression. For instance, in:
12456   //
12457   //   struct Temp { ~Temp(); };
12458   //   struct S { S(Temp); };
12459   //   struct T { S a, b; } t = { Temp(), Temp() }
12460   //
12461   // we should destroy the first Temp before constructing the second.
12462   ExprResult Result =
12463       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12464                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12465   if (Result.isInvalid()) {
12466     VDecl->setInvalidDecl();
12467     return;
12468   }
12469   Init = Result.get();
12470 
12471   // Attach the initializer to the decl.
12472   VDecl->setInit(Init);
12473 
12474   if (VDecl->isLocalVarDecl()) {
12475     // Don't check the initializer if the declaration is malformed.
12476     if (VDecl->isInvalidDecl()) {
12477       // do nothing
12478 
12479     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12480     // This is true even in C++ for OpenCL.
12481     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12482       CheckForConstantInitializer(Init, DclT);
12483 
12484     // Otherwise, C++ does not restrict the initializer.
12485     } else if (getLangOpts().CPlusPlus) {
12486       // do nothing
12487 
12488     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12489     // static storage duration shall be constant expressions or string literals.
12490     } else if (VDecl->getStorageClass() == SC_Static) {
12491       CheckForConstantInitializer(Init, DclT);
12492 
12493     // C89 is stricter than C99 for aggregate initializers.
12494     // C89 6.5.7p3: All the expressions [...] in an initializer list
12495     // for an object that has aggregate or union type shall be
12496     // constant expressions.
12497     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12498                isa<InitListExpr>(Init)) {
12499       const Expr *Culprit;
12500       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12501         Diag(Culprit->getExprLoc(),
12502              diag::ext_aggregate_init_not_constant)
12503           << Culprit->getSourceRange();
12504       }
12505     }
12506 
12507     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12508       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12509         if (VDecl->hasLocalStorage())
12510           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12511   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12512              VDecl->getLexicalDeclContext()->isRecord()) {
12513     // This is an in-class initialization for a static data member, e.g.,
12514     //
12515     // struct S {
12516     //   static const int value = 17;
12517     // };
12518 
12519     // C++ [class.mem]p4:
12520     //   A member-declarator can contain a constant-initializer only
12521     //   if it declares a static member (9.4) of const integral or
12522     //   const enumeration type, see 9.4.2.
12523     //
12524     // C++11 [class.static.data]p3:
12525     //   If a non-volatile non-inline const static data member is of integral
12526     //   or enumeration type, its declaration in the class definition can
12527     //   specify a brace-or-equal-initializer in which every initializer-clause
12528     //   that is an assignment-expression is a constant expression. A static
12529     //   data member of literal type can be declared in the class definition
12530     //   with the constexpr specifier; if so, its declaration shall specify a
12531     //   brace-or-equal-initializer in which every initializer-clause that is
12532     //   an assignment-expression is a constant expression.
12533 
12534     // Do nothing on dependent types.
12535     if (DclT->isDependentType()) {
12536 
12537     // Allow any 'static constexpr' members, whether or not they are of literal
12538     // type. We separately check that every constexpr variable is of literal
12539     // type.
12540     } else if (VDecl->isConstexpr()) {
12541 
12542     // Require constness.
12543     } else if (!DclT.isConstQualified()) {
12544       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12545         << Init->getSourceRange();
12546       VDecl->setInvalidDecl();
12547 
12548     // We allow integer constant expressions in all cases.
12549     } else if (DclT->isIntegralOrEnumerationType()) {
12550       // Check whether the expression is a constant expression.
12551       SourceLocation Loc;
12552       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12553         // In C++11, a non-constexpr const static data member with an
12554         // in-class initializer cannot be volatile.
12555         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12556       else if (Init->isValueDependent())
12557         ; // Nothing to check.
12558       else if (Init->isIntegerConstantExpr(Context, &Loc))
12559         ; // Ok, it's an ICE!
12560       else if (Init->getType()->isScopedEnumeralType() &&
12561                Init->isCXX11ConstantExpr(Context))
12562         ; // Ok, it is a scoped-enum constant expression.
12563       else if (Init->isEvaluatable(Context)) {
12564         // If we can constant fold the initializer through heroics, accept it,
12565         // but report this as a use of an extension for -pedantic.
12566         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12567           << Init->getSourceRange();
12568       } else {
12569         // Otherwise, this is some crazy unknown case.  Report the issue at the
12570         // location provided by the isIntegerConstantExpr failed check.
12571         Diag(Loc, diag::err_in_class_initializer_non_constant)
12572           << Init->getSourceRange();
12573         VDecl->setInvalidDecl();
12574       }
12575 
12576     // We allow foldable floating-point constants as an extension.
12577     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12578       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12579       // it anyway and provide a fixit to add the 'constexpr'.
12580       if (getLangOpts().CPlusPlus11) {
12581         Diag(VDecl->getLocation(),
12582              diag::ext_in_class_initializer_float_type_cxx11)
12583             << DclT << Init->getSourceRange();
12584         Diag(VDecl->getBeginLoc(),
12585              diag::note_in_class_initializer_float_type_cxx11)
12586             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12587       } else {
12588         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12589           << DclT << Init->getSourceRange();
12590 
12591         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12592           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12593             << Init->getSourceRange();
12594           VDecl->setInvalidDecl();
12595         }
12596       }
12597 
12598     // Suggest adding 'constexpr' in C++11 for literal types.
12599     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12600       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12601           << DclT << Init->getSourceRange()
12602           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12603       VDecl->setConstexpr(true);
12604 
12605     } else {
12606       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12607         << DclT << Init->getSourceRange();
12608       VDecl->setInvalidDecl();
12609     }
12610   } else if (VDecl->isFileVarDecl()) {
12611     // In C, extern is typically used to avoid tentative definitions when
12612     // declaring variables in headers, but adding an intializer makes it a
12613     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12614     // In C++, extern is often used to give implictly static const variables
12615     // external linkage, so don't warn in that case. If selectany is present,
12616     // this might be header code intended for C and C++ inclusion, so apply the
12617     // C++ rules.
12618     if (VDecl->getStorageClass() == SC_Extern &&
12619         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12620          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12621         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12622         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12623       Diag(VDecl->getLocation(), diag::warn_extern_init);
12624 
12625     // In Microsoft C++ mode, a const variable defined in namespace scope has
12626     // external linkage by default if the variable is declared with
12627     // __declspec(dllexport).
12628     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12629         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12630         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12631       VDecl->setStorageClass(SC_Extern);
12632 
12633     // C99 6.7.8p4. All file scoped initializers need to be constant.
12634     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12635       CheckForConstantInitializer(Init, DclT);
12636   }
12637 
12638   QualType InitType = Init->getType();
12639   if (!InitType.isNull() &&
12640       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12641        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12642     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12643 
12644   // We will represent direct-initialization similarly to copy-initialization:
12645   //    int x(1);  -as-> int x = 1;
12646   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12647   //
12648   // Clients that want to distinguish between the two forms, can check for
12649   // direct initializer using VarDecl::getInitStyle().
12650   // A major benefit is that clients that don't particularly care about which
12651   // exactly form was it (like the CodeGen) can handle both cases without
12652   // special case code.
12653 
12654   // C++ 8.5p11:
12655   // The form of initialization (using parentheses or '=') is generally
12656   // insignificant, but does matter when the entity being initialized has a
12657   // class type.
12658   if (CXXDirectInit) {
12659     assert(DirectInit && "Call-style initializer must be direct init.");
12660     VDecl->setInitStyle(VarDecl::CallInit);
12661   } else if (DirectInit) {
12662     // This must be list-initialization. No other way is direct-initialization.
12663     VDecl->setInitStyle(VarDecl::ListInit);
12664   }
12665 
12666   if (LangOpts.OpenMP &&
12667       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12668       VDecl->isFileVarDecl())
12669     DeclsToCheckForDeferredDiags.insert(VDecl);
12670   CheckCompleteVariableDeclaration(VDecl);
12671 }
12672 
12673 /// ActOnInitializerError - Given that there was an error parsing an
12674 /// initializer for the given declaration, try to at least re-establish
12675 /// invariants such as whether a variable's type is either dependent or
12676 /// complete.
12677 void Sema::ActOnInitializerError(Decl *D) {
12678   // Our main concern here is re-establishing invariants like "a
12679   // variable's type is either dependent or complete".
12680   if (!D || D->isInvalidDecl()) return;
12681 
12682   VarDecl *VD = dyn_cast<VarDecl>(D);
12683   if (!VD) return;
12684 
12685   // Bindings are not usable if we can't make sense of the initializer.
12686   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12687     for (auto *BD : DD->bindings())
12688       BD->setInvalidDecl();
12689 
12690   // Auto types are meaningless if we can't make sense of the initializer.
12691   if (VD->getType()->isUndeducedType()) {
12692     D->setInvalidDecl();
12693     return;
12694   }
12695 
12696   QualType Ty = VD->getType();
12697   if (Ty->isDependentType()) return;
12698 
12699   // Require a complete type.
12700   if (RequireCompleteType(VD->getLocation(),
12701                           Context.getBaseElementType(Ty),
12702                           diag::err_typecheck_decl_incomplete_type)) {
12703     VD->setInvalidDecl();
12704     return;
12705   }
12706 
12707   // Require a non-abstract type.
12708   if (RequireNonAbstractType(VD->getLocation(), Ty,
12709                              diag::err_abstract_type_in_decl,
12710                              AbstractVariableType)) {
12711     VD->setInvalidDecl();
12712     return;
12713   }
12714 
12715   // Don't bother complaining about constructors or destructors,
12716   // though.
12717 }
12718 
12719 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12720   // If there is no declaration, there was an error parsing it. Just ignore it.
12721   if (!RealDecl)
12722     return;
12723 
12724   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12725     QualType Type = Var->getType();
12726 
12727     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12728     if (isa<DecompositionDecl>(RealDecl)) {
12729       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12730       Var->setInvalidDecl();
12731       return;
12732     }
12733 
12734     if (Type->isUndeducedType() &&
12735         DeduceVariableDeclarationType(Var, false, nullptr))
12736       return;
12737 
12738     // C++11 [class.static.data]p3: A static data member can be declared with
12739     // the constexpr specifier; if so, its declaration shall specify
12740     // a brace-or-equal-initializer.
12741     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12742     // the definition of a variable [...] or the declaration of a static data
12743     // member.
12744     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12745         !Var->isThisDeclarationADemotedDefinition()) {
12746       if (Var->isStaticDataMember()) {
12747         // C++1z removes the relevant rule; the in-class declaration is always
12748         // a definition there.
12749         if (!getLangOpts().CPlusPlus17 &&
12750             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12751           Diag(Var->getLocation(),
12752                diag::err_constexpr_static_mem_var_requires_init)
12753               << Var;
12754           Var->setInvalidDecl();
12755           return;
12756         }
12757       } else {
12758         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12759         Var->setInvalidDecl();
12760         return;
12761       }
12762     }
12763 
12764     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12765     // be initialized.
12766     if (!Var->isInvalidDecl() &&
12767         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12768         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12769       bool HasConstExprDefaultConstructor = false;
12770       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12771         for (auto *Ctor : RD->ctors()) {
12772           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12773               Ctor->getMethodQualifiers().getAddressSpace() ==
12774                   LangAS::opencl_constant) {
12775             HasConstExprDefaultConstructor = true;
12776           }
12777         }
12778       }
12779       if (!HasConstExprDefaultConstructor) {
12780         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12781         Var->setInvalidDecl();
12782         return;
12783       }
12784     }
12785 
12786     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12787       if (Var->getStorageClass() == SC_Extern) {
12788         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12789             << Var;
12790         Var->setInvalidDecl();
12791         return;
12792       }
12793       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12794                               diag::err_typecheck_decl_incomplete_type)) {
12795         Var->setInvalidDecl();
12796         return;
12797       }
12798       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12799         if (!RD->hasTrivialDefaultConstructor()) {
12800           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12801           Var->setInvalidDecl();
12802           return;
12803         }
12804       }
12805       // The declaration is unitialized, no need for further checks.
12806       return;
12807     }
12808 
12809     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12810     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12811         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12812       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12813                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12814 
12815 
12816     switch (DefKind) {
12817     case VarDecl::Definition:
12818       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12819         break;
12820 
12821       // We have an out-of-line definition of a static data member
12822       // that has an in-class initializer, so we type-check this like
12823       // a declaration.
12824       //
12825       LLVM_FALLTHROUGH;
12826 
12827     case VarDecl::DeclarationOnly:
12828       // It's only a declaration.
12829 
12830       // Block scope. C99 6.7p7: If an identifier for an object is
12831       // declared with no linkage (C99 6.2.2p6), the type for the
12832       // object shall be complete.
12833       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12834           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12835           RequireCompleteType(Var->getLocation(), Type,
12836                               diag::err_typecheck_decl_incomplete_type))
12837         Var->setInvalidDecl();
12838 
12839       // Make sure that the type is not abstract.
12840       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12841           RequireNonAbstractType(Var->getLocation(), Type,
12842                                  diag::err_abstract_type_in_decl,
12843                                  AbstractVariableType))
12844         Var->setInvalidDecl();
12845       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12846           Var->getStorageClass() == SC_PrivateExtern) {
12847         Diag(Var->getLocation(), diag::warn_private_extern);
12848         Diag(Var->getLocation(), diag::note_private_extern);
12849       }
12850 
12851       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12852           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12853         ExternalDeclarations.push_back(Var);
12854 
12855       return;
12856 
12857     case VarDecl::TentativeDefinition:
12858       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12859       // object that has file scope without an initializer, and without a
12860       // storage-class specifier or with the storage-class specifier "static",
12861       // constitutes a tentative definition. Note: A tentative definition with
12862       // external linkage is valid (C99 6.2.2p5).
12863       if (!Var->isInvalidDecl()) {
12864         if (const IncompleteArrayType *ArrayT
12865                                     = Context.getAsIncompleteArrayType(Type)) {
12866           if (RequireCompleteSizedType(
12867                   Var->getLocation(), ArrayT->getElementType(),
12868                   diag::err_array_incomplete_or_sizeless_type))
12869             Var->setInvalidDecl();
12870         } else if (Var->getStorageClass() == SC_Static) {
12871           // C99 6.9.2p3: If the declaration of an identifier for an object is
12872           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12873           // declared type shall not be an incomplete type.
12874           // NOTE: code such as the following
12875           //     static struct s;
12876           //     struct s { int a; };
12877           // is accepted by gcc. Hence here we issue a warning instead of
12878           // an error and we do not invalidate the static declaration.
12879           // NOTE: to avoid multiple warnings, only check the first declaration.
12880           if (Var->isFirstDecl())
12881             RequireCompleteType(Var->getLocation(), Type,
12882                                 diag::ext_typecheck_decl_incomplete_type);
12883         }
12884       }
12885 
12886       // Record the tentative definition; we're done.
12887       if (!Var->isInvalidDecl())
12888         TentativeDefinitions.push_back(Var);
12889       return;
12890     }
12891 
12892     // Provide a specific diagnostic for uninitialized variable
12893     // definitions with incomplete array type.
12894     if (Type->isIncompleteArrayType()) {
12895       Diag(Var->getLocation(),
12896            diag::err_typecheck_incomplete_array_needs_initializer);
12897       Var->setInvalidDecl();
12898       return;
12899     }
12900 
12901     // Provide a specific diagnostic for uninitialized variable
12902     // definitions with reference type.
12903     if (Type->isReferenceType()) {
12904       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12905           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12906       Var->setInvalidDecl();
12907       return;
12908     }
12909 
12910     // Do not attempt to type-check the default initializer for a
12911     // variable with dependent type.
12912     if (Type->isDependentType())
12913       return;
12914 
12915     if (Var->isInvalidDecl())
12916       return;
12917 
12918     if (!Var->hasAttr<AliasAttr>()) {
12919       if (RequireCompleteType(Var->getLocation(),
12920                               Context.getBaseElementType(Type),
12921                               diag::err_typecheck_decl_incomplete_type)) {
12922         Var->setInvalidDecl();
12923         return;
12924       }
12925     } else {
12926       return;
12927     }
12928 
12929     // The variable can not have an abstract class type.
12930     if (RequireNonAbstractType(Var->getLocation(), Type,
12931                                diag::err_abstract_type_in_decl,
12932                                AbstractVariableType)) {
12933       Var->setInvalidDecl();
12934       return;
12935     }
12936 
12937     // Check for jumps past the implicit initializer.  C++0x
12938     // clarifies that this applies to a "variable with automatic
12939     // storage duration", not a "local variable".
12940     // C++11 [stmt.dcl]p3
12941     //   A program that jumps from a point where a variable with automatic
12942     //   storage duration is not in scope to a point where it is in scope is
12943     //   ill-formed unless the variable has scalar type, class type with a
12944     //   trivial default constructor and a trivial destructor, a cv-qualified
12945     //   version of one of these types, or an array of one of the preceding
12946     //   types and is declared without an initializer.
12947     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12948       if (const RecordType *Record
12949             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12950         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12951         // Mark the function (if we're in one) for further checking even if the
12952         // looser rules of C++11 do not require such checks, so that we can
12953         // diagnose incompatibilities with C++98.
12954         if (!CXXRecord->isPOD())
12955           setFunctionHasBranchProtectedScope();
12956       }
12957     }
12958     // In OpenCL, we can't initialize objects in the __local address space,
12959     // even implicitly, so don't synthesize an implicit initializer.
12960     if (getLangOpts().OpenCL &&
12961         Var->getType().getAddressSpace() == LangAS::opencl_local)
12962       return;
12963     // C++03 [dcl.init]p9:
12964     //   If no initializer is specified for an object, and the
12965     //   object is of (possibly cv-qualified) non-POD class type (or
12966     //   array thereof), the object shall be default-initialized; if
12967     //   the object is of const-qualified type, the underlying class
12968     //   type shall have a user-declared default
12969     //   constructor. Otherwise, if no initializer is specified for
12970     //   a non- static object, the object and its subobjects, if
12971     //   any, have an indeterminate initial value); if the object
12972     //   or any of its subobjects are of const-qualified type, the
12973     //   program is ill-formed.
12974     // C++0x [dcl.init]p11:
12975     //   If no initializer is specified for an object, the object is
12976     //   default-initialized; [...].
12977     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12978     InitializationKind Kind
12979       = InitializationKind::CreateDefault(Var->getLocation());
12980 
12981     InitializationSequence InitSeq(*this, Entity, Kind, None);
12982     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12983 
12984     if (Init.get()) {
12985       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12986       // This is important for template substitution.
12987       Var->setInitStyle(VarDecl::CallInit);
12988     } else if (Init.isInvalid()) {
12989       // If default-init fails, attach a recovery-expr initializer to track
12990       // that initialization was attempted and failed.
12991       auto RecoveryExpr =
12992           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12993       if (RecoveryExpr.get())
12994         Var->setInit(RecoveryExpr.get());
12995     }
12996 
12997     CheckCompleteVariableDeclaration(Var);
12998   }
12999 }
13000 
13001 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13002   // If there is no declaration, there was an error parsing it. Ignore it.
13003   if (!D)
13004     return;
13005 
13006   VarDecl *VD = dyn_cast<VarDecl>(D);
13007   if (!VD) {
13008     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13009     D->setInvalidDecl();
13010     return;
13011   }
13012 
13013   VD->setCXXForRangeDecl(true);
13014 
13015   // for-range-declaration cannot be given a storage class specifier.
13016   int Error = -1;
13017   switch (VD->getStorageClass()) {
13018   case SC_None:
13019     break;
13020   case SC_Extern:
13021     Error = 0;
13022     break;
13023   case SC_Static:
13024     Error = 1;
13025     break;
13026   case SC_PrivateExtern:
13027     Error = 2;
13028     break;
13029   case SC_Auto:
13030     Error = 3;
13031     break;
13032   case SC_Register:
13033     Error = 4;
13034     break;
13035   }
13036 
13037   // for-range-declaration cannot be given a storage class specifier con't.
13038   switch (VD->getTSCSpec()) {
13039   case TSCS_thread_local:
13040     Error = 6;
13041     break;
13042   case TSCS___thread:
13043   case TSCS__Thread_local:
13044   case TSCS_unspecified:
13045     break;
13046   }
13047 
13048   if (Error != -1) {
13049     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13050         << VD << Error;
13051     D->setInvalidDecl();
13052   }
13053 }
13054 
13055 StmtResult
13056 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13057                                  IdentifierInfo *Ident,
13058                                  ParsedAttributes &Attrs,
13059                                  SourceLocation AttrEnd) {
13060   // C++1y [stmt.iter]p1:
13061   //   A range-based for statement of the form
13062   //      for ( for-range-identifier : for-range-initializer ) statement
13063   //   is equivalent to
13064   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13065   DeclSpec DS(Attrs.getPool().getFactory());
13066 
13067   const char *PrevSpec;
13068   unsigned DiagID;
13069   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13070                      getPrintingPolicy());
13071 
13072   Declarator D(DS, DeclaratorContext::ForInit);
13073   D.SetIdentifier(Ident, IdentLoc);
13074   D.takeAttributes(Attrs, AttrEnd);
13075 
13076   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13077                 IdentLoc);
13078   Decl *Var = ActOnDeclarator(S, D);
13079   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13080   FinalizeDeclaration(Var);
13081   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13082                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13083 }
13084 
13085 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13086   if (var->isInvalidDecl()) return;
13087 
13088   MaybeAddCUDAConstantAttr(var);
13089 
13090   if (getLangOpts().OpenCL) {
13091     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13092     // initialiser
13093     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13094         !var->hasInit()) {
13095       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13096           << 1 /*Init*/;
13097       var->setInvalidDecl();
13098       return;
13099     }
13100   }
13101 
13102   // In Objective-C, don't allow jumps past the implicit initialization of a
13103   // local retaining variable.
13104   if (getLangOpts().ObjC &&
13105       var->hasLocalStorage()) {
13106     switch (var->getType().getObjCLifetime()) {
13107     case Qualifiers::OCL_None:
13108     case Qualifiers::OCL_ExplicitNone:
13109     case Qualifiers::OCL_Autoreleasing:
13110       break;
13111 
13112     case Qualifiers::OCL_Weak:
13113     case Qualifiers::OCL_Strong:
13114       setFunctionHasBranchProtectedScope();
13115       break;
13116     }
13117   }
13118 
13119   if (var->hasLocalStorage() &&
13120       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13121     setFunctionHasBranchProtectedScope();
13122 
13123   // Warn about externally-visible variables being defined without a
13124   // prior declaration.  We only want to do this for global
13125   // declarations, but we also specifically need to avoid doing it for
13126   // class members because the linkage of an anonymous class can
13127   // change if it's later given a typedef name.
13128   if (var->isThisDeclarationADefinition() &&
13129       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13130       var->isExternallyVisible() && var->hasLinkage() &&
13131       !var->isInline() && !var->getDescribedVarTemplate() &&
13132       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13133       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13134       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13135                                   var->getLocation())) {
13136     // Find a previous declaration that's not a definition.
13137     VarDecl *prev = var->getPreviousDecl();
13138     while (prev && prev->isThisDeclarationADefinition())
13139       prev = prev->getPreviousDecl();
13140 
13141     if (!prev) {
13142       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13143       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13144           << /* variable */ 0;
13145     }
13146   }
13147 
13148   // Cache the result of checking for constant initialization.
13149   Optional<bool> CacheHasConstInit;
13150   const Expr *CacheCulprit = nullptr;
13151   auto checkConstInit = [&]() mutable {
13152     if (!CacheHasConstInit)
13153       CacheHasConstInit = var->getInit()->isConstantInitializer(
13154             Context, var->getType()->isReferenceType(), &CacheCulprit);
13155     return *CacheHasConstInit;
13156   };
13157 
13158   if (var->getTLSKind() == VarDecl::TLS_Static) {
13159     if (var->getType().isDestructedType()) {
13160       // GNU C++98 edits for __thread, [basic.start.term]p3:
13161       //   The type of an object with thread storage duration shall not
13162       //   have a non-trivial destructor.
13163       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13164       if (getLangOpts().CPlusPlus11)
13165         Diag(var->getLocation(), diag::note_use_thread_local);
13166     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13167       if (!checkConstInit()) {
13168         // GNU C++98 edits for __thread, [basic.start.init]p4:
13169         //   An object of thread storage duration shall not require dynamic
13170         //   initialization.
13171         // FIXME: Need strict checking here.
13172         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13173           << CacheCulprit->getSourceRange();
13174         if (getLangOpts().CPlusPlus11)
13175           Diag(var->getLocation(), diag::note_use_thread_local);
13176       }
13177     }
13178   }
13179 
13180 
13181   if (!var->getType()->isStructureType() && var->hasInit() &&
13182       isa<InitListExpr>(var->getInit())) {
13183     const auto *ILE = cast<InitListExpr>(var->getInit());
13184     unsigned NumInits = ILE->getNumInits();
13185     if (NumInits > 2)
13186       for (unsigned I = 0; I < NumInits; ++I) {
13187         const auto *Init = ILE->getInit(I);
13188         if (!Init)
13189           break;
13190         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13191         if (!SL)
13192           break;
13193 
13194         unsigned NumConcat = SL->getNumConcatenated();
13195         // Diagnose missing comma in string array initialization.
13196         // Do not warn when all the elements in the initializer are concatenated
13197         // together. Do not warn for macros too.
13198         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13199           bool OnlyOneMissingComma = true;
13200           for (unsigned J = I + 1; J < NumInits; ++J) {
13201             const auto *Init = ILE->getInit(J);
13202             if (!Init)
13203               break;
13204             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13205             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13206               OnlyOneMissingComma = false;
13207               break;
13208             }
13209           }
13210 
13211           if (OnlyOneMissingComma) {
13212             SmallVector<FixItHint, 1> Hints;
13213             for (unsigned i = 0; i < NumConcat - 1; ++i)
13214               Hints.push_back(FixItHint::CreateInsertion(
13215                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13216 
13217             Diag(SL->getStrTokenLoc(1),
13218                  diag::warn_concatenated_literal_array_init)
13219                 << Hints;
13220             Diag(SL->getBeginLoc(),
13221                  diag::note_concatenated_string_literal_silence);
13222           }
13223           // In any case, stop now.
13224           break;
13225         }
13226       }
13227   }
13228 
13229 
13230   QualType type = var->getType();
13231 
13232   if (var->hasAttr<BlocksAttr>())
13233     getCurFunction()->addByrefBlockVar(var);
13234 
13235   Expr *Init = var->getInit();
13236   bool GlobalStorage = var->hasGlobalStorage();
13237   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13238   QualType baseType = Context.getBaseElementType(type);
13239   bool HasConstInit = true;
13240 
13241   // Check whether the initializer is sufficiently constant.
13242   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13243       !Init->isValueDependent() &&
13244       (GlobalStorage || var->isConstexpr() ||
13245        var->mightBeUsableInConstantExpressions(Context))) {
13246     // If this variable might have a constant initializer or might be usable in
13247     // constant expressions, check whether or not it actually is now.  We can't
13248     // do this lazily, because the result might depend on things that change
13249     // later, such as which constexpr functions happen to be defined.
13250     SmallVector<PartialDiagnosticAt, 8> Notes;
13251     if (!getLangOpts().CPlusPlus11) {
13252       // Prior to C++11, in contexts where a constant initializer is required,
13253       // the set of valid constant initializers is described by syntactic rules
13254       // in [expr.const]p2-6.
13255       // FIXME: Stricter checking for these rules would be useful for constinit /
13256       // -Wglobal-constructors.
13257       HasConstInit = checkConstInit();
13258 
13259       // Compute and cache the constant value, and remember that we have a
13260       // constant initializer.
13261       if (HasConstInit) {
13262         (void)var->checkForConstantInitialization(Notes);
13263         Notes.clear();
13264       } else if (CacheCulprit) {
13265         Notes.emplace_back(CacheCulprit->getExprLoc(),
13266                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13267         Notes.back().second << CacheCulprit->getSourceRange();
13268       }
13269     } else {
13270       // Evaluate the initializer to see if it's a constant initializer.
13271       HasConstInit = var->checkForConstantInitialization(Notes);
13272     }
13273 
13274     if (HasConstInit) {
13275       // FIXME: Consider replacing the initializer with a ConstantExpr.
13276     } else if (var->isConstexpr()) {
13277       SourceLocation DiagLoc = var->getLocation();
13278       // If the note doesn't add any useful information other than a source
13279       // location, fold it into the primary diagnostic.
13280       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13281                                    diag::note_invalid_subexpr_in_const_expr) {
13282         DiagLoc = Notes[0].first;
13283         Notes.clear();
13284       }
13285       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13286           << var << Init->getSourceRange();
13287       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13288         Diag(Notes[I].first, Notes[I].second);
13289     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13290       auto *Attr = var->getAttr<ConstInitAttr>();
13291       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13292           << Init->getSourceRange();
13293       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13294           << Attr->getRange() << Attr->isConstinit();
13295       for (auto &it : Notes)
13296         Diag(it.first, it.second);
13297     } else if (IsGlobal &&
13298                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13299                                            var->getLocation())) {
13300       // Warn about globals which don't have a constant initializer.  Don't
13301       // warn about globals with a non-trivial destructor because we already
13302       // warned about them.
13303       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13304       if (!(RD && !RD->hasTrivialDestructor())) {
13305         // checkConstInit() here permits trivial default initialization even in
13306         // C++11 onwards, where such an initializer is not a constant initializer
13307         // but nonetheless doesn't require a global constructor.
13308         if (!checkConstInit())
13309           Diag(var->getLocation(), diag::warn_global_constructor)
13310               << Init->getSourceRange();
13311       }
13312     }
13313   }
13314 
13315   // Apply section attributes and pragmas to global variables.
13316   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13317       !inTemplateInstantiation()) {
13318     PragmaStack<StringLiteral *> *Stack = nullptr;
13319     int SectionFlags = ASTContext::PSF_Read;
13320     if (var->getType().isConstQualified()) {
13321       if (HasConstInit)
13322         Stack = &ConstSegStack;
13323       else {
13324         Stack = &BSSSegStack;
13325         SectionFlags |= ASTContext::PSF_Write;
13326       }
13327     } else if (var->hasInit() && HasConstInit) {
13328       Stack = &DataSegStack;
13329       SectionFlags |= ASTContext::PSF_Write;
13330     } else {
13331       Stack = &BSSSegStack;
13332       SectionFlags |= ASTContext::PSF_Write;
13333     }
13334     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13335       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13336         SectionFlags |= ASTContext::PSF_Implicit;
13337       UnifySection(SA->getName(), SectionFlags, var);
13338     } else if (Stack->CurrentValue) {
13339       SectionFlags |= ASTContext::PSF_Implicit;
13340       auto SectionName = Stack->CurrentValue->getString();
13341       var->addAttr(SectionAttr::CreateImplicit(
13342           Context, SectionName, Stack->CurrentPragmaLocation,
13343           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13344       if (UnifySection(SectionName, SectionFlags, var))
13345         var->dropAttr<SectionAttr>();
13346     }
13347 
13348     // Apply the init_seg attribute if this has an initializer.  If the
13349     // initializer turns out to not be dynamic, we'll end up ignoring this
13350     // attribute.
13351     if (CurInitSeg && var->getInit())
13352       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13353                                                CurInitSegLoc,
13354                                                AttributeCommonInfo::AS_Pragma));
13355   }
13356 
13357   // All the following checks are C++ only.
13358   if (!getLangOpts().CPlusPlus) {
13359     // If this variable must be emitted, add it as an initializer for the
13360     // current module.
13361     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13362       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13363     return;
13364   }
13365 
13366   // Require the destructor.
13367   if (!type->isDependentType())
13368     if (const RecordType *recordType = baseType->getAs<RecordType>())
13369       FinalizeVarWithDestructor(var, recordType);
13370 
13371   // If this variable must be emitted, add it as an initializer for the current
13372   // module.
13373   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13374     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13375 
13376   // Build the bindings if this is a structured binding declaration.
13377   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13378     CheckCompleteDecompositionDeclaration(DD);
13379 }
13380 
13381 /// Check if VD needs to be dllexport/dllimport due to being in a
13382 /// dllexport/import function.
13383 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13384   assert(VD->isStaticLocal());
13385 
13386   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13387 
13388   // Find outermost function when VD is in lambda function.
13389   while (FD && !getDLLAttr(FD) &&
13390          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13391          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13392     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13393   }
13394 
13395   if (!FD)
13396     return;
13397 
13398   // Static locals inherit dll attributes from their function.
13399   if (Attr *A = getDLLAttr(FD)) {
13400     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13401     NewAttr->setInherited(true);
13402     VD->addAttr(NewAttr);
13403   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13404     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13405     NewAttr->setInherited(true);
13406     VD->addAttr(NewAttr);
13407 
13408     // Export this function to enforce exporting this static variable even
13409     // if it is not used in this compilation unit.
13410     if (!FD->hasAttr<DLLExportAttr>())
13411       FD->addAttr(NewAttr);
13412 
13413   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13414     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13415     NewAttr->setInherited(true);
13416     VD->addAttr(NewAttr);
13417   }
13418 }
13419 
13420 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13421 /// any semantic actions necessary after any initializer has been attached.
13422 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13423   // Note that we are no longer parsing the initializer for this declaration.
13424   ParsingInitForAutoVars.erase(ThisDecl);
13425 
13426   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13427   if (!VD)
13428     return;
13429 
13430   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13431   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13432       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13433     if (PragmaClangBSSSection.Valid)
13434       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13435           Context, PragmaClangBSSSection.SectionName,
13436           PragmaClangBSSSection.PragmaLocation,
13437           AttributeCommonInfo::AS_Pragma));
13438     if (PragmaClangDataSection.Valid)
13439       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13440           Context, PragmaClangDataSection.SectionName,
13441           PragmaClangDataSection.PragmaLocation,
13442           AttributeCommonInfo::AS_Pragma));
13443     if (PragmaClangRodataSection.Valid)
13444       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13445           Context, PragmaClangRodataSection.SectionName,
13446           PragmaClangRodataSection.PragmaLocation,
13447           AttributeCommonInfo::AS_Pragma));
13448     if (PragmaClangRelroSection.Valid)
13449       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13450           Context, PragmaClangRelroSection.SectionName,
13451           PragmaClangRelroSection.PragmaLocation,
13452           AttributeCommonInfo::AS_Pragma));
13453   }
13454 
13455   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13456     for (auto *BD : DD->bindings()) {
13457       FinalizeDeclaration(BD);
13458     }
13459   }
13460 
13461   checkAttributesAfterMerging(*this, *VD);
13462 
13463   // Perform TLS alignment check here after attributes attached to the variable
13464   // which may affect the alignment have been processed. Only perform the check
13465   // if the target has a maximum TLS alignment (zero means no constraints).
13466   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13467     // Protect the check so that it's not performed on dependent types and
13468     // dependent alignments (we can't determine the alignment in that case).
13469     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13470       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13471       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13472         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13473           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13474           << (unsigned)MaxAlignChars.getQuantity();
13475       }
13476     }
13477   }
13478 
13479   if (VD->isStaticLocal())
13480     CheckStaticLocalForDllExport(VD);
13481 
13482   // Perform check for initializers of device-side global variables.
13483   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13484   // 7.5). We must also apply the same checks to all __shared__
13485   // variables whether they are local or not. CUDA also allows
13486   // constant initializers for __constant__ and __device__ variables.
13487   if (getLangOpts().CUDA)
13488     checkAllowedCUDAInitializer(VD);
13489 
13490   // Grab the dllimport or dllexport attribute off of the VarDecl.
13491   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13492 
13493   // Imported static data members cannot be defined out-of-line.
13494   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13495     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13496         VD->isThisDeclarationADefinition()) {
13497       // We allow definitions of dllimport class template static data members
13498       // with a warning.
13499       CXXRecordDecl *Context =
13500         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13501       bool IsClassTemplateMember =
13502           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13503           Context->getDescribedClassTemplate();
13504 
13505       Diag(VD->getLocation(),
13506            IsClassTemplateMember
13507                ? diag::warn_attribute_dllimport_static_field_definition
13508                : diag::err_attribute_dllimport_static_field_definition);
13509       Diag(IA->getLocation(), diag::note_attribute);
13510       if (!IsClassTemplateMember)
13511         VD->setInvalidDecl();
13512     }
13513   }
13514 
13515   // dllimport/dllexport variables cannot be thread local, their TLS index
13516   // isn't exported with the variable.
13517   if (DLLAttr && VD->getTLSKind()) {
13518     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13519     if (F && getDLLAttr(F)) {
13520       assert(VD->isStaticLocal());
13521       // But if this is a static local in a dlimport/dllexport function, the
13522       // function will never be inlined, which means the var would never be
13523       // imported, so having it marked import/export is safe.
13524     } else {
13525       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13526                                                                     << DLLAttr;
13527       VD->setInvalidDecl();
13528     }
13529   }
13530 
13531   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13532     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13533       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13534           << Attr;
13535       VD->dropAttr<UsedAttr>();
13536     }
13537   }
13538   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13539     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13540       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13541           << Attr;
13542       VD->dropAttr<RetainAttr>();
13543     }
13544   }
13545 
13546   const DeclContext *DC = VD->getDeclContext();
13547   // If there's a #pragma GCC visibility in scope, and this isn't a class
13548   // member, set the visibility of this variable.
13549   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13550     AddPushedVisibilityAttribute(VD);
13551 
13552   // FIXME: Warn on unused var template partial specializations.
13553   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13554     MarkUnusedFileScopedDecl(VD);
13555 
13556   // Now we have parsed the initializer and can update the table of magic
13557   // tag values.
13558   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13559       !VD->getType()->isIntegralOrEnumerationType())
13560     return;
13561 
13562   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13563     const Expr *MagicValueExpr = VD->getInit();
13564     if (!MagicValueExpr) {
13565       continue;
13566     }
13567     Optional<llvm::APSInt> MagicValueInt;
13568     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13569       Diag(I->getRange().getBegin(),
13570            diag::err_type_tag_for_datatype_not_ice)
13571         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13572       continue;
13573     }
13574     if (MagicValueInt->getActiveBits() > 64) {
13575       Diag(I->getRange().getBegin(),
13576            diag::err_type_tag_for_datatype_too_large)
13577         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13578       continue;
13579     }
13580     uint64_t MagicValue = MagicValueInt->getZExtValue();
13581     RegisterTypeTagForDatatype(I->getArgumentKind(),
13582                                MagicValue,
13583                                I->getMatchingCType(),
13584                                I->getLayoutCompatible(),
13585                                I->getMustBeNull());
13586   }
13587 }
13588 
13589 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13590   auto *VD = dyn_cast<VarDecl>(DD);
13591   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13592 }
13593 
13594 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13595                                                    ArrayRef<Decl *> Group) {
13596   SmallVector<Decl*, 8> Decls;
13597 
13598   if (DS.isTypeSpecOwned())
13599     Decls.push_back(DS.getRepAsDecl());
13600 
13601   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13602   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13603   bool DiagnosedMultipleDecomps = false;
13604   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13605   bool DiagnosedNonDeducedAuto = false;
13606 
13607   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13608     if (Decl *D = Group[i]) {
13609       // For declarators, there are some additional syntactic-ish checks we need
13610       // to perform.
13611       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13612         if (!FirstDeclaratorInGroup)
13613           FirstDeclaratorInGroup = DD;
13614         if (!FirstDecompDeclaratorInGroup)
13615           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13616         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13617             !hasDeducedAuto(DD))
13618           FirstNonDeducedAutoInGroup = DD;
13619 
13620         if (FirstDeclaratorInGroup != DD) {
13621           // A decomposition declaration cannot be combined with any other
13622           // declaration in the same group.
13623           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13624             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13625                  diag::err_decomp_decl_not_alone)
13626                 << FirstDeclaratorInGroup->getSourceRange()
13627                 << DD->getSourceRange();
13628             DiagnosedMultipleDecomps = true;
13629           }
13630 
13631           // A declarator that uses 'auto' in any way other than to declare a
13632           // variable with a deduced type cannot be combined with any other
13633           // declarator in the same group.
13634           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13635             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13636                  diag::err_auto_non_deduced_not_alone)
13637                 << FirstNonDeducedAutoInGroup->getType()
13638                        ->hasAutoForTrailingReturnType()
13639                 << FirstDeclaratorInGroup->getSourceRange()
13640                 << DD->getSourceRange();
13641             DiagnosedNonDeducedAuto = true;
13642           }
13643         }
13644       }
13645 
13646       Decls.push_back(D);
13647     }
13648   }
13649 
13650   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13651     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13652       handleTagNumbering(Tag, S);
13653       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13654           getLangOpts().CPlusPlus)
13655         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13656     }
13657   }
13658 
13659   return BuildDeclaratorGroup(Decls);
13660 }
13661 
13662 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13663 /// group, performing any necessary semantic checking.
13664 Sema::DeclGroupPtrTy
13665 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13666   // C++14 [dcl.spec.auto]p7: (DR1347)
13667   //   If the type that replaces the placeholder type is not the same in each
13668   //   deduction, the program is ill-formed.
13669   if (Group.size() > 1) {
13670     QualType Deduced;
13671     VarDecl *DeducedDecl = nullptr;
13672     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13673       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13674       if (!D || D->isInvalidDecl())
13675         break;
13676       DeducedType *DT = D->getType()->getContainedDeducedType();
13677       if (!DT || DT->getDeducedType().isNull())
13678         continue;
13679       if (Deduced.isNull()) {
13680         Deduced = DT->getDeducedType();
13681         DeducedDecl = D;
13682       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13683         auto *AT = dyn_cast<AutoType>(DT);
13684         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13685                         diag::err_auto_different_deductions)
13686                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13687                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13688                    << D->getDeclName();
13689         if (DeducedDecl->hasInit())
13690           Dia << DeducedDecl->getInit()->getSourceRange();
13691         if (D->getInit())
13692           Dia << D->getInit()->getSourceRange();
13693         D->setInvalidDecl();
13694         break;
13695       }
13696     }
13697   }
13698 
13699   ActOnDocumentableDecls(Group);
13700 
13701   return DeclGroupPtrTy::make(
13702       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13703 }
13704 
13705 void Sema::ActOnDocumentableDecl(Decl *D) {
13706   ActOnDocumentableDecls(D);
13707 }
13708 
13709 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13710   // Don't parse the comment if Doxygen diagnostics are ignored.
13711   if (Group.empty() || !Group[0])
13712     return;
13713 
13714   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13715                       Group[0]->getLocation()) &&
13716       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13717                       Group[0]->getLocation()))
13718     return;
13719 
13720   if (Group.size() >= 2) {
13721     // This is a decl group.  Normally it will contain only declarations
13722     // produced from declarator list.  But in case we have any definitions or
13723     // additional declaration references:
13724     //   'typedef struct S {} S;'
13725     //   'typedef struct S *S;'
13726     //   'struct S *pS;'
13727     // FinalizeDeclaratorGroup adds these as separate declarations.
13728     Decl *MaybeTagDecl = Group[0];
13729     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13730       Group = Group.slice(1);
13731     }
13732   }
13733 
13734   // FIMXE: We assume every Decl in the group is in the same file.
13735   // This is false when preprocessor constructs the group from decls in
13736   // different files (e. g. macros or #include).
13737   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13738 }
13739 
13740 /// Common checks for a parameter-declaration that should apply to both function
13741 /// parameters and non-type template parameters.
13742 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13743   // Check that there are no default arguments inside the type of this
13744   // parameter.
13745   if (getLangOpts().CPlusPlus)
13746     CheckExtraCXXDefaultArguments(D);
13747 
13748   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13749   if (D.getCXXScopeSpec().isSet()) {
13750     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13751       << D.getCXXScopeSpec().getRange();
13752   }
13753 
13754   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13755   // simple identifier except [...irrelevant cases...].
13756   switch (D.getName().getKind()) {
13757   case UnqualifiedIdKind::IK_Identifier:
13758     break;
13759 
13760   case UnqualifiedIdKind::IK_OperatorFunctionId:
13761   case UnqualifiedIdKind::IK_ConversionFunctionId:
13762   case UnqualifiedIdKind::IK_LiteralOperatorId:
13763   case UnqualifiedIdKind::IK_ConstructorName:
13764   case UnqualifiedIdKind::IK_DestructorName:
13765   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13766   case UnqualifiedIdKind::IK_DeductionGuideName:
13767     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13768       << GetNameForDeclarator(D).getName();
13769     break;
13770 
13771   case UnqualifiedIdKind::IK_TemplateId:
13772   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13773     // GetNameForDeclarator would not produce a useful name in this case.
13774     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13775     break;
13776   }
13777 }
13778 
13779 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13780 /// to introduce parameters into function prototype scope.
13781 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13782   const DeclSpec &DS = D.getDeclSpec();
13783 
13784   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13785 
13786   // C++03 [dcl.stc]p2 also permits 'auto'.
13787   StorageClass SC = SC_None;
13788   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13789     SC = SC_Register;
13790     // In C++11, the 'register' storage class specifier is deprecated.
13791     // In C++17, it is not allowed, but we tolerate it as an extension.
13792     if (getLangOpts().CPlusPlus11) {
13793       Diag(DS.getStorageClassSpecLoc(),
13794            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13795                                      : diag::warn_deprecated_register)
13796         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13797     }
13798   } else if (getLangOpts().CPlusPlus &&
13799              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13800     SC = SC_Auto;
13801   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13802     Diag(DS.getStorageClassSpecLoc(),
13803          diag::err_invalid_storage_class_in_func_decl);
13804     D.getMutableDeclSpec().ClearStorageClassSpecs();
13805   }
13806 
13807   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13808     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13809       << DeclSpec::getSpecifierName(TSCS);
13810   if (DS.isInlineSpecified())
13811     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13812         << getLangOpts().CPlusPlus17;
13813   if (DS.hasConstexprSpecifier())
13814     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13815         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13816 
13817   DiagnoseFunctionSpecifiers(DS);
13818 
13819   CheckFunctionOrTemplateParamDeclarator(S, D);
13820 
13821   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13822   QualType parmDeclType = TInfo->getType();
13823 
13824   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13825   IdentifierInfo *II = D.getIdentifier();
13826   if (II) {
13827     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13828                    ForVisibleRedeclaration);
13829     LookupName(R, S);
13830     if (R.isSingleResult()) {
13831       NamedDecl *PrevDecl = R.getFoundDecl();
13832       if (PrevDecl->isTemplateParameter()) {
13833         // Maybe we will complain about the shadowed template parameter.
13834         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13835         // Just pretend that we didn't see the previous declaration.
13836         PrevDecl = nullptr;
13837       } else if (S->isDeclScope(PrevDecl)) {
13838         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13839         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13840 
13841         // Recover by removing the name
13842         II = nullptr;
13843         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13844         D.setInvalidType(true);
13845       }
13846     }
13847   }
13848 
13849   // Temporarily put parameter variables in the translation unit, not
13850   // the enclosing context.  This prevents them from accidentally
13851   // looking like class members in C++.
13852   ParmVarDecl *New =
13853       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13854                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13855 
13856   if (D.isInvalidType())
13857     New->setInvalidDecl();
13858 
13859   assert(S->isFunctionPrototypeScope());
13860   assert(S->getFunctionPrototypeDepth() >= 1);
13861   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13862                     S->getNextFunctionPrototypeIndex());
13863 
13864   // Add the parameter declaration into this scope.
13865   S->AddDecl(New);
13866   if (II)
13867     IdResolver.AddDecl(New);
13868 
13869   ProcessDeclAttributes(S, New, D);
13870 
13871   if (D.getDeclSpec().isModulePrivateSpecified())
13872     Diag(New->getLocation(), diag::err_module_private_local)
13873         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13874         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13875 
13876   if (New->hasAttr<BlocksAttr>()) {
13877     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13878   }
13879 
13880   if (getLangOpts().OpenCL)
13881     deduceOpenCLAddressSpace(New);
13882 
13883   return New;
13884 }
13885 
13886 /// Synthesizes a variable for a parameter arising from a
13887 /// typedef.
13888 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13889                                               SourceLocation Loc,
13890                                               QualType T) {
13891   /* FIXME: setting StartLoc == Loc.
13892      Would it be worth to modify callers so as to provide proper source
13893      location for the unnamed parameters, embedding the parameter's type? */
13894   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13895                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13896                                            SC_None, nullptr);
13897   Param->setImplicit();
13898   return Param;
13899 }
13900 
13901 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13902   // Don't diagnose unused-parameter errors in template instantiations; we
13903   // will already have done so in the template itself.
13904   if (inTemplateInstantiation())
13905     return;
13906 
13907   for (const ParmVarDecl *Parameter : Parameters) {
13908     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13909         !Parameter->hasAttr<UnusedAttr>()) {
13910       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13911         << Parameter->getDeclName();
13912     }
13913   }
13914 }
13915 
13916 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13917     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13918   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13919     return;
13920 
13921   // Warn if the return value is pass-by-value and larger than the specified
13922   // threshold.
13923   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13924     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13925     if (Size > LangOpts.NumLargeByValueCopy)
13926       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13927   }
13928 
13929   // Warn if any parameter is pass-by-value and larger than the specified
13930   // threshold.
13931   for (const ParmVarDecl *Parameter : Parameters) {
13932     QualType T = Parameter->getType();
13933     if (T->isDependentType() || !T.isPODType(Context))
13934       continue;
13935     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13936     if (Size > LangOpts.NumLargeByValueCopy)
13937       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13938           << Parameter << Size;
13939   }
13940 }
13941 
13942 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13943                                   SourceLocation NameLoc, IdentifierInfo *Name,
13944                                   QualType T, TypeSourceInfo *TSInfo,
13945                                   StorageClass SC) {
13946   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13947   if (getLangOpts().ObjCAutoRefCount &&
13948       T.getObjCLifetime() == Qualifiers::OCL_None &&
13949       T->isObjCLifetimeType()) {
13950 
13951     Qualifiers::ObjCLifetime lifetime;
13952 
13953     // Special cases for arrays:
13954     //   - if it's const, use __unsafe_unretained
13955     //   - otherwise, it's an error
13956     if (T->isArrayType()) {
13957       if (!T.isConstQualified()) {
13958         if (DelayedDiagnostics.shouldDelayDiagnostics())
13959           DelayedDiagnostics.add(
13960               sema::DelayedDiagnostic::makeForbiddenType(
13961               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13962         else
13963           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13964               << TSInfo->getTypeLoc().getSourceRange();
13965       }
13966       lifetime = Qualifiers::OCL_ExplicitNone;
13967     } else {
13968       lifetime = T->getObjCARCImplicitLifetime();
13969     }
13970     T = Context.getLifetimeQualifiedType(T, lifetime);
13971   }
13972 
13973   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13974                                          Context.getAdjustedParameterType(T),
13975                                          TSInfo, SC, nullptr);
13976 
13977   // Make a note if we created a new pack in the scope of a lambda, so that
13978   // we know that references to that pack must also be expanded within the
13979   // lambda scope.
13980   if (New->isParameterPack())
13981     if (auto *LSI = getEnclosingLambda())
13982       LSI->LocalPacks.push_back(New);
13983 
13984   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13985       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13986     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13987                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13988 
13989   // Parameters can not be abstract class types.
13990   // For record types, this is done by the AbstractClassUsageDiagnoser once
13991   // the class has been completely parsed.
13992   if (!CurContext->isRecord() &&
13993       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13994                              AbstractParamType))
13995     New->setInvalidDecl();
13996 
13997   // Parameter declarators cannot be interface types. All ObjC objects are
13998   // passed by reference.
13999   if (T->isObjCObjectType()) {
14000     SourceLocation TypeEndLoc =
14001         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14002     Diag(NameLoc,
14003          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14004       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14005     T = Context.getObjCObjectPointerType(T);
14006     New->setType(T);
14007   }
14008 
14009   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14010   // duration shall not be qualified by an address-space qualifier."
14011   // Since all parameters have automatic store duration, they can not have
14012   // an address space.
14013   if (T.getAddressSpace() != LangAS::Default &&
14014       // OpenCL allows function arguments declared to be an array of a type
14015       // to be qualified with an address space.
14016       !(getLangOpts().OpenCL &&
14017         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14018     Diag(NameLoc, diag::err_arg_with_address_space);
14019     New->setInvalidDecl();
14020   }
14021 
14022   // PPC MMA non-pointer types are not allowed as function argument types.
14023   if (Context.getTargetInfo().getTriple().isPPC64() &&
14024       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14025     New->setInvalidDecl();
14026   }
14027 
14028   return New;
14029 }
14030 
14031 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14032                                            SourceLocation LocAfterDecls) {
14033   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14034 
14035   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14036   // for a K&R function.
14037   if (!FTI.hasPrototype) {
14038     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14039       --i;
14040       if (FTI.Params[i].Param == nullptr) {
14041         SmallString<256> Code;
14042         llvm::raw_svector_ostream(Code)
14043             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14044         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14045             << FTI.Params[i].Ident
14046             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14047 
14048         // Implicitly declare the argument as type 'int' for lack of a better
14049         // type.
14050         AttributeFactory attrs;
14051         DeclSpec DS(attrs);
14052         const char* PrevSpec; // unused
14053         unsigned DiagID; // unused
14054         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14055                            DiagID, Context.getPrintingPolicy());
14056         // Use the identifier location for the type source range.
14057         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14058         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14059         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14060         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14061         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14062       }
14063     }
14064   }
14065 }
14066 
14067 Decl *
14068 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14069                               MultiTemplateParamsArg TemplateParameterLists,
14070                               SkipBodyInfo *SkipBody) {
14071   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14072   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14073   Scope *ParentScope = FnBodyScope->getParent();
14074 
14075   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14076   // we define a non-templated function definition, we will create a declaration
14077   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14078   // The base function declaration will have the equivalent of an `omp declare
14079   // variant` annotation which specifies the mangled definition as a
14080   // specialization function under the OpenMP context defined as part of the
14081   // `omp begin declare variant`.
14082   SmallVector<FunctionDecl *, 4> Bases;
14083   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14084     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14085         ParentScope, D, TemplateParameterLists, Bases);
14086 
14087   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14088   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14089   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14090 
14091   if (!Bases.empty())
14092     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14093 
14094   return Dcl;
14095 }
14096 
14097 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14098   Consumer.HandleInlineFunctionDefinition(D);
14099 }
14100 
14101 static bool
14102 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14103                                 const FunctionDecl *&PossiblePrototype) {
14104   // Don't warn about invalid declarations.
14105   if (FD->isInvalidDecl())
14106     return false;
14107 
14108   // Or declarations that aren't global.
14109   if (!FD->isGlobal())
14110     return false;
14111 
14112   // Don't warn about C++ member functions.
14113   if (isa<CXXMethodDecl>(FD))
14114     return false;
14115 
14116   // Don't warn about 'main'.
14117   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14118     if (IdentifierInfo *II = FD->getIdentifier())
14119       if (II->isStr("main") || II->isStr("efi_main"))
14120         return false;
14121 
14122   // Don't warn about inline functions.
14123   if (FD->isInlined())
14124     return false;
14125 
14126   // Don't warn about function templates.
14127   if (FD->getDescribedFunctionTemplate())
14128     return false;
14129 
14130   // Don't warn about function template specializations.
14131   if (FD->isFunctionTemplateSpecialization())
14132     return false;
14133 
14134   // Don't warn for OpenCL kernels.
14135   if (FD->hasAttr<OpenCLKernelAttr>())
14136     return false;
14137 
14138   // Don't warn on explicitly deleted functions.
14139   if (FD->isDeleted())
14140     return false;
14141 
14142   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14143        Prev; Prev = Prev->getPreviousDecl()) {
14144     // Ignore any declarations that occur in function or method
14145     // scope, because they aren't visible from the header.
14146     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14147       continue;
14148 
14149     PossiblePrototype = Prev;
14150     return Prev->getType()->isFunctionNoProtoType();
14151   }
14152 
14153   return true;
14154 }
14155 
14156 void
14157 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14158                                    const FunctionDecl *EffectiveDefinition,
14159                                    SkipBodyInfo *SkipBody) {
14160   const FunctionDecl *Definition = EffectiveDefinition;
14161   if (!Definition &&
14162       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14163     return;
14164 
14165   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14166     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14167       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14168         // A merged copy of the same function, instantiated as a member of
14169         // the same class, is OK.
14170         if (declaresSameEntity(OrigFD, OrigDef) &&
14171             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14172                                cast<Decl>(FD->getLexicalDeclContext())))
14173           return;
14174       }
14175     }
14176   }
14177 
14178   if (canRedefineFunction(Definition, getLangOpts()))
14179     return;
14180 
14181   // Don't emit an error when this is redefinition of a typo-corrected
14182   // definition.
14183   if (TypoCorrectedFunctionDefinitions.count(Definition))
14184     return;
14185 
14186   // If we don't have a visible definition of the function, and it's inline or
14187   // a template, skip the new definition.
14188   if (SkipBody && !hasVisibleDefinition(Definition) &&
14189       (Definition->getFormalLinkage() == InternalLinkage ||
14190        Definition->isInlined() ||
14191        Definition->getDescribedFunctionTemplate() ||
14192        Definition->getNumTemplateParameterLists())) {
14193     SkipBody->ShouldSkip = true;
14194     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14195     if (auto *TD = Definition->getDescribedFunctionTemplate())
14196       makeMergedDefinitionVisible(TD);
14197     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14198     return;
14199   }
14200 
14201   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14202       Definition->getStorageClass() == SC_Extern)
14203     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14204         << FD << getLangOpts().CPlusPlus;
14205   else
14206     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14207 
14208   Diag(Definition->getLocation(), diag::note_previous_definition);
14209   FD->setInvalidDecl();
14210 }
14211 
14212 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14213                                    Sema &S) {
14214   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14215 
14216   LambdaScopeInfo *LSI = S.PushLambdaScope();
14217   LSI->CallOperator = CallOperator;
14218   LSI->Lambda = LambdaClass;
14219   LSI->ReturnType = CallOperator->getReturnType();
14220   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14221 
14222   if (LCD == LCD_None)
14223     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14224   else if (LCD == LCD_ByCopy)
14225     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14226   else if (LCD == LCD_ByRef)
14227     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14228   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14229 
14230   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14231   LSI->Mutable = !CallOperator->isConst();
14232 
14233   // Add the captures to the LSI so they can be noted as already
14234   // captured within tryCaptureVar.
14235   auto I = LambdaClass->field_begin();
14236   for (const auto &C : LambdaClass->captures()) {
14237     if (C.capturesVariable()) {
14238       VarDecl *VD = C.getCapturedVar();
14239       if (VD->isInitCapture())
14240         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14241       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14242       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14243           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14244           /*EllipsisLoc*/C.isPackExpansion()
14245                          ? C.getEllipsisLoc() : SourceLocation(),
14246           I->getType(), /*Invalid*/false);
14247 
14248     } else if (C.capturesThis()) {
14249       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14250                           C.getCaptureKind() == LCK_StarThis);
14251     } else {
14252       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14253                              I->getType());
14254     }
14255     ++I;
14256   }
14257 }
14258 
14259 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14260                                     SkipBodyInfo *SkipBody) {
14261   if (!D) {
14262     // Parsing the function declaration failed in some way. Push on a fake scope
14263     // anyway so we can try to parse the function body.
14264     PushFunctionScope();
14265     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14266     return D;
14267   }
14268 
14269   FunctionDecl *FD = nullptr;
14270 
14271   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14272     FD = FunTmpl->getTemplatedDecl();
14273   else
14274     FD = cast<FunctionDecl>(D);
14275 
14276   // Do not push if it is a lambda because one is already pushed when building
14277   // the lambda in ActOnStartOfLambdaDefinition().
14278   if (!isLambdaCallOperator(FD))
14279     PushExpressionEvaluationContext(
14280         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14281                           : ExprEvalContexts.back().Context);
14282 
14283   // Check for defining attributes before the check for redefinition.
14284   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14285     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14286     FD->dropAttr<AliasAttr>();
14287     FD->setInvalidDecl();
14288   }
14289   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14290     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14291     FD->dropAttr<IFuncAttr>();
14292     FD->setInvalidDecl();
14293   }
14294 
14295   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14296     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14297         Ctor->isDefaultConstructor() &&
14298         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14299       // If this is an MS ABI dllexport default constructor, instantiate any
14300       // default arguments.
14301       InstantiateDefaultCtorDefaultArgs(Ctor);
14302     }
14303   }
14304 
14305   // See if this is a redefinition. If 'will have body' (or similar) is already
14306   // set, then these checks were already performed when it was set.
14307   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14308       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14309     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14310 
14311     // If we're skipping the body, we're done. Don't enter the scope.
14312     if (SkipBody && SkipBody->ShouldSkip)
14313       return D;
14314   }
14315 
14316   // Mark this function as "will have a body eventually".  This lets users to
14317   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14318   // this function.
14319   FD->setWillHaveBody();
14320 
14321   // If we are instantiating a generic lambda call operator, push
14322   // a LambdaScopeInfo onto the function stack.  But use the information
14323   // that's already been calculated (ActOnLambdaExpr) to prime the current
14324   // LambdaScopeInfo.
14325   // When the template operator is being specialized, the LambdaScopeInfo,
14326   // has to be properly restored so that tryCaptureVariable doesn't try
14327   // and capture any new variables. In addition when calculating potential
14328   // captures during transformation of nested lambdas, it is necessary to
14329   // have the LSI properly restored.
14330   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14331     assert(inTemplateInstantiation() &&
14332            "There should be an active template instantiation on the stack "
14333            "when instantiating a generic lambda!");
14334     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14335   } else {
14336     // Enter a new function scope
14337     PushFunctionScope();
14338   }
14339 
14340   // Builtin functions cannot be defined.
14341   if (unsigned BuiltinID = FD->getBuiltinID()) {
14342     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14343         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14344       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14345       FD->setInvalidDecl();
14346     }
14347   }
14348 
14349   // The return type of a function definition must be complete
14350   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14351   QualType ResultType = FD->getReturnType();
14352   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14353       !FD->isInvalidDecl() &&
14354       RequireCompleteType(FD->getLocation(), ResultType,
14355                           diag::err_func_def_incomplete_result))
14356     FD->setInvalidDecl();
14357 
14358   if (FnBodyScope)
14359     PushDeclContext(FnBodyScope, FD);
14360 
14361   // Check the validity of our function parameters
14362   CheckParmsForFunctionDef(FD->parameters(),
14363                            /*CheckParameterNames=*/true);
14364 
14365   // Add non-parameter declarations already in the function to the current
14366   // scope.
14367   if (FnBodyScope) {
14368     for (Decl *NPD : FD->decls()) {
14369       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14370       if (!NonParmDecl)
14371         continue;
14372       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14373              "parameters should not be in newly created FD yet");
14374 
14375       // If the decl has a name, make it accessible in the current scope.
14376       if (NonParmDecl->getDeclName())
14377         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14378 
14379       // Similarly, dive into enums and fish their constants out, making them
14380       // accessible in this scope.
14381       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14382         for (auto *EI : ED->enumerators())
14383           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14384       }
14385     }
14386   }
14387 
14388   // Introduce our parameters into the function scope
14389   for (auto Param : FD->parameters()) {
14390     Param->setOwningFunction(FD);
14391 
14392     // If this has an identifier, add it to the scope stack.
14393     if (Param->getIdentifier() && FnBodyScope) {
14394       CheckShadow(FnBodyScope, Param);
14395 
14396       PushOnScopeChains(Param, FnBodyScope);
14397     }
14398   }
14399 
14400   // Ensure that the function's exception specification is instantiated.
14401   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14402     ResolveExceptionSpec(D->getLocation(), FPT);
14403 
14404   // dllimport cannot be applied to non-inline function definitions.
14405   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14406       !FD->isTemplateInstantiation()) {
14407     assert(!FD->hasAttr<DLLExportAttr>());
14408     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14409     FD->setInvalidDecl();
14410     return D;
14411   }
14412   // We want to attach documentation to original Decl (which might be
14413   // a function template).
14414   ActOnDocumentableDecl(D);
14415   if (getCurLexicalContext()->isObjCContainer() &&
14416       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14417       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14418     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14419 
14420   return D;
14421 }
14422 
14423 /// Given the set of return statements within a function body,
14424 /// compute the variables that are subject to the named return value
14425 /// optimization.
14426 ///
14427 /// Each of the variables that is subject to the named return value
14428 /// optimization will be marked as NRVO variables in the AST, and any
14429 /// return statement that has a marked NRVO variable as its NRVO candidate can
14430 /// use the named return value optimization.
14431 ///
14432 /// This function applies a very simplistic algorithm for NRVO: if every return
14433 /// statement in the scope of a variable has the same NRVO candidate, that
14434 /// candidate is an NRVO variable.
14435 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14436   ReturnStmt **Returns = Scope->Returns.data();
14437 
14438   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14439     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14440       if (!NRVOCandidate->isNRVOVariable())
14441         Returns[I]->setNRVOCandidate(nullptr);
14442     }
14443   }
14444 }
14445 
14446 bool Sema::canDelayFunctionBody(const Declarator &D) {
14447   // We can't delay parsing the body of a constexpr function template (yet).
14448   if (D.getDeclSpec().hasConstexprSpecifier())
14449     return false;
14450 
14451   // We can't delay parsing the body of a function template with a deduced
14452   // return type (yet).
14453   if (D.getDeclSpec().hasAutoTypeSpec()) {
14454     // If the placeholder introduces a non-deduced trailing return type,
14455     // we can still delay parsing it.
14456     if (D.getNumTypeObjects()) {
14457       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14458       if (Outer.Kind == DeclaratorChunk::Function &&
14459           Outer.Fun.hasTrailingReturnType()) {
14460         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14461         return Ty.isNull() || !Ty->isUndeducedType();
14462       }
14463     }
14464     return false;
14465   }
14466 
14467   return true;
14468 }
14469 
14470 bool Sema::canSkipFunctionBody(Decl *D) {
14471   // We cannot skip the body of a function (or function template) which is
14472   // constexpr, since we may need to evaluate its body in order to parse the
14473   // rest of the file.
14474   // We cannot skip the body of a function with an undeduced return type,
14475   // because any callers of that function need to know the type.
14476   if (const FunctionDecl *FD = D->getAsFunction()) {
14477     if (FD->isConstexpr())
14478       return false;
14479     // We can't simply call Type::isUndeducedType here, because inside template
14480     // auto can be deduced to a dependent type, which is not considered
14481     // "undeduced".
14482     if (FD->getReturnType()->getContainedDeducedType())
14483       return false;
14484   }
14485   return Consumer.shouldSkipFunctionBody(D);
14486 }
14487 
14488 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14489   if (!Decl)
14490     return nullptr;
14491   if (FunctionDecl *FD = Decl->getAsFunction())
14492     FD->setHasSkippedBody();
14493   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14494     MD->setHasSkippedBody();
14495   return Decl;
14496 }
14497 
14498 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14499   return ActOnFinishFunctionBody(D, BodyArg, false);
14500 }
14501 
14502 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14503 /// body.
14504 class ExitFunctionBodyRAII {
14505 public:
14506   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14507   ~ExitFunctionBodyRAII() {
14508     if (!IsLambda)
14509       S.PopExpressionEvaluationContext();
14510   }
14511 
14512 private:
14513   Sema &S;
14514   bool IsLambda = false;
14515 };
14516 
14517 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14518   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14519 
14520   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14521     if (EscapeInfo.count(BD))
14522       return EscapeInfo[BD];
14523 
14524     bool R = false;
14525     const BlockDecl *CurBD = BD;
14526 
14527     do {
14528       R = !CurBD->doesNotEscape();
14529       if (R)
14530         break;
14531       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14532     } while (CurBD);
14533 
14534     return EscapeInfo[BD] = R;
14535   };
14536 
14537   // If the location where 'self' is implicitly retained is inside a escaping
14538   // block, emit a diagnostic.
14539   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14540        S.ImplicitlyRetainedSelfLocs)
14541     if (IsOrNestedInEscapingBlock(P.second))
14542       S.Diag(P.first, diag::warn_implicitly_retains_self)
14543           << FixItHint::CreateInsertion(P.first, "self->");
14544 }
14545 
14546 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14547                                     bool IsInstantiation) {
14548   FunctionScopeInfo *FSI = getCurFunction();
14549   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14550 
14551   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14552     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14553 
14554   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14555   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14556 
14557   if (getLangOpts().Coroutines && FSI->isCoroutine())
14558     CheckCompletedCoroutineBody(FD, Body);
14559 
14560   {
14561     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14562     // one is already popped when finishing the lambda in BuildLambdaExpr().
14563     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14564     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14565 
14566     if (FD) {
14567       FD->setBody(Body);
14568       FD->setWillHaveBody(false);
14569 
14570       if (getLangOpts().CPlusPlus14) {
14571         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14572             FD->getReturnType()->isUndeducedType()) {
14573           // If the function has a deduced result type but contains no 'return'
14574           // statements, the result type as written must be exactly 'auto', and
14575           // the deduced result type is 'void'.
14576           if (!FD->getReturnType()->getAs<AutoType>()) {
14577             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14578                 << FD->getReturnType();
14579             FD->setInvalidDecl();
14580           } else {
14581             // Substitute 'void' for the 'auto' in the type.
14582             TypeLoc ResultType = getReturnTypeLoc(FD);
14583             Context.adjustDeducedFunctionResultType(
14584                 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14585           }
14586         }
14587       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14588         // In C++11, we don't use 'auto' deduction rules for lambda call
14589         // operators because we don't support return type deduction.
14590         auto *LSI = getCurLambda();
14591         if (LSI->HasImplicitReturnType) {
14592           deduceClosureReturnType(*LSI);
14593 
14594           // C++11 [expr.prim.lambda]p4:
14595           //   [...] if there are no return statements in the compound-statement
14596           //   [the deduced type is] the type void
14597           QualType RetType =
14598               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14599 
14600           // Update the return type to the deduced type.
14601           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14602           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14603                                               Proto->getExtProtoInfo()));
14604         }
14605       }
14606 
14607       // If the function implicitly returns zero (like 'main') or is naked,
14608       // don't complain about missing return statements.
14609       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14610         WP.disableCheckFallThrough();
14611 
14612       // MSVC permits the use of pure specifier (=0) on function definition,
14613       // defined at class scope, warn about this non-standard construct.
14614       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14615         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14616 
14617       if (!FD->isInvalidDecl()) {
14618         // Don't diagnose unused parameters of defaulted or deleted functions.
14619         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14620           DiagnoseUnusedParameters(FD->parameters());
14621         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14622                                                FD->getReturnType(), FD);
14623 
14624         // If this is a structor, we need a vtable.
14625         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14626           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14627         else if (CXXDestructorDecl *Destructor =
14628                      dyn_cast<CXXDestructorDecl>(FD))
14629           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14630 
14631         // Try to apply the named return value optimization. We have to check
14632         // if we can do this here because lambdas keep return statements around
14633         // to deduce an implicit return type.
14634         if (FD->getReturnType()->isRecordType() &&
14635             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14636           computeNRVO(Body, FSI);
14637       }
14638 
14639       // GNU warning -Wmissing-prototypes:
14640       //   Warn if a global function is defined without a previous
14641       //   prototype declaration. This warning is issued even if the
14642       //   definition itself provides a prototype. The aim is to detect
14643       //   global functions that fail to be declared in header files.
14644       const FunctionDecl *PossiblePrototype = nullptr;
14645       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14646         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14647 
14648         if (PossiblePrototype) {
14649           // We found a declaration that is not a prototype,
14650           // but that could be a zero-parameter prototype
14651           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14652             TypeLoc TL = TI->getTypeLoc();
14653             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14654               Diag(PossiblePrototype->getLocation(),
14655                    diag::note_declaration_not_a_prototype)
14656                   << (FD->getNumParams() != 0)
14657                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14658                                                     FTL.getRParenLoc(), "void")
14659                                               : FixItHint{});
14660           }
14661         } else {
14662           // Returns true if the token beginning at this Loc is `const`.
14663           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14664                                   const LangOptions &LangOpts) {
14665             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14666             if (LocInfo.first.isInvalid())
14667               return false;
14668 
14669             bool Invalid = false;
14670             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14671             if (Invalid)
14672               return false;
14673 
14674             if (LocInfo.second > Buffer.size())
14675               return false;
14676 
14677             const char *LexStart = Buffer.data() + LocInfo.second;
14678             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14679 
14680             return StartTok.consume_front("const") &&
14681                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14682                     StartTok.startswith("/*") || StartTok.startswith("//"));
14683           };
14684 
14685           auto findBeginLoc = [&]() {
14686             // If the return type has `const` qualifier, we want to insert
14687             // `static` before `const` (and not before the typename).
14688             if ((FD->getReturnType()->isAnyPointerType() &&
14689                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14690                 FD->getReturnType().isConstQualified()) {
14691               // But only do this if we can determine where the `const` is.
14692 
14693               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14694                                getLangOpts()))
14695 
14696                 return FD->getBeginLoc();
14697             }
14698             return FD->getTypeSpecStartLoc();
14699           };
14700           Diag(FD->getTypeSpecStartLoc(),
14701                diag::note_static_for_internal_linkage)
14702               << /* function */ 1
14703               << (FD->getStorageClass() == SC_None
14704                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14705                       : FixItHint{});
14706         }
14707 
14708         // GNU warning -Wstrict-prototypes
14709         //   Warn if K&R function is defined without a previous declaration.
14710         //   This warning is issued only if the definition itself does not
14711         //   provide a prototype. Only K&R definitions do not provide a
14712         //   prototype.
14713         if (!FD->hasWrittenPrototype()) {
14714           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14715           TypeLoc TL = TI->getTypeLoc();
14716           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14717           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14718         }
14719       }
14720 
14721       // Warn on CPUDispatch with an actual body.
14722       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14723         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14724           if (!CmpndBody->body_empty())
14725             Diag(CmpndBody->body_front()->getBeginLoc(),
14726                  diag::warn_dispatch_body_ignored);
14727 
14728       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14729         const CXXMethodDecl *KeyFunction;
14730         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14731             MD->isVirtual() &&
14732             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14733             MD == KeyFunction->getCanonicalDecl()) {
14734           // Update the key-function state if necessary for this ABI.
14735           if (FD->isInlined() &&
14736               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14737             Context.setNonKeyFunction(MD);
14738 
14739             // If the newly-chosen key function is already defined, then we
14740             // need to mark the vtable as used retroactively.
14741             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14742             const FunctionDecl *Definition;
14743             if (KeyFunction && KeyFunction->isDefined(Definition))
14744               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14745           } else {
14746             // We just defined they key function; mark the vtable as used.
14747             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14748           }
14749         }
14750       }
14751 
14752       assert(
14753           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14754           "Function parsing confused");
14755     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14756       assert(MD == getCurMethodDecl() && "Method parsing confused");
14757       MD->setBody(Body);
14758       if (!MD->isInvalidDecl()) {
14759         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14760                                                MD->getReturnType(), MD);
14761 
14762         if (Body)
14763           computeNRVO(Body, FSI);
14764       }
14765       if (FSI->ObjCShouldCallSuper) {
14766         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14767             << MD->getSelector().getAsString();
14768         FSI->ObjCShouldCallSuper = false;
14769       }
14770       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14771         const ObjCMethodDecl *InitMethod = nullptr;
14772         bool isDesignated =
14773             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14774         assert(isDesignated && InitMethod);
14775         (void)isDesignated;
14776 
14777         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14778           auto IFace = MD->getClassInterface();
14779           if (!IFace)
14780             return false;
14781           auto SuperD = IFace->getSuperClass();
14782           if (!SuperD)
14783             return false;
14784           return SuperD->getIdentifier() ==
14785                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14786         };
14787         // Don't issue this warning for unavailable inits or direct subclasses
14788         // of NSObject.
14789         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14790           Diag(MD->getLocation(),
14791                diag::warn_objc_designated_init_missing_super_call);
14792           Diag(InitMethod->getLocation(),
14793                diag::note_objc_designated_init_marked_here);
14794         }
14795         FSI->ObjCWarnForNoDesignatedInitChain = false;
14796       }
14797       if (FSI->ObjCWarnForNoInitDelegation) {
14798         // Don't issue this warning for unavaialable inits.
14799         if (!MD->isUnavailable())
14800           Diag(MD->getLocation(),
14801                diag::warn_objc_secondary_init_missing_init_call);
14802         FSI->ObjCWarnForNoInitDelegation = false;
14803       }
14804 
14805       diagnoseImplicitlyRetainedSelf(*this);
14806     } else {
14807       // Parsing the function declaration failed in some way. Pop the fake scope
14808       // we pushed on.
14809       PopFunctionScopeInfo(ActivePolicy, dcl);
14810       return nullptr;
14811     }
14812 
14813     if (Body && FSI->HasPotentialAvailabilityViolations)
14814       DiagnoseUnguardedAvailabilityViolations(dcl);
14815 
14816     assert(!FSI->ObjCShouldCallSuper &&
14817            "This should only be set for ObjC methods, which should have been "
14818            "handled in the block above.");
14819 
14820     // Verify and clean out per-function state.
14821     if (Body && (!FD || !FD->isDefaulted())) {
14822       // C++ constructors that have function-try-blocks can't have return
14823       // statements in the handlers of that block. (C++ [except.handle]p14)
14824       // Verify this.
14825       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14826         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14827 
14828       // Verify that gotos and switch cases don't jump into scopes illegally.
14829       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14830         DiagnoseInvalidJumps(Body);
14831 
14832       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14833         if (!Destructor->getParent()->isDependentType())
14834           CheckDestructor(Destructor);
14835 
14836         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14837                                                Destructor->getParent());
14838       }
14839 
14840       // If any errors have occurred, clear out any temporaries that may have
14841       // been leftover. This ensures that these temporaries won't be picked up
14842       // for deletion in some later function.
14843       if (hasUncompilableErrorOccurred() ||
14844           getDiagnostics().getSuppressAllDiagnostics()) {
14845         DiscardCleanupsInEvaluationContext();
14846       }
14847       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14848         // Since the body is valid, issue any analysis-based warnings that are
14849         // enabled.
14850         ActivePolicy = &WP;
14851       }
14852 
14853       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14854           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14855         FD->setInvalidDecl();
14856 
14857       if (FD && FD->hasAttr<NakedAttr>()) {
14858         for (const Stmt *S : Body->children()) {
14859           // Allow local register variables without initializer as they don't
14860           // require prologue.
14861           bool RegisterVariables = false;
14862           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14863             for (const auto *Decl : DS->decls()) {
14864               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14865                 RegisterVariables =
14866                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14867                 if (!RegisterVariables)
14868                   break;
14869               }
14870             }
14871           }
14872           if (RegisterVariables)
14873             continue;
14874           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14875             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14876             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14877             FD->setInvalidDecl();
14878             break;
14879           }
14880         }
14881       }
14882 
14883       assert(ExprCleanupObjects.size() ==
14884                  ExprEvalContexts.back().NumCleanupObjects &&
14885              "Leftover temporaries in function");
14886       assert(!Cleanup.exprNeedsCleanups() &&
14887              "Unaccounted cleanups in function");
14888       assert(MaybeODRUseExprs.empty() &&
14889              "Leftover expressions for odr-use checking");
14890     }
14891   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14892     // the declaration context below. Otherwise, we're unable to transform
14893     // 'this' expressions when transforming immediate context functions.
14894 
14895   if (!IsInstantiation)
14896     PopDeclContext();
14897 
14898   PopFunctionScopeInfo(ActivePolicy, dcl);
14899   // If any errors have occurred, clear out any temporaries that may have
14900   // been leftover. This ensures that these temporaries won't be picked up for
14901   // deletion in some later function.
14902   if (hasUncompilableErrorOccurred()) {
14903     DiscardCleanupsInEvaluationContext();
14904   }
14905 
14906   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
14907                                   !LangOpts.OMPTargetTriples.empty())) ||
14908              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14909     auto ES = getEmissionStatus(FD);
14910     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14911         ES == Sema::FunctionEmissionStatus::Unknown)
14912       DeclsToCheckForDeferredDiags.insert(FD);
14913   }
14914 
14915   if (FD && !FD->isDeleted())
14916     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
14917 
14918   return dcl;
14919 }
14920 
14921 /// When we finish delayed parsing of an attribute, we must attach it to the
14922 /// relevant Decl.
14923 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14924                                        ParsedAttributes &Attrs) {
14925   // Always attach attributes to the underlying decl.
14926   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14927     D = TD->getTemplatedDecl();
14928   ProcessDeclAttributeList(S, D, Attrs);
14929 
14930   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14931     if (Method->isStatic())
14932       checkThisInStaticMemberFunctionAttributes(Method);
14933 }
14934 
14935 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14936 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14937 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14938                                           IdentifierInfo &II, Scope *S) {
14939   // Find the scope in which the identifier is injected and the corresponding
14940   // DeclContext.
14941   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14942   // In that case, we inject the declaration into the translation unit scope
14943   // instead.
14944   Scope *BlockScope = S;
14945   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14946     BlockScope = BlockScope->getParent();
14947 
14948   Scope *ContextScope = BlockScope;
14949   while (!ContextScope->getEntity())
14950     ContextScope = ContextScope->getParent();
14951   ContextRAII SavedContext(*this, ContextScope->getEntity());
14952 
14953   // Before we produce a declaration for an implicitly defined
14954   // function, see whether there was a locally-scoped declaration of
14955   // this name as a function or variable. If so, use that
14956   // (non-visible) declaration, and complain about it.
14957   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14958   if (ExternCPrev) {
14959     // We still need to inject the function into the enclosing block scope so
14960     // that later (non-call) uses can see it.
14961     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14962 
14963     // C89 footnote 38:
14964     //   If in fact it is not defined as having type "function returning int",
14965     //   the behavior is undefined.
14966     if (!isa<FunctionDecl>(ExternCPrev) ||
14967         !Context.typesAreCompatible(
14968             cast<FunctionDecl>(ExternCPrev)->getType(),
14969             Context.getFunctionNoProtoType(Context.IntTy))) {
14970       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14971           << ExternCPrev << !getLangOpts().C99;
14972       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14973       return ExternCPrev;
14974     }
14975   }
14976 
14977   // Extension in C99.  Legal in C90, but warn about it.
14978   unsigned diag_id;
14979   if (II.getName().startswith("__builtin_"))
14980     diag_id = diag::warn_builtin_unknown;
14981   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14982   else if (getLangOpts().OpenCL)
14983     diag_id = diag::err_opencl_implicit_function_decl;
14984   else if (getLangOpts().C99)
14985     diag_id = diag::ext_implicit_function_decl;
14986   else
14987     diag_id = diag::warn_implicit_function_decl;
14988   Diag(Loc, diag_id) << &II;
14989 
14990   // If we found a prior declaration of this function, don't bother building
14991   // another one. We've already pushed that one into scope, so there's nothing
14992   // more to do.
14993   if (ExternCPrev)
14994     return ExternCPrev;
14995 
14996   // Because typo correction is expensive, only do it if the implicit
14997   // function declaration is going to be treated as an error.
14998   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14999     TypoCorrection Corrected;
15000     DeclFilterCCC<FunctionDecl> CCC{};
15001     if (S && (Corrected =
15002                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15003                               S, nullptr, CCC, CTK_NonError)))
15004       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15005                    /*ErrorRecovery*/false);
15006   }
15007 
15008   // Set a Declarator for the implicit definition: int foo();
15009   const char *Dummy;
15010   AttributeFactory attrFactory;
15011   DeclSpec DS(attrFactory);
15012   unsigned DiagID;
15013   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15014                                   Context.getPrintingPolicy());
15015   (void)Error; // Silence warning.
15016   assert(!Error && "Error setting up implicit decl!");
15017   SourceLocation NoLoc;
15018   Declarator D(DS, DeclaratorContext::Block);
15019   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15020                                              /*IsAmbiguous=*/false,
15021                                              /*LParenLoc=*/NoLoc,
15022                                              /*Params=*/nullptr,
15023                                              /*NumParams=*/0,
15024                                              /*EllipsisLoc=*/NoLoc,
15025                                              /*RParenLoc=*/NoLoc,
15026                                              /*RefQualifierIsLvalueRef=*/true,
15027                                              /*RefQualifierLoc=*/NoLoc,
15028                                              /*MutableLoc=*/NoLoc, EST_None,
15029                                              /*ESpecRange=*/SourceRange(),
15030                                              /*Exceptions=*/nullptr,
15031                                              /*ExceptionRanges=*/nullptr,
15032                                              /*NumExceptions=*/0,
15033                                              /*NoexceptExpr=*/nullptr,
15034                                              /*ExceptionSpecTokens=*/nullptr,
15035                                              /*DeclsInPrototype=*/None, Loc,
15036                                              Loc, D),
15037                 std::move(DS.getAttributes()), SourceLocation());
15038   D.SetIdentifier(&II, Loc);
15039 
15040   // Insert this function into the enclosing block scope.
15041   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15042   FD->setImplicit();
15043 
15044   AddKnownFunctionAttributes(FD);
15045 
15046   return FD;
15047 }
15048 
15049 /// If this function is a C++ replaceable global allocation function
15050 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15051 /// adds any function attributes that we know a priori based on the standard.
15052 ///
15053 /// We need to check for duplicate attributes both here and where user-written
15054 /// attributes are applied to declarations.
15055 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15056     FunctionDecl *FD) {
15057   if (FD->isInvalidDecl())
15058     return;
15059 
15060   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15061       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15062     return;
15063 
15064   Optional<unsigned> AlignmentParam;
15065   bool IsNothrow = false;
15066   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15067     return;
15068 
15069   // C++2a [basic.stc.dynamic.allocation]p4:
15070   //   An allocation function that has a non-throwing exception specification
15071   //   indicates failure by returning a null pointer value. Any other allocation
15072   //   function never returns a null pointer value and indicates failure only by
15073   //   throwing an exception [...]
15074   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15075     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15076 
15077   // C++2a [basic.stc.dynamic.allocation]p2:
15078   //   An allocation function attempts to allocate the requested amount of
15079   //   storage. [...] If the request succeeds, the value returned by a
15080   //   replaceable allocation function is a [...] pointer value p0 different
15081   //   from any previously returned value p1 [...]
15082   //
15083   // However, this particular information is being added in codegen,
15084   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15085 
15086   // C++2a [basic.stc.dynamic.allocation]p2:
15087   //   An allocation function attempts to allocate the requested amount of
15088   //   storage. If it is successful, it returns the address of the start of a
15089   //   block of storage whose length in bytes is at least as large as the
15090   //   requested size.
15091   if (!FD->hasAttr<AllocSizeAttr>()) {
15092     FD->addAttr(AllocSizeAttr::CreateImplicit(
15093         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15094         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15095   }
15096 
15097   // C++2a [basic.stc.dynamic.allocation]p3:
15098   //   For an allocation function [...], the pointer returned on a successful
15099   //   call shall represent the address of storage that is aligned as follows:
15100   //   (3.1) If the allocation function takes an argument of type
15101   //         std​::​align_­val_­t, the storage will have the alignment
15102   //         specified by the value of this argument.
15103   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15104     FD->addAttr(AllocAlignAttr::CreateImplicit(
15105         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15106   }
15107 
15108   // FIXME:
15109   // C++2a [basic.stc.dynamic.allocation]p3:
15110   //   For an allocation function [...], the pointer returned on a successful
15111   //   call shall represent the address of storage that is aligned as follows:
15112   //   (3.2) Otherwise, if the allocation function is named operator new[],
15113   //         the storage is aligned for any object that does not have
15114   //         new-extended alignment ([basic.align]) and is no larger than the
15115   //         requested size.
15116   //   (3.3) Otherwise, the storage is aligned for any object that does not
15117   //         have new-extended alignment and is of the requested size.
15118 }
15119 
15120 /// Adds any function attributes that we know a priori based on
15121 /// the declaration of this function.
15122 ///
15123 /// These attributes can apply both to implicitly-declared builtins
15124 /// (like __builtin___printf_chk) or to library-declared functions
15125 /// like NSLog or printf.
15126 ///
15127 /// We need to check for duplicate attributes both here and where user-written
15128 /// attributes are applied to declarations.
15129 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15130   if (FD->isInvalidDecl())
15131     return;
15132 
15133   // If this is a built-in function, map its builtin attributes to
15134   // actual attributes.
15135   if (unsigned BuiltinID = FD->getBuiltinID()) {
15136     // Handle printf-formatting attributes.
15137     unsigned FormatIdx;
15138     bool HasVAListArg;
15139     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15140       if (!FD->hasAttr<FormatAttr>()) {
15141         const char *fmt = "printf";
15142         unsigned int NumParams = FD->getNumParams();
15143         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15144             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15145           fmt = "NSString";
15146         FD->addAttr(FormatAttr::CreateImplicit(Context,
15147                                                &Context.Idents.get(fmt),
15148                                                FormatIdx+1,
15149                                                HasVAListArg ? 0 : FormatIdx+2,
15150                                                FD->getLocation()));
15151       }
15152     }
15153     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15154                                              HasVAListArg)) {
15155      if (!FD->hasAttr<FormatAttr>())
15156        FD->addAttr(FormatAttr::CreateImplicit(Context,
15157                                               &Context.Idents.get("scanf"),
15158                                               FormatIdx+1,
15159                                               HasVAListArg ? 0 : FormatIdx+2,
15160                                               FD->getLocation()));
15161     }
15162 
15163     // Handle automatically recognized callbacks.
15164     SmallVector<int, 4> Encoding;
15165     if (!FD->hasAttr<CallbackAttr>() &&
15166         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15167       FD->addAttr(CallbackAttr::CreateImplicit(
15168           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15169 
15170     // Mark const if we don't care about errno and that is the only thing
15171     // preventing the function from being const. This allows IRgen to use LLVM
15172     // intrinsics for such functions.
15173     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15174         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15175       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15176 
15177     // We make "fma" on some platforms const because we know it does not set
15178     // errno in those environments even though it could set errno based on the
15179     // C standard.
15180     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15181     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15182         !FD->hasAttr<ConstAttr>()) {
15183       switch (BuiltinID) {
15184       case Builtin::BI__builtin_fma:
15185       case Builtin::BI__builtin_fmaf:
15186       case Builtin::BI__builtin_fmal:
15187       case Builtin::BIfma:
15188       case Builtin::BIfmaf:
15189       case Builtin::BIfmal:
15190         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15191         break;
15192       default:
15193         break;
15194       }
15195     }
15196 
15197     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15198         !FD->hasAttr<ReturnsTwiceAttr>())
15199       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15200                                          FD->getLocation()));
15201     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15202       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15203     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15204       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15205     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15206       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15207     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15208         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15209       // Add the appropriate attribute, depending on the CUDA compilation mode
15210       // and which target the builtin belongs to. For example, during host
15211       // compilation, aux builtins are __device__, while the rest are __host__.
15212       if (getLangOpts().CUDAIsDevice !=
15213           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15214         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15215       else
15216         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15217     }
15218 
15219     // Add known guaranteed alignment for allocation functions.
15220     switch (BuiltinID) {
15221     case Builtin::BIaligned_alloc:
15222       if (!FD->hasAttr<AllocAlignAttr>())
15223         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15224                                                    FD->getLocation()));
15225       LLVM_FALLTHROUGH;
15226     case Builtin::BIcalloc:
15227     case Builtin::BImalloc:
15228     case Builtin::BImemalign:
15229     case Builtin::BIrealloc:
15230     case Builtin::BIstrdup:
15231     case Builtin::BIstrndup: {
15232       if (!FD->hasAttr<AssumeAlignedAttr>()) {
15233         unsigned NewAlign = Context.getTargetInfo().getNewAlign() /
15234                             Context.getTargetInfo().getCharWidth();
15235         IntegerLiteral *Alignment = IntegerLiteral::Create(
15236             Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy),
15237             Context.UnsignedIntTy, FD->getLocation());
15238         FD->addAttr(AssumeAlignedAttr::CreateImplicit(
15239             Context, Alignment, /*Offset=*/nullptr, FD->getLocation()));
15240       }
15241       break;
15242     }
15243     default:
15244       break;
15245     }
15246   }
15247 
15248   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15249 
15250   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15251   // throw, add an implicit nothrow attribute to any extern "C" function we come
15252   // across.
15253   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15254       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15255     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15256     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15257       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15258   }
15259 
15260   IdentifierInfo *Name = FD->getIdentifier();
15261   if (!Name)
15262     return;
15263   if ((!getLangOpts().CPlusPlus &&
15264        FD->getDeclContext()->isTranslationUnit()) ||
15265       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15266        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15267        LinkageSpecDecl::lang_c)) {
15268     // Okay: this could be a libc/libm/Objective-C function we know
15269     // about.
15270   } else
15271     return;
15272 
15273   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15274     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15275     // target-specific builtins, perhaps?
15276     if (!FD->hasAttr<FormatAttr>())
15277       FD->addAttr(FormatAttr::CreateImplicit(Context,
15278                                              &Context.Idents.get("printf"), 2,
15279                                              Name->isStr("vasprintf") ? 0 : 3,
15280                                              FD->getLocation()));
15281   }
15282 
15283   if (Name->isStr("__CFStringMakeConstantString")) {
15284     // We already have a __builtin___CFStringMakeConstantString,
15285     // but builds that use -fno-constant-cfstrings don't go through that.
15286     if (!FD->hasAttr<FormatArgAttr>())
15287       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15288                                                 FD->getLocation()));
15289   }
15290 }
15291 
15292 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15293                                     TypeSourceInfo *TInfo) {
15294   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15295   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15296 
15297   if (!TInfo) {
15298     assert(D.isInvalidType() && "no declarator info for valid type");
15299     TInfo = Context.getTrivialTypeSourceInfo(T);
15300   }
15301 
15302   // Scope manipulation handled by caller.
15303   TypedefDecl *NewTD =
15304       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15305                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15306 
15307   // Bail out immediately if we have an invalid declaration.
15308   if (D.isInvalidType()) {
15309     NewTD->setInvalidDecl();
15310     return NewTD;
15311   }
15312 
15313   if (D.getDeclSpec().isModulePrivateSpecified()) {
15314     if (CurContext->isFunctionOrMethod())
15315       Diag(NewTD->getLocation(), diag::err_module_private_local)
15316           << 2 << NewTD
15317           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15318           << FixItHint::CreateRemoval(
15319                  D.getDeclSpec().getModulePrivateSpecLoc());
15320     else
15321       NewTD->setModulePrivate();
15322   }
15323 
15324   // C++ [dcl.typedef]p8:
15325   //   If the typedef declaration defines an unnamed class (or
15326   //   enum), the first typedef-name declared by the declaration
15327   //   to be that class type (or enum type) is used to denote the
15328   //   class type (or enum type) for linkage purposes only.
15329   // We need to check whether the type was declared in the declaration.
15330   switch (D.getDeclSpec().getTypeSpecType()) {
15331   case TST_enum:
15332   case TST_struct:
15333   case TST_interface:
15334   case TST_union:
15335   case TST_class: {
15336     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15337     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15338     break;
15339   }
15340 
15341   default:
15342     break;
15343   }
15344 
15345   return NewTD;
15346 }
15347 
15348 /// Check that this is a valid underlying type for an enum declaration.
15349 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15350   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15351   QualType T = TI->getType();
15352 
15353   if (T->isDependentType())
15354     return false;
15355 
15356   // This doesn't use 'isIntegralType' despite the error message mentioning
15357   // integral type because isIntegralType would also allow enum types in C.
15358   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15359     if (BT->isInteger())
15360       return false;
15361 
15362   if (T->isExtIntType())
15363     return false;
15364 
15365   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15366 }
15367 
15368 /// Check whether this is a valid redeclaration of a previous enumeration.
15369 /// \return true if the redeclaration was invalid.
15370 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15371                                   QualType EnumUnderlyingTy, bool IsFixed,
15372                                   const EnumDecl *Prev) {
15373   if (IsScoped != Prev->isScoped()) {
15374     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15375       << Prev->isScoped();
15376     Diag(Prev->getLocation(), diag::note_previous_declaration);
15377     return true;
15378   }
15379 
15380   if (IsFixed && Prev->isFixed()) {
15381     if (!EnumUnderlyingTy->isDependentType() &&
15382         !Prev->getIntegerType()->isDependentType() &&
15383         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15384                                         Prev->getIntegerType())) {
15385       // TODO: Highlight the underlying type of the redeclaration.
15386       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15387         << EnumUnderlyingTy << Prev->getIntegerType();
15388       Diag(Prev->getLocation(), diag::note_previous_declaration)
15389           << Prev->getIntegerTypeRange();
15390       return true;
15391     }
15392   } else if (IsFixed != Prev->isFixed()) {
15393     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15394       << Prev->isFixed();
15395     Diag(Prev->getLocation(), diag::note_previous_declaration);
15396     return true;
15397   }
15398 
15399   return false;
15400 }
15401 
15402 /// Get diagnostic %select index for tag kind for
15403 /// redeclaration diagnostic message.
15404 /// WARNING: Indexes apply to particular diagnostics only!
15405 ///
15406 /// \returns diagnostic %select index.
15407 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15408   switch (Tag) {
15409   case TTK_Struct: return 0;
15410   case TTK_Interface: return 1;
15411   case TTK_Class:  return 2;
15412   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15413   }
15414 }
15415 
15416 /// Determine if tag kind is a class-key compatible with
15417 /// class for redeclaration (class, struct, or __interface).
15418 ///
15419 /// \returns true iff the tag kind is compatible.
15420 static bool isClassCompatTagKind(TagTypeKind Tag)
15421 {
15422   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15423 }
15424 
15425 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15426                                              TagTypeKind TTK) {
15427   if (isa<TypedefDecl>(PrevDecl))
15428     return NTK_Typedef;
15429   else if (isa<TypeAliasDecl>(PrevDecl))
15430     return NTK_TypeAlias;
15431   else if (isa<ClassTemplateDecl>(PrevDecl))
15432     return NTK_Template;
15433   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15434     return NTK_TypeAliasTemplate;
15435   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15436     return NTK_TemplateTemplateArgument;
15437   switch (TTK) {
15438   case TTK_Struct:
15439   case TTK_Interface:
15440   case TTK_Class:
15441     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15442   case TTK_Union:
15443     return NTK_NonUnion;
15444   case TTK_Enum:
15445     return NTK_NonEnum;
15446   }
15447   llvm_unreachable("invalid TTK");
15448 }
15449 
15450 /// Determine whether a tag with a given kind is acceptable
15451 /// as a redeclaration of the given tag declaration.
15452 ///
15453 /// \returns true if the new tag kind is acceptable, false otherwise.
15454 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15455                                         TagTypeKind NewTag, bool isDefinition,
15456                                         SourceLocation NewTagLoc,
15457                                         const IdentifierInfo *Name) {
15458   // C++ [dcl.type.elab]p3:
15459   //   The class-key or enum keyword present in the
15460   //   elaborated-type-specifier shall agree in kind with the
15461   //   declaration to which the name in the elaborated-type-specifier
15462   //   refers. This rule also applies to the form of
15463   //   elaborated-type-specifier that declares a class-name or
15464   //   friend class since it can be construed as referring to the
15465   //   definition of the class. Thus, in any
15466   //   elaborated-type-specifier, the enum keyword shall be used to
15467   //   refer to an enumeration (7.2), the union class-key shall be
15468   //   used to refer to a union (clause 9), and either the class or
15469   //   struct class-key shall be used to refer to a class (clause 9)
15470   //   declared using the class or struct class-key.
15471   TagTypeKind OldTag = Previous->getTagKind();
15472   if (OldTag != NewTag &&
15473       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15474     return false;
15475 
15476   // Tags are compatible, but we might still want to warn on mismatched tags.
15477   // Non-class tags can't be mismatched at this point.
15478   if (!isClassCompatTagKind(NewTag))
15479     return true;
15480 
15481   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15482   // by our warning analysis. We don't want to warn about mismatches with (eg)
15483   // declarations in system headers that are designed to be specialized, but if
15484   // a user asks us to warn, we should warn if their code contains mismatched
15485   // declarations.
15486   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15487     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15488                                       Loc);
15489   };
15490   if (IsIgnoredLoc(NewTagLoc))
15491     return true;
15492 
15493   auto IsIgnored = [&](const TagDecl *Tag) {
15494     return IsIgnoredLoc(Tag->getLocation());
15495   };
15496   while (IsIgnored(Previous)) {
15497     Previous = Previous->getPreviousDecl();
15498     if (!Previous)
15499       return true;
15500     OldTag = Previous->getTagKind();
15501   }
15502 
15503   bool isTemplate = false;
15504   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15505     isTemplate = Record->getDescribedClassTemplate();
15506 
15507   if (inTemplateInstantiation()) {
15508     if (OldTag != NewTag) {
15509       // In a template instantiation, do not offer fix-its for tag mismatches
15510       // since they usually mess up the template instead of fixing the problem.
15511       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15512         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15513         << getRedeclDiagFromTagKind(OldTag);
15514       // FIXME: Note previous location?
15515     }
15516     return true;
15517   }
15518 
15519   if (isDefinition) {
15520     // On definitions, check all previous tags and issue a fix-it for each
15521     // one that doesn't match the current tag.
15522     if (Previous->getDefinition()) {
15523       // Don't suggest fix-its for redefinitions.
15524       return true;
15525     }
15526 
15527     bool previousMismatch = false;
15528     for (const TagDecl *I : Previous->redecls()) {
15529       if (I->getTagKind() != NewTag) {
15530         // Ignore previous declarations for which the warning was disabled.
15531         if (IsIgnored(I))
15532           continue;
15533 
15534         if (!previousMismatch) {
15535           previousMismatch = true;
15536           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15537             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15538             << getRedeclDiagFromTagKind(I->getTagKind());
15539         }
15540         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15541           << getRedeclDiagFromTagKind(NewTag)
15542           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15543                TypeWithKeyword::getTagTypeKindName(NewTag));
15544       }
15545     }
15546     return true;
15547   }
15548 
15549   // Identify the prevailing tag kind: this is the kind of the definition (if
15550   // there is a non-ignored definition), or otherwise the kind of the prior
15551   // (non-ignored) declaration.
15552   const TagDecl *PrevDef = Previous->getDefinition();
15553   if (PrevDef && IsIgnored(PrevDef))
15554     PrevDef = nullptr;
15555   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15556   if (Redecl->getTagKind() != NewTag) {
15557     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15558       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15559       << getRedeclDiagFromTagKind(OldTag);
15560     Diag(Redecl->getLocation(), diag::note_previous_use);
15561 
15562     // If there is a previous definition, suggest a fix-it.
15563     if (PrevDef) {
15564       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15565         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15566         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15567              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15568     }
15569   }
15570 
15571   return true;
15572 }
15573 
15574 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15575 /// from an outer enclosing namespace or file scope inside a friend declaration.
15576 /// This should provide the commented out code in the following snippet:
15577 ///   namespace N {
15578 ///     struct X;
15579 ///     namespace M {
15580 ///       struct Y { friend struct /*N::*/ X; };
15581 ///     }
15582 ///   }
15583 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15584                                          SourceLocation NameLoc) {
15585   // While the decl is in a namespace, do repeated lookup of that name and see
15586   // if we get the same namespace back.  If we do not, continue until
15587   // translation unit scope, at which point we have a fully qualified NNS.
15588   SmallVector<IdentifierInfo *, 4> Namespaces;
15589   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15590   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15591     // This tag should be declared in a namespace, which can only be enclosed by
15592     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15593     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15594     if (!Namespace || Namespace->isAnonymousNamespace())
15595       return FixItHint();
15596     IdentifierInfo *II = Namespace->getIdentifier();
15597     Namespaces.push_back(II);
15598     NamedDecl *Lookup = SemaRef.LookupSingleName(
15599         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15600     if (Lookup == Namespace)
15601       break;
15602   }
15603 
15604   // Once we have all the namespaces, reverse them to go outermost first, and
15605   // build an NNS.
15606   SmallString<64> Insertion;
15607   llvm::raw_svector_ostream OS(Insertion);
15608   if (DC->isTranslationUnit())
15609     OS << "::";
15610   std::reverse(Namespaces.begin(), Namespaces.end());
15611   for (auto *II : Namespaces)
15612     OS << II->getName() << "::";
15613   return FixItHint::CreateInsertion(NameLoc, Insertion);
15614 }
15615 
15616 /// Determine whether a tag originally declared in context \p OldDC can
15617 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15618 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15619 /// using-declaration).
15620 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15621                                          DeclContext *NewDC) {
15622   OldDC = OldDC->getRedeclContext();
15623   NewDC = NewDC->getRedeclContext();
15624 
15625   if (OldDC->Equals(NewDC))
15626     return true;
15627 
15628   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15629   // encloses the other).
15630   if (S.getLangOpts().MSVCCompat &&
15631       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15632     return true;
15633 
15634   return false;
15635 }
15636 
15637 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15638 /// former case, Name will be non-null.  In the later case, Name will be null.
15639 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15640 /// reference/declaration/definition of a tag.
15641 ///
15642 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15643 /// trailing-type-specifier) other than one in an alias-declaration.
15644 ///
15645 /// \param SkipBody If non-null, will be set to indicate if the caller should
15646 /// skip the definition of this tag and treat it as if it were a declaration.
15647 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15648                      SourceLocation KWLoc, CXXScopeSpec &SS,
15649                      IdentifierInfo *Name, SourceLocation NameLoc,
15650                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15651                      SourceLocation ModulePrivateLoc,
15652                      MultiTemplateParamsArg TemplateParameterLists,
15653                      bool &OwnedDecl, bool &IsDependent,
15654                      SourceLocation ScopedEnumKWLoc,
15655                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15656                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15657                      SkipBodyInfo *SkipBody) {
15658   // If this is not a definition, it must have a name.
15659   IdentifierInfo *OrigName = Name;
15660   assert((Name != nullptr || TUK == TUK_Definition) &&
15661          "Nameless record must be a definition!");
15662   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15663 
15664   OwnedDecl = false;
15665   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15666   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15667 
15668   // FIXME: Check member specializations more carefully.
15669   bool isMemberSpecialization = false;
15670   bool Invalid = false;
15671 
15672   // We only need to do this matching if we have template parameters
15673   // or a scope specifier, which also conveniently avoids this work
15674   // for non-C++ cases.
15675   if (TemplateParameterLists.size() > 0 ||
15676       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15677     if (TemplateParameterList *TemplateParams =
15678             MatchTemplateParametersToScopeSpecifier(
15679                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15680                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15681       if (Kind == TTK_Enum) {
15682         Diag(KWLoc, diag::err_enum_template);
15683         return nullptr;
15684       }
15685 
15686       if (TemplateParams->size() > 0) {
15687         // This is a declaration or definition of a class template (which may
15688         // be a member of another template).
15689 
15690         if (Invalid)
15691           return nullptr;
15692 
15693         OwnedDecl = false;
15694         DeclResult Result = CheckClassTemplate(
15695             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15696             AS, ModulePrivateLoc,
15697             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15698             TemplateParameterLists.data(), SkipBody);
15699         return Result.get();
15700       } else {
15701         // The "template<>" header is extraneous.
15702         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15703           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15704         isMemberSpecialization = true;
15705       }
15706     }
15707 
15708     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15709         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15710       return nullptr;
15711   }
15712 
15713   // Figure out the underlying type if this a enum declaration. We need to do
15714   // this early, because it's needed to detect if this is an incompatible
15715   // redeclaration.
15716   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15717   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15718 
15719   if (Kind == TTK_Enum) {
15720     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15721       // No underlying type explicitly specified, or we failed to parse the
15722       // type, default to int.
15723       EnumUnderlying = Context.IntTy.getTypePtr();
15724     } else if (UnderlyingType.get()) {
15725       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15726       // integral type; any cv-qualification is ignored.
15727       TypeSourceInfo *TI = nullptr;
15728       GetTypeFromParser(UnderlyingType.get(), &TI);
15729       EnumUnderlying = TI;
15730 
15731       if (CheckEnumUnderlyingType(TI))
15732         // Recover by falling back to int.
15733         EnumUnderlying = Context.IntTy.getTypePtr();
15734 
15735       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15736                                           UPPC_FixedUnderlyingType))
15737         EnumUnderlying = Context.IntTy.getTypePtr();
15738 
15739     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15740       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15741       // of 'int'. However, if this is an unfixed forward declaration, don't set
15742       // the underlying type unless the user enables -fms-compatibility. This
15743       // makes unfixed forward declared enums incomplete and is more conforming.
15744       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15745         EnumUnderlying = Context.IntTy.getTypePtr();
15746     }
15747   }
15748 
15749   DeclContext *SearchDC = CurContext;
15750   DeclContext *DC = CurContext;
15751   bool isStdBadAlloc = false;
15752   bool isStdAlignValT = false;
15753 
15754   RedeclarationKind Redecl = forRedeclarationInCurContext();
15755   if (TUK == TUK_Friend || TUK == TUK_Reference)
15756     Redecl = NotForRedeclaration;
15757 
15758   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15759   /// implemented asks for structural equivalence checking, the returned decl
15760   /// here is passed back to the parser, allowing the tag body to be parsed.
15761   auto createTagFromNewDecl = [&]() -> TagDecl * {
15762     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15763     // If there is an identifier, use the location of the identifier as the
15764     // location of the decl, otherwise use the location of the struct/union
15765     // keyword.
15766     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15767     TagDecl *New = nullptr;
15768 
15769     if (Kind == TTK_Enum) {
15770       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15771                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15772       // If this is an undefined enum, bail.
15773       if (TUK != TUK_Definition && !Invalid)
15774         return nullptr;
15775       if (EnumUnderlying) {
15776         EnumDecl *ED = cast<EnumDecl>(New);
15777         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15778           ED->setIntegerTypeSourceInfo(TI);
15779         else
15780           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15781         ED->setPromotionType(ED->getIntegerType());
15782       }
15783     } else { // struct/union
15784       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15785                                nullptr);
15786     }
15787 
15788     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15789       // Add alignment attributes if necessary; these attributes are checked
15790       // when the ASTContext lays out the structure.
15791       //
15792       // It is important for implementing the correct semantics that this
15793       // happen here (in ActOnTag). The #pragma pack stack is
15794       // maintained as a result of parser callbacks which can occur at
15795       // many points during the parsing of a struct declaration (because
15796       // the #pragma tokens are effectively skipped over during the
15797       // parsing of the struct).
15798       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15799         AddAlignmentAttributesForRecord(RD);
15800         AddMsStructLayoutForRecord(RD);
15801       }
15802     }
15803     New->setLexicalDeclContext(CurContext);
15804     return New;
15805   };
15806 
15807   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15808   if (Name && SS.isNotEmpty()) {
15809     // We have a nested-name tag ('struct foo::bar').
15810 
15811     // Check for invalid 'foo::'.
15812     if (SS.isInvalid()) {
15813       Name = nullptr;
15814       goto CreateNewDecl;
15815     }
15816 
15817     // If this is a friend or a reference to a class in a dependent
15818     // context, don't try to make a decl for it.
15819     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15820       DC = computeDeclContext(SS, false);
15821       if (!DC) {
15822         IsDependent = true;
15823         return nullptr;
15824       }
15825     } else {
15826       DC = computeDeclContext(SS, true);
15827       if (!DC) {
15828         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15829           << SS.getRange();
15830         return nullptr;
15831       }
15832     }
15833 
15834     if (RequireCompleteDeclContext(SS, DC))
15835       return nullptr;
15836 
15837     SearchDC = DC;
15838     // Look-up name inside 'foo::'.
15839     LookupQualifiedName(Previous, DC);
15840 
15841     if (Previous.isAmbiguous())
15842       return nullptr;
15843 
15844     if (Previous.empty()) {
15845       // Name lookup did not find anything. However, if the
15846       // nested-name-specifier refers to the current instantiation,
15847       // and that current instantiation has any dependent base
15848       // classes, we might find something at instantiation time: treat
15849       // this as a dependent elaborated-type-specifier.
15850       // But this only makes any sense for reference-like lookups.
15851       if (Previous.wasNotFoundInCurrentInstantiation() &&
15852           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15853         IsDependent = true;
15854         return nullptr;
15855       }
15856 
15857       // A tag 'foo::bar' must already exist.
15858       Diag(NameLoc, diag::err_not_tag_in_scope)
15859         << Kind << Name << DC << SS.getRange();
15860       Name = nullptr;
15861       Invalid = true;
15862       goto CreateNewDecl;
15863     }
15864   } else if (Name) {
15865     // C++14 [class.mem]p14:
15866     //   If T is the name of a class, then each of the following shall have a
15867     //   name different from T:
15868     //    -- every member of class T that is itself a type
15869     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15870         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15871       return nullptr;
15872 
15873     // If this is a named struct, check to see if there was a previous forward
15874     // declaration or definition.
15875     // FIXME: We're looking into outer scopes here, even when we
15876     // shouldn't be. Doing so can result in ambiguities that we
15877     // shouldn't be diagnosing.
15878     LookupName(Previous, S);
15879 
15880     // When declaring or defining a tag, ignore ambiguities introduced
15881     // by types using'ed into this scope.
15882     if (Previous.isAmbiguous() &&
15883         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15884       LookupResult::Filter F = Previous.makeFilter();
15885       while (F.hasNext()) {
15886         NamedDecl *ND = F.next();
15887         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15888                 SearchDC->getRedeclContext()))
15889           F.erase();
15890       }
15891       F.done();
15892     }
15893 
15894     // C++11 [namespace.memdef]p3:
15895     //   If the name in a friend declaration is neither qualified nor
15896     //   a template-id and the declaration is a function or an
15897     //   elaborated-type-specifier, the lookup to determine whether
15898     //   the entity has been previously declared shall not consider
15899     //   any scopes outside the innermost enclosing namespace.
15900     //
15901     // MSVC doesn't implement the above rule for types, so a friend tag
15902     // declaration may be a redeclaration of a type declared in an enclosing
15903     // scope.  They do implement this rule for friend functions.
15904     //
15905     // Does it matter that this should be by scope instead of by
15906     // semantic context?
15907     if (!Previous.empty() && TUK == TUK_Friend) {
15908       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15909       LookupResult::Filter F = Previous.makeFilter();
15910       bool FriendSawTagOutsideEnclosingNamespace = false;
15911       while (F.hasNext()) {
15912         NamedDecl *ND = F.next();
15913         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15914         if (DC->isFileContext() &&
15915             !EnclosingNS->Encloses(ND->getDeclContext())) {
15916           if (getLangOpts().MSVCCompat)
15917             FriendSawTagOutsideEnclosingNamespace = true;
15918           else
15919             F.erase();
15920         }
15921       }
15922       F.done();
15923 
15924       // Diagnose this MSVC extension in the easy case where lookup would have
15925       // unambiguously found something outside the enclosing namespace.
15926       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15927         NamedDecl *ND = Previous.getFoundDecl();
15928         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15929             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15930       }
15931     }
15932 
15933     // Note:  there used to be some attempt at recovery here.
15934     if (Previous.isAmbiguous())
15935       return nullptr;
15936 
15937     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15938       // FIXME: This makes sure that we ignore the contexts associated
15939       // with C structs, unions, and enums when looking for a matching
15940       // tag declaration or definition. See the similar lookup tweak
15941       // in Sema::LookupName; is there a better way to deal with this?
15942       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15943         SearchDC = SearchDC->getParent();
15944     }
15945   }
15946 
15947   if (Previous.isSingleResult() &&
15948       Previous.getFoundDecl()->isTemplateParameter()) {
15949     // Maybe we will complain about the shadowed template parameter.
15950     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15951     // Just pretend that we didn't see the previous declaration.
15952     Previous.clear();
15953   }
15954 
15955   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15956       DC->Equals(getStdNamespace())) {
15957     if (Name->isStr("bad_alloc")) {
15958       // This is a declaration of or a reference to "std::bad_alloc".
15959       isStdBadAlloc = true;
15960 
15961       // If std::bad_alloc has been implicitly declared (but made invisible to
15962       // name lookup), fill in this implicit declaration as the previous
15963       // declaration, so that the declarations get chained appropriately.
15964       if (Previous.empty() && StdBadAlloc)
15965         Previous.addDecl(getStdBadAlloc());
15966     } else if (Name->isStr("align_val_t")) {
15967       isStdAlignValT = true;
15968       if (Previous.empty() && StdAlignValT)
15969         Previous.addDecl(getStdAlignValT());
15970     }
15971   }
15972 
15973   // If we didn't find a previous declaration, and this is a reference
15974   // (or friend reference), move to the correct scope.  In C++, we
15975   // also need to do a redeclaration lookup there, just in case
15976   // there's a shadow friend decl.
15977   if (Name && Previous.empty() &&
15978       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15979     if (Invalid) goto CreateNewDecl;
15980     assert(SS.isEmpty());
15981 
15982     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15983       // C++ [basic.scope.pdecl]p5:
15984       //   -- for an elaborated-type-specifier of the form
15985       //
15986       //          class-key identifier
15987       //
15988       //      if the elaborated-type-specifier is used in the
15989       //      decl-specifier-seq or parameter-declaration-clause of a
15990       //      function defined in namespace scope, the identifier is
15991       //      declared as a class-name in the namespace that contains
15992       //      the declaration; otherwise, except as a friend
15993       //      declaration, the identifier is declared in the smallest
15994       //      non-class, non-function-prototype scope that contains the
15995       //      declaration.
15996       //
15997       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15998       // C structs and unions.
15999       //
16000       // It is an error in C++ to declare (rather than define) an enum
16001       // type, including via an elaborated type specifier.  We'll
16002       // diagnose that later; for now, declare the enum in the same
16003       // scope as we would have picked for any other tag type.
16004       //
16005       // GNU C also supports this behavior as part of its incomplete
16006       // enum types extension, while GNU C++ does not.
16007       //
16008       // Find the context where we'll be declaring the tag.
16009       // FIXME: We would like to maintain the current DeclContext as the
16010       // lexical context,
16011       SearchDC = getTagInjectionContext(SearchDC);
16012 
16013       // Find the scope where we'll be declaring the tag.
16014       S = getTagInjectionScope(S, getLangOpts());
16015     } else {
16016       assert(TUK == TUK_Friend);
16017       // C++ [namespace.memdef]p3:
16018       //   If a friend declaration in a non-local class first declares a
16019       //   class or function, the friend class or function is a member of
16020       //   the innermost enclosing namespace.
16021       SearchDC = SearchDC->getEnclosingNamespaceContext();
16022     }
16023 
16024     // In C++, we need to do a redeclaration lookup to properly
16025     // diagnose some problems.
16026     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16027     // hidden declaration so that we don't get ambiguity errors when using a
16028     // type declared by an elaborated-type-specifier.  In C that is not correct
16029     // and we should instead merge compatible types found by lookup.
16030     if (getLangOpts().CPlusPlus) {
16031       // FIXME: This can perform qualified lookups into function contexts,
16032       // which are meaningless.
16033       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16034       LookupQualifiedName(Previous, SearchDC);
16035     } else {
16036       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16037       LookupName(Previous, S);
16038     }
16039   }
16040 
16041   // If we have a known previous declaration to use, then use it.
16042   if (Previous.empty() && SkipBody && SkipBody->Previous)
16043     Previous.addDecl(SkipBody->Previous);
16044 
16045   if (!Previous.empty()) {
16046     NamedDecl *PrevDecl = Previous.getFoundDecl();
16047     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16048 
16049     // It's okay to have a tag decl in the same scope as a typedef
16050     // which hides a tag decl in the same scope.  Finding this
16051     // with a redeclaration lookup can only actually happen in C++.
16052     //
16053     // This is also okay for elaborated-type-specifiers, which is
16054     // technically forbidden by the current standard but which is
16055     // okay according to the likely resolution of an open issue;
16056     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16057     if (getLangOpts().CPlusPlus) {
16058       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16059         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16060           TagDecl *Tag = TT->getDecl();
16061           if (Tag->getDeclName() == Name &&
16062               Tag->getDeclContext()->getRedeclContext()
16063                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16064             PrevDecl = Tag;
16065             Previous.clear();
16066             Previous.addDecl(Tag);
16067             Previous.resolveKind();
16068           }
16069         }
16070       }
16071     }
16072 
16073     // If this is a redeclaration of a using shadow declaration, it must
16074     // declare a tag in the same context. In MSVC mode, we allow a
16075     // redefinition if either context is within the other.
16076     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16077       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16078       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16079           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16080           !(OldTag && isAcceptableTagRedeclContext(
16081                           *this, OldTag->getDeclContext(), SearchDC))) {
16082         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16083         Diag(Shadow->getTargetDecl()->getLocation(),
16084              diag::note_using_decl_target);
16085         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16086             << 0;
16087         // Recover by ignoring the old declaration.
16088         Previous.clear();
16089         goto CreateNewDecl;
16090       }
16091     }
16092 
16093     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16094       // If this is a use of a previous tag, or if the tag is already declared
16095       // in the same scope (so that the definition/declaration completes or
16096       // rementions the tag), reuse the decl.
16097       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16098           isDeclInScope(DirectPrevDecl, SearchDC, S,
16099                         SS.isNotEmpty() || isMemberSpecialization)) {
16100         // Make sure that this wasn't declared as an enum and now used as a
16101         // struct or something similar.
16102         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16103                                           TUK == TUK_Definition, KWLoc,
16104                                           Name)) {
16105           bool SafeToContinue
16106             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16107                Kind != TTK_Enum);
16108           if (SafeToContinue)
16109             Diag(KWLoc, diag::err_use_with_wrong_tag)
16110               << Name
16111               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16112                                               PrevTagDecl->getKindName());
16113           else
16114             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16115           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16116 
16117           if (SafeToContinue)
16118             Kind = PrevTagDecl->getTagKind();
16119           else {
16120             // Recover by making this an anonymous redefinition.
16121             Name = nullptr;
16122             Previous.clear();
16123             Invalid = true;
16124           }
16125         }
16126 
16127         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16128           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16129           if (TUK == TUK_Reference || TUK == TUK_Friend)
16130             return PrevTagDecl;
16131 
16132           QualType EnumUnderlyingTy;
16133           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16134             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16135           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16136             EnumUnderlyingTy = QualType(T, 0);
16137 
16138           // All conflicts with previous declarations are recovered by
16139           // returning the previous declaration, unless this is a definition,
16140           // in which case we want the caller to bail out.
16141           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16142                                      ScopedEnum, EnumUnderlyingTy,
16143                                      IsFixed, PrevEnum))
16144             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16145         }
16146 
16147         // C++11 [class.mem]p1:
16148         //   A member shall not be declared twice in the member-specification,
16149         //   except that a nested class or member class template can be declared
16150         //   and then later defined.
16151         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16152             S->isDeclScope(PrevDecl)) {
16153           Diag(NameLoc, diag::ext_member_redeclared);
16154           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16155         }
16156 
16157         if (!Invalid) {
16158           // If this is a use, just return the declaration we found, unless
16159           // we have attributes.
16160           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16161             if (!Attrs.empty()) {
16162               // FIXME: Diagnose these attributes. For now, we create a new
16163               // declaration to hold them.
16164             } else if (TUK == TUK_Reference &&
16165                        (PrevTagDecl->getFriendObjectKind() ==
16166                             Decl::FOK_Undeclared ||
16167                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16168                        SS.isEmpty()) {
16169               // This declaration is a reference to an existing entity, but
16170               // has different visibility from that entity: it either makes
16171               // a friend visible or it makes a type visible in a new module.
16172               // In either case, create a new declaration. We only do this if
16173               // the declaration would have meant the same thing if no prior
16174               // declaration were found, that is, if it was found in the same
16175               // scope where we would have injected a declaration.
16176               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16177                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16178                 return PrevTagDecl;
16179               // This is in the injected scope, create a new declaration in
16180               // that scope.
16181               S = getTagInjectionScope(S, getLangOpts());
16182             } else {
16183               return PrevTagDecl;
16184             }
16185           }
16186 
16187           // Diagnose attempts to redefine a tag.
16188           if (TUK == TUK_Definition) {
16189             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16190               // If we're defining a specialization and the previous definition
16191               // is from an implicit instantiation, don't emit an error
16192               // here; we'll catch this in the general case below.
16193               bool IsExplicitSpecializationAfterInstantiation = false;
16194               if (isMemberSpecialization) {
16195                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16196                   IsExplicitSpecializationAfterInstantiation =
16197                     RD->getTemplateSpecializationKind() !=
16198                     TSK_ExplicitSpecialization;
16199                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16200                   IsExplicitSpecializationAfterInstantiation =
16201                     ED->getTemplateSpecializationKind() !=
16202                     TSK_ExplicitSpecialization;
16203               }
16204 
16205               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16206               // not keep more that one definition around (merge them). However,
16207               // ensure the decl passes the structural compatibility check in
16208               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16209               NamedDecl *Hidden = nullptr;
16210               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16211                 // There is a definition of this tag, but it is not visible. We
16212                 // explicitly make use of C++'s one definition rule here, and
16213                 // assume that this definition is identical to the hidden one
16214                 // we already have. Make the existing definition visible and
16215                 // use it in place of this one.
16216                 if (!getLangOpts().CPlusPlus) {
16217                   // Postpone making the old definition visible until after we
16218                   // complete parsing the new one and do the structural
16219                   // comparison.
16220                   SkipBody->CheckSameAsPrevious = true;
16221                   SkipBody->New = createTagFromNewDecl();
16222                   SkipBody->Previous = Def;
16223                   return Def;
16224                 } else {
16225                   SkipBody->ShouldSkip = true;
16226                   SkipBody->Previous = Def;
16227                   makeMergedDefinitionVisible(Hidden);
16228                   // Carry on and handle it like a normal definition. We'll
16229                   // skip starting the definitiion later.
16230                 }
16231               } else if (!IsExplicitSpecializationAfterInstantiation) {
16232                 // A redeclaration in function prototype scope in C isn't
16233                 // visible elsewhere, so merely issue a warning.
16234                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16235                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16236                 else
16237                   Diag(NameLoc, diag::err_redefinition) << Name;
16238                 notePreviousDefinition(Def,
16239                                        NameLoc.isValid() ? NameLoc : KWLoc);
16240                 // If this is a redefinition, recover by making this
16241                 // struct be anonymous, which will make any later
16242                 // references get the previous definition.
16243                 Name = nullptr;
16244                 Previous.clear();
16245                 Invalid = true;
16246               }
16247             } else {
16248               // If the type is currently being defined, complain
16249               // about a nested redefinition.
16250               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16251               if (TD->isBeingDefined()) {
16252                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16253                 Diag(PrevTagDecl->getLocation(),
16254                      diag::note_previous_definition);
16255                 Name = nullptr;
16256                 Previous.clear();
16257                 Invalid = true;
16258               }
16259             }
16260 
16261             // Okay, this is definition of a previously declared or referenced
16262             // tag. We're going to create a new Decl for it.
16263           }
16264 
16265           // Okay, we're going to make a redeclaration.  If this is some kind
16266           // of reference, make sure we build the redeclaration in the same DC
16267           // as the original, and ignore the current access specifier.
16268           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16269             SearchDC = PrevTagDecl->getDeclContext();
16270             AS = AS_none;
16271           }
16272         }
16273         // If we get here we have (another) forward declaration or we
16274         // have a definition.  Just create a new decl.
16275 
16276       } else {
16277         // If we get here, this is a definition of a new tag type in a nested
16278         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16279         // new decl/type.  We set PrevDecl to NULL so that the entities
16280         // have distinct types.
16281         Previous.clear();
16282       }
16283       // If we get here, we're going to create a new Decl. If PrevDecl
16284       // is non-NULL, it's a definition of the tag declared by
16285       // PrevDecl. If it's NULL, we have a new definition.
16286 
16287     // Otherwise, PrevDecl is not a tag, but was found with tag
16288     // lookup.  This is only actually possible in C++, where a few
16289     // things like templates still live in the tag namespace.
16290     } else {
16291       // Use a better diagnostic if an elaborated-type-specifier
16292       // found the wrong kind of type on the first
16293       // (non-redeclaration) lookup.
16294       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16295           !Previous.isForRedeclaration()) {
16296         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16297         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16298                                                        << Kind;
16299         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16300         Invalid = true;
16301 
16302       // Otherwise, only diagnose if the declaration is in scope.
16303       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16304                                 SS.isNotEmpty() || isMemberSpecialization)) {
16305         // do nothing
16306 
16307       // Diagnose implicit declarations introduced by elaborated types.
16308       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16309         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16310         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16311         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16312         Invalid = true;
16313 
16314       // Otherwise it's a declaration.  Call out a particularly common
16315       // case here.
16316       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16317         unsigned Kind = 0;
16318         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16319         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16320           << Name << Kind << TND->getUnderlyingType();
16321         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16322         Invalid = true;
16323 
16324       // Otherwise, diagnose.
16325       } else {
16326         // The tag name clashes with something else in the target scope,
16327         // issue an error and recover by making this tag be anonymous.
16328         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16329         notePreviousDefinition(PrevDecl, NameLoc);
16330         Name = nullptr;
16331         Invalid = true;
16332       }
16333 
16334       // The existing declaration isn't relevant to us; we're in a
16335       // new scope, so clear out the previous declaration.
16336       Previous.clear();
16337     }
16338   }
16339 
16340 CreateNewDecl:
16341 
16342   TagDecl *PrevDecl = nullptr;
16343   if (Previous.isSingleResult())
16344     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16345 
16346   // If there is an identifier, use the location of the identifier as the
16347   // location of the decl, otherwise use the location of the struct/union
16348   // keyword.
16349   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16350 
16351   // Otherwise, create a new declaration. If there is a previous
16352   // declaration of the same entity, the two will be linked via
16353   // PrevDecl.
16354   TagDecl *New;
16355 
16356   if (Kind == TTK_Enum) {
16357     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16358     // enum X { A, B, C } D;    D should chain to X.
16359     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16360                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16361                            ScopedEnumUsesClassTag, IsFixed);
16362 
16363     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16364       StdAlignValT = cast<EnumDecl>(New);
16365 
16366     // If this is an undefined enum, warn.
16367     if (TUK != TUK_Definition && !Invalid) {
16368       TagDecl *Def;
16369       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16370         // C++0x: 7.2p2: opaque-enum-declaration.
16371         // Conflicts are diagnosed above. Do nothing.
16372       }
16373       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16374         Diag(Loc, diag::ext_forward_ref_enum_def)
16375           << New;
16376         Diag(Def->getLocation(), diag::note_previous_definition);
16377       } else {
16378         unsigned DiagID = diag::ext_forward_ref_enum;
16379         if (getLangOpts().MSVCCompat)
16380           DiagID = diag::ext_ms_forward_ref_enum;
16381         else if (getLangOpts().CPlusPlus)
16382           DiagID = diag::err_forward_ref_enum;
16383         Diag(Loc, DiagID);
16384       }
16385     }
16386 
16387     if (EnumUnderlying) {
16388       EnumDecl *ED = cast<EnumDecl>(New);
16389       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16390         ED->setIntegerTypeSourceInfo(TI);
16391       else
16392         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16393       ED->setPromotionType(ED->getIntegerType());
16394       assert(ED->isComplete() && "enum with type should be complete");
16395     }
16396   } else {
16397     // struct/union/class
16398 
16399     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16400     // struct X { int A; } D;    D should chain to X.
16401     if (getLangOpts().CPlusPlus) {
16402       // FIXME: Look for a way to use RecordDecl for simple structs.
16403       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16404                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16405 
16406       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16407         StdBadAlloc = cast<CXXRecordDecl>(New);
16408     } else
16409       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16410                                cast_or_null<RecordDecl>(PrevDecl));
16411   }
16412 
16413   // C++11 [dcl.type]p3:
16414   //   A type-specifier-seq shall not define a class or enumeration [...].
16415   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16416       TUK == TUK_Definition) {
16417     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16418       << Context.getTagDeclType(New);
16419     Invalid = true;
16420   }
16421 
16422   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16423       DC->getDeclKind() == Decl::Enum) {
16424     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16425       << Context.getTagDeclType(New);
16426     Invalid = true;
16427   }
16428 
16429   // Maybe add qualifier info.
16430   if (SS.isNotEmpty()) {
16431     if (SS.isSet()) {
16432       // If this is either a declaration or a definition, check the
16433       // nested-name-specifier against the current context.
16434       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16435           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16436                                        isMemberSpecialization))
16437         Invalid = true;
16438 
16439       New->setQualifierInfo(SS.getWithLocInContext(Context));
16440       if (TemplateParameterLists.size() > 0) {
16441         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16442       }
16443     }
16444     else
16445       Invalid = true;
16446   }
16447 
16448   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16449     // Add alignment attributes if necessary; these attributes are checked when
16450     // the ASTContext lays out the structure.
16451     //
16452     // It is important for implementing the correct semantics that this
16453     // happen here (in ActOnTag). The #pragma pack stack is
16454     // maintained as a result of parser callbacks which can occur at
16455     // many points during the parsing of a struct declaration (because
16456     // the #pragma tokens are effectively skipped over during the
16457     // parsing of the struct).
16458     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16459       AddAlignmentAttributesForRecord(RD);
16460       AddMsStructLayoutForRecord(RD);
16461     }
16462   }
16463 
16464   if (ModulePrivateLoc.isValid()) {
16465     if (isMemberSpecialization)
16466       Diag(New->getLocation(), diag::err_module_private_specialization)
16467         << 2
16468         << FixItHint::CreateRemoval(ModulePrivateLoc);
16469     // __module_private__ does not apply to local classes. However, we only
16470     // diagnose this as an error when the declaration specifiers are
16471     // freestanding. Here, we just ignore the __module_private__.
16472     else if (!SearchDC->isFunctionOrMethod())
16473       New->setModulePrivate();
16474   }
16475 
16476   // If this is a specialization of a member class (of a class template),
16477   // check the specialization.
16478   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16479     Invalid = true;
16480 
16481   // If we're declaring or defining a tag in function prototype scope in C,
16482   // note that this type can only be used within the function and add it to
16483   // the list of decls to inject into the function definition scope.
16484   if ((Name || Kind == TTK_Enum) &&
16485       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16486     if (getLangOpts().CPlusPlus) {
16487       // C++ [dcl.fct]p6:
16488       //   Types shall not be defined in return or parameter types.
16489       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16490         Diag(Loc, diag::err_type_defined_in_param_type)
16491             << Name;
16492         Invalid = true;
16493       }
16494     } else if (!PrevDecl) {
16495       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16496     }
16497   }
16498 
16499   if (Invalid)
16500     New->setInvalidDecl();
16501 
16502   // Set the lexical context. If the tag has a C++ scope specifier, the
16503   // lexical context will be different from the semantic context.
16504   New->setLexicalDeclContext(CurContext);
16505 
16506   // Mark this as a friend decl if applicable.
16507   // In Microsoft mode, a friend declaration also acts as a forward
16508   // declaration so we always pass true to setObjectOfFriendDecl to make
16509   // the tag name visible.
16510   if (TUK == TUK_Friend)
16511     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16512 
16513   // Set the access specifier.
16514   if (!Invalid && SearchDC->isRecord())
16515     SetMemberAccessSpecifier(New, PrevDecl, AS);
16516 
16517   if (PrevDecl)
16518     CheckRedeclarationModuleOwnership(New, PrevDecl);
16519 
16520   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16521     New->startDefinition();
16522 
16523   ProcessDeclAttributeList(S, New, Attrs);
16524   AddPragmaAttributes(S, New);
16525 
16526   // If this has an identifier, add it to the scope stack.
16527   if (TUK == TUK_Friend) {
16528     // We might be replacing an existing declaration in the lookup tables;
16529     // if so, borrow its access specifier.
16530     if (PrevDecl)
16531       New->setAccess(PrevDecl->getAccess());
16532 
16533     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16534     DC->makeDeclVisibleInContext(New);
16535     if (Name) // can be null along some error paths
16536       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16537         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16538   } else if (Name) {
16539     S = getNonFieldDeclScope(S);
16540     PushOnScopeChains(New, S, true);
16541   } else {
16542     CurContext->addDecl(New);
16543   }
16544 
16545   // If this is the C FILE type, notify the AST context.
16546   if (IdentifierInfo *II = New->getIdentifier())
16547     if (!New->isInvalidDecl() &&
16548         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16549         II->isStr("FILE"))
16550       Context.setFILEDecl(New);
16551 
16552   if (PrevDecl)
16553     mergeDeclAttributes(New, PrevDecl);
16554 
16555   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16556     inferGslOwnerPointerAttribute(CXXRD);
16557 
16558   // If there's a #pragma GCC visibility in scope, set the visibility of this
16559   // record.
16560   AddPushedVisibilityAttribute(New);
16561 
16562   if (isMemberSpecialization && !New->isInvalidDecl())
16563     CompleteMemberSpecialization(New, Previous);
16564 
16565   OwnedDecl = true;
16566   // In C++, don't return an invalid declaration. We can't recover well from
16567   // the cases where we make the type anonymous.
16568   if (Invalid && getLangOpts().CPlusPlus) {
16569     if (New->isBeingDefined())
16570       if (auto RD = dyn_cast<RecordDecl>(New))
16571         RD->completeDefinition();
16572     return nullptr;
16573   } else if (SkipBody && SkipBody->ShouldSkip) {
16574     return SkipBody->Previous;
16575   } else {
16576     return New;
16577   }
16578 }
16579 
16580 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16581   AdjustDeclIfTemplate(TagD);
16582   TagDecl *Tag = cast<TagDecl>(TagD);
16583 
16584   // Enter the tag context.
16585   PushDeclContext(S, Tag);
16586 
16587   ActOnDocumentableDecl(TagD);
16588 
16589   // If there's a #pragma GCC visibility in scope, set the visibility of this
16590   // record.
16591   AddPushedVisibilityAttribute(Tag);
16592 }
16593 
16594 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16595                                     SkipBodyInfo &SkipBody) {
16596   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16597     return false;
16598 
16599   // Make the previous decl visible.
16600   makeMergedDefinitionVisible(SkipBody.Previous);
16601   return true;
16602 }
16603 
16604 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16605   assert(isa<ObjCContainerDecl>(IDecl) &&
16606          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16607   DeclContext *OCD = cast<DeclContext>(IDecl);
16608   assert(OCD->getLexicalParent() == CurContext &&
16609       "The next DeclContext should be lexically contained in the current one.");
16610   CurContext = OCD;
16611   return IDecl;
16612 }
16613 
16614 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16615                                            SourceLocation FinalLoc,
16616                                            bool IsFinalSpelledSealed,
16617                                            bool IsAbstract,
16618                                            SourceLocation LBraceLoc) {
16619   AdjustDeclIfTemplate(TagD);
16620   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16621 
16622   FieldCollector->StartClass();
16623 
16624   if (!Record->getIdentifier())
16625     return;
16626 
16627   if (IsAbstract)
16628     Record->markAbstract();
16629 
16630   if (FinalLoc.isValid()) {
16631     Record->addAttr(FinalAttr::Create(
16632         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16633         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16634   }
16635   // C++ [class]p2:
16636   //   [...] The class-name is also inserted into the scope of the
16637   //   class itself; this is known as the injected-class-name. For
16638   //   purposes of access checking, the injected-class-name is treated
16639   //   as if it were a public member name.
16640   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16641       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16642       Record->getLocation(), Record->getIdentifier(),
16643       /*PrevDecl=*/nullptr,
16644       /*DelayTypeCreation=*/true);
16645   Context.getTypeDeclType(InjectedClassName, Record);
16646   InjectedClassName->setImplicit();
16647   InjectedClassName->setAccess(AS_public);
16648   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16649       InjectedClassName->setDescribedClassTemplate(Template);
16650   PushOnScopeChains(InjectedClassName, S);
16651   assert(InjectedClassName->isInjectedClassName() &&
16652          "Broken injected-class-name");
16653 }
16654 
16655 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16656                                     SourceRange BraceRange) {
16657   AdjustDeclIfTemplate(TagD);
16658   TagDecl *Tag = cast<TagDecl>(TagD);
16659   Tag->setBraceRange(BraceRange);
16660 
16661   // Make sure we "complete" the definition even it is invalid.
16662   if (Tag->isBeingDefined()) {
16663     assert(Tag->isInvalidDecl() && "We should already have completed it");
16664     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16665       RD->completeDefinition();
16666   }
16667 
16668   if (isa<CXXRecordDecl>(Tag)) {
16669     FieldCollector->FinishClass();
16670   }
16671 
16672   // Exit this scope of this tag's definition.
16673   PopDeclContext();
16674 
16675   if (getCurLexicalContext()->isObjCContainer() &&
16676       Tag->getDeclContext()->isFileContext())
16677     Tag->setTopLevelDeclInObjCContainer();
16678 
16679   // Notify the consumer that we've defined a tag.
16680   if (!Tag->isInvalidDecl())
16681     Consumer.HandleTagDeclDefinition(Tag);
16682 
16683   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16684   // from XLs and instead matches the XL #pragma pack(1) behavior.
16685   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16686       AlignPackStack.hasValue()) {
16687     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16688     // Only diagnose #pragma align(packed).
16689     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16690       return;
16691     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16692     if (!RD)
16693       return;
16694     // Only warn if there is at least 1 bitfield member.
16695     if (llvm::any_of(RD->fields(),
16696                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16697       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16698   }
16699 }
16700 
16701 void Sema::ActOnObjCContainerFinishDefinition() {
16702   // Exit this scope of this interface definition.
16703   PopDeclContext();
16704 }
16705 
16706 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16707   assert(DC == CurContext && "Mismatch of container contexts");
16708   OriginalLexicalContext = DC;
16709   ActOnObjCContainerFinishDefinition();
16710 }
16711 
16712 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16713   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16714   OriginalLexicalContext = nullptr;
16715 }
16716 
16717 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16718   AdjustDeclIfTemplate(TagD);
16719   TagDecl *Tag = cast<TagDecl>(TagD);
16720   Tag->setInvalidDecl();
16721 
16722   // Make sure we "complete" the definition even it is invalid.
16723   if (Tag->isBeingDefined()) {
16724     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16725       RD->completeDefinition();
16726   }
16727 
16728   // We're undoing ActOnTagStartDefinition here, not
16729   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16730   // the FieldCollector.
16731 
16732   PopDeclContext();
16733 }
16734 
16735 // Note that FieldName may be null for anonymous bitfields.
16736 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16737                                 IdentifierInfo *FieldName,
16738                                 QualType FieldTy, bool IsMsStruct,
16739                                 Expr *BitWidth, bool *ZeroWidth) {
16740   assert(BitWidth);
16741   if (BitWidth->containsErrors())
16742     return ExprError();
16743 
16744   // Default to true; that shouldn't confuse checks for emptiness
16745   if (ZeroWidth)
16746     *ZeroWidth = true;
16747 
16748   // C99 6.7.2.1p4 - verify the field type.
16749   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16750   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16751     // Handle incomplete and sizeless types with a specific error.
16752     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16753                                  diag::err_field_incomplete_or_sizeless))
16754       return ExprError();
16755     if (FieldName)
16756       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16757         << FieldName << FieldTy << BitWidth->getSourceRange();
16758     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16759       << FieldTy << BitWidth->getSourceRange();
16760   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16761                                              UPPC_BitFieldWidth))
16762     return ExprError();
16763 
16764   // If the bit-width is type- or value-dependent, don't try to check
16765   // it now.
16766   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16767     return BitWidth;
16768 
16769   llvm::APSInt Value;
16770   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16771   if (ICE.isInvalid())
16772     return ICE;
16773   BitWidth = ICE.get();
16774 
16775   if (Value != 0 && ZeroWidth)
16776     *ZeroWidth = false;
16777 
16778   // Zero-width bitfield is ok for anonymous field.
16779   if (Value == 0 && FieldName)
16780     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16781 
16782   if (Value.isSigned() && Value.isNegative()) {
16783     if (FieldName)
16784       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16785                << FieldName << toString(Value, 10);
16786     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16787       << toString(Value, 10);
16788   }
16789 
16790   // The size of the bit-field must not exceed our maximum permitted object
16791   // size.
16792   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16793     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16794            << !FieldName << FieldName << toString(Value, 10);
16795   }
16796 
16797   if (!FieldTy->isDependentType()) {
16798     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16799     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16800     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16801 
16802     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16803     // ABI.
16804     bool CStdConstraintViolation =
16805         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16806     bool MSBitfieldViolation =
16807         Value.ugt(TypeStorageSize) &&
16808         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16809     if (CStdConstraintViolation || MSBitfieldViolation) {
16810       unsigned DiagWidth =
16811           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16812       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16813              << (bool)FieldName << FieldName << toString(Value, 10)
16814              << !CStdConstraintViolation << DiagWidth;
16815     }
16816 
16817     // Warn on types where the user might conceivably expect to get all
16818     // specified bits as value bits: that's all integral types other than
16819     // 'bool'.
16820     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16821       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16822           << FieldName << toString(Value, 10)
16823           << (unsigned)TypeWidth;
16824     }
16825   }
16826 
16827   return BitWidth;
16828 }
16829 
16830 /// ActOnField - Each field of a C struct/union is passed into this in order
16831 /// to create a FieldDecl object for it.
16832 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16833                        Declarator &D, Expr *BitfieldWidth) {
16834   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16835                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16836                                /*InitStyle=*/ICIS_NoInit, AS_public);
16837   return Res;
16838 }
16839 
16840 /// HandleField - Analyze a field of a C struct or a C++ data member.
16841 ///
16842 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16843                              SourceLocation DeclStart,
16844                              Declarator &D, Expr *BitWidth,
16845                              InClassInitStyle InitStyle,
16846                              AccessSpecifier AS) {
16847   if (D.isDecompositionDeclarator()) {
16848     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16849     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16850       << Decomp.getSourceRange();
16851     return nullptr;
16852   }
16853 
16854   IdentifierInfo *II = D.getIdentifier();
16855   SourceLocation Loc = DeclStart;
16856   if (II) Loc = D.getIdentifierLoc();
16857 
16858   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16859   QualType T = TInfo->getType();
16860   if (getLangOpts().CPlusPlus) {
16861     CheckExtraCXXDefaultArguments(D);
16862 
16863     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16864                                         UPPC_DataMemberType)) {
16865       D.setInvalidType();
16866       T = Context.IntTy;
16867       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16868     }
16869   }
16870 
16871   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16872 
16873   if (D.getDeclSpec().isInlineSpecified())
16874     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16875         << getLangOpts().CPlusPlus17;
16876   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16877     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16878          diag::err_invalid_thread)
16879       << DeclSpec::getSpecifierName(TSCS);
16880 
16881   // Check to see if this name was declared as a member previously
16882   NamedDecl *PrevDecl = nullptr;
16883   LookupResult Previous(*this, II, Loc, LookupMemberName,
16884                         ForVisibleRedeclaration);
16885   LookupName(Previous, S);
16886   switch (Previous.getResultKind()) {
16887     case LookupResult::Found:
16888     case LookupResult::FoundUnresolvedValue:
16889       PrevDecl = Previous.getAsSingle<NamedDecl>();
16890       break;
16891 
16892     case LookupResult::FoundOverloaded:
16893       PrevDecl = Previous.getRepresentativeDecl();
16894       break;
16895 
16896     case LookupResult::NotFound:
16897     case LookupResult::NotFoundInCurrentInstantiation:
16898     case LookupResult::Ambiguous:
16899       break;
16900   }
16901   Previous.suppressDiagnostics();
16902 
16903   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16904     // Maybe we will complain about the shadowed template parameter.
16905     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16906     // Just pretend that we didn't see the previous declaration.
16907     PrevDecl = nullptr;
16908   }
16909 
16910   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16911     PrevDecl = nullptr;
16912 
16913   bool Mutable
16914     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16915   SourceLocation TSSL = D.getBeginLoc();
16916   FieldDecl *NewFD
16917     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16918                      TSSL, AS, PrevDecl, &D);
16919 
16920   if (NewFD->isInvalidDecl())
16921     Record->setInvalidDecl();
16922 
16923   if (D.getDeclSpec().isModulePrivateSpecified())
16924     NewFD->setModulePrivate();
16925 
16926   if (NewFD->isInvalidDecl() && PrevDecl) {
16927     // Don't introduce NewFD into scope; there's already something
16928     // with the same name in the same scope.
16929   } else if (II) {
16930     PushOnScopeChains(NewFD, S);
16931   } else
16932     Record->addDecl(NewFD);
16933 
16934   return NewFD;
16935 }
16936 
16937 /// Build a new FieldDecl and check its well-formedness.
16938 ///
16939 /// This routine builds a new FieldDecl given the fields name, type,
16940 /// record, etc. \p PrevDecl should refer to any previous declaration
16941 /// with the same name and in the same scope as the field to be
16942 /// created.
16943 ///
16944 /// \returns a new FieldDecl.
16945 ///
16946 /// \todo The Declarator argument is a hack. It will be removed once
16947 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16948                                 TypeSourceInfo *TInfo,
16949                                 RecordDecl *Record, SourceLocation Loc,
16950                                 bool Mutable, Expr *BitWidth,
16951                                 InClassInitStyle InitStyle,
16952                                 SourceLocation TSSL,
16953                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16954                                 Declarator *D) {
16955   IdentifierInfo *II = Name.getAsIdentifierInfo();
16956   bool InvalidDecl = false;
16957   if (D) InvalidDecl = D->isInvalidType();
16958 
16959   // If we receive a broken type, recover by assuming 'int' and
16960   // marking this declaration as invalid.
16961   if (T.isNull() || T->containsErrors()) {
16962     InvalidDecl = true;
16963     T = Context.IntTy;
16964   }
16965 
16966   QualType EltTy = Context.getBaseElementType(T);
16967   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16968     if (RequireCompleteSizedType(Loc, EltTy,
16969                                  diag::err_field_incomplete_or_sizeless)) {
16970       // Fields of incomplete type force their record to be invalid.
16971       Record->setInvalidDecl();
16972       InvalidDecl = true;
16973     } else {
16974       NamedDecl *Def;
16975       EltTy->isIncompleteType(&Def);
16976       if (Def && Def->isInvalidDecl()) {
16977         Record->setInvalidDecl();
16978         InvalidDecl = true;
16979       }
16980     }
16981   }
16982 
16983   // TR 18037 does not allow fields to be declared with address space
16984   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16985       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16986     Diag(Loc, diag::err_field_with_address_space);
16987     Record->setInvalidDecl();
16988     InvalidDecl = true;
16989   }
16990 
16991   if (LangOpts.OpenCL) {
16992     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16993     // used as structure or union field: image, sampler, event or block types.
16994     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16995         T->isBlockPointerType()) {
16996       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16997       Record->setInvalidDecl();
16998       InvalidDecl = true;
16999     }
17000     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17001     // is enabled.
17002     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17003                         "__cl_clang_bitfields", LangOpts)) {
17004       Diag(Loc, diag::err_opencl_bitfields);
17005       InvalidDecl = true;
17006     }
17007   }
17008 
17009   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17010   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17011       T.hasQualifiers()) {
17012     InvalidDecl = true;
17013     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17014   }
17015 
17016   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17017   // than a variably modified type.
17018   if (!InvalidDecl && T->isVariablyModifiedType()) {
17019     if (!tryToFixVariablyModifiedVarType(
17020             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17021       InvalidDecl = true;
17022   }
17023 
17024   // Fields can not have abstract class types
17025   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17026                                              diag::err_abstract_type_in_decl,
17027                                              AbstractFieldType))
17028     InvalidDecl = true;
17029 
17030   bool ZeroWidth = false;
17031   if (InvalidDecl)
17032     BitWidth = nullptr;
17033   // If this is declared as a bit-field, check the bit-field.
17034   if (BitWidth) {
17035     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17036                               &ZeroWidth).get();
17037     if (!BitWidth) {
17038       InvalidDecl = true;
17039       BitWidth = nullptr;
17040       ZeroWidth = false;
17041     }
17042   }
17043 
17044   // Check that 'mutable' is consistent with the type of the declaration.
17045   if (!InvalidDecl && Mutable) {
17046     unsigned DiagID = 0;
17047     if (T->isReferenceType())
17048       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17049                                         : diag::err_mutable_reference;
17050     else if (T.isConstQualified())
17051       DiagID = diag::err_mutable_const;
17052 
17053     if (DiagID) {
17054       SourceLocation ErrLoc = Loc;
17055       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17056         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17057       Diag(ErrLoc, DiagID);
17058       if (DiagID != diag::ext_mutable_reference) {
17059         Mutable = false;
17060         InvalidDecl = true;
17061       }
17062     }
17063   }
17064 
17065   // C++11 [class.union]p8 (DR1460):
17066   //   At most one variant member of a union may have a
17067   //   brace-or-equal-initializer.
17068   if (InitStyle != ICIS_NoInit)
17069     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17070 
17071   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17072                                        BitWidth, Mutable, InitStyle);
17073   if (InvalidDecl)
17074     NewFD->setInvalidDecl();
17075 
17076   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17077     Diag(Loc, diag::err_duplicate_member) << II;
17078     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17079     NewFD->setInvalidDecl();
17080   }
17081 
17082   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17083     if (Record->isUnion()) {
17084       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17085         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17086         if (RDecl->getDefinition()) {
17087           // C++ [class.union]p1: An object of a class with a non-trivial
17088           // constructor, a non-trivial copy constructor, a non-trivial
17089           // destructor, or a non-trivial copy assignment operator
17090           // cannot be a member of a union, nor can an array of such
17091           // objects.
17092           if (CheckNontrivialField(NewFD))
17093             NewFD->setInvalidDecl();
17094         }
17095       }
17096 
17097       // C++ [class.union]p1: If a union contains a member of reference type,
17098       // the program is ill-formed, except when compiling with MSVC extensions
17099       // enabled.
17100       if (EltTy->isReferenceType()) {
17101         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17102                                     diag::ext_union_member_of_reference_type :
17103                                     diag::err_union_member_of_reference_type)
17104           << NewFD->getDeclName() << EltTy;
17105         if (!getLangOpts().MicrosoftExt)
17106           NewFD->setInvalidDecl();
17107       }
17108     }
17109   }
17110 
17111   // FIXME: We need to pass in the attributes given an AST
17112   // representation, not a parser representation.
17113   if (D) {
17114     // FIXME: The current scope is almost... but not entirely... correct here.
17115     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17116 
17117     if (NewFD->hasAttrs())
17118       CheckAlignasUnderalignment(NewFD);
17119   }
17120 
17121   // In auto-retain/release, infer strong retension for fields of
17122   // retainable type.
17123   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17124     NewFD->setInvalidDecl();
17125 
17126   if (T.isObjCGCWeak())
17127     Diag(Loc, diag::warn_attribute_weak_on_field);
17128 
17129   // PPC MMA non-pointer types are not allowed as field types.
17130   if (Context.getTargetInfo().getTriple().isPPC64() &&
17131       CheckPPCMMAType(T, NewFD->getLocation()))
17132     NewFD->setInvalidDecl();
17133 
17134   NewFD->setAccess(AS);
17135   return NewFD;
17136 }
17137 
17138 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17139   assert(FD);
17140   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17141 
17142   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17143     return false;
17144 
17145   QualType EltTy = Context.getBaseElementType(FD->getType());
17146   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17147     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17148     if (RDecl->getDefinition()) {
17149       // We check for copy constructors before constructors
17150       // because otherwise we'll never get complaints about
17151       // copy constructors.
17152 
17153       CXXSpecialMember member = CXXInvalid;
17154       // We're required to check for any non-trivial constructors. Since the
17155       // implicit default constructor is suppressed if there are any
17156       // user-declared constructors, we just need to check that there is a
17157       // trivial default constructor and a trivial copy constructor. (We don't
17158       // worry about move constructors here, since this is a C++98 check.)
17159       if (RDecl->hasNonTrivialCopyConstructor())
17160         member = CXXCopyConstructor;
17161       else if (!RDecl->hasTrivialDefaultConstructor())
17162         member = CXXDefaultConstructor;
17163       else if (RDecl->hasNonTrivialCopyAssignment())
17164         member = CXXCopyAssignment;
17165       else if (RDecl->hasNonTrivialDestructor())
17166         member = CXXDestructor;
17167 
17168       if (member != CXXInvalid) {
17169         if (!getLangOpts().CPlusPlus11 &&
17170             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17171           // Objective-C++ ARC: it is an error to have a non-trivial field of
17172           // a union. However, system headers in Objective-C programs
17173           // occasionally have Objective-C lifetime objects within unions,
17174           // and rather than cause the program to fail, we make those
17175           // members unavailable.
17176           SourceLocation Loc = FD->getLocation();
17177           if (getSourceManager().isInSystemHeader(Loc)) {
17178             if (!FD->hasAttr<UnavailableAttr>())
17179               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17180                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17181             return false;
17182           }
17183         }
17184 
17185         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17186                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17187                diag::err_illegal_union_or_anon_struct_member)
17188           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17189         DiagnoseNontrivial(RDecl, member);
17190         return !getLangOpts().CPlusPlus11;
17191       }
17192     }
17193   }
17194 
17195   return false;
17196 }
17197 
17198 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17199 ///  AST enum value.
17200 static ObjCIvarDecl::AccessControl
17201 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17202   switch (ivarVisibility) {
17203   default: llvm_unreachable("Unknown visitibility kind");
17204   case tok::objc_private: return ObjCIvarDecl::Private;
17205   case tok::objc_public: return ObjCIvarDecl::Public;
17206   case tok::objc_protected: return ObjCIvarDecl::Protected;
17207   case tok::objc_package: return ObjCIvarDecl::Package;
17208   }
17209 }
17210 
17211 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17212 /// in order to create an IvarDecl object for it.
17213 Decl *Sema::ActOnIvar(Scope *S,
17214                                 SourceLocation DeclStart,
17215                                 Declarator &D, Expr *BitfieldWidth,
17216                                 tok::ObjCKeywordKind Visibility) {
17217 
17218   IdentifierInfo *II = D.getIdentifier();
17219   Expr *BitWidth = (Expr*)BitfieldWidth;
17220   SourceLocation Loc = DeclStart;
17221   if (II) Loc = D.getIdentifierLoc();
17222 
17223   // FIXME: Unnamed fields can be handled in various different ways, for
17224   // example, unnamed unions inject all members into the struct namespace!
17225 
17226   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17227   QualType T = TInfo->getType();
17228 
17229   if (BitWidth) {
17230     // 6.7.2.1p3, 6.7.2.1p4
17231     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17232     if (!BitWidth)
17233       D.setInvalidType();
17234   } else {
17235     // Not a bitfield.
17236 
17237     // validate II.
17238 
17239   }
17240   if (T->isReferenceType()) {
17241     Diag(Loc, diag::err_ivar_reference_type);
17242     D.setInvalidType();
17243   }
17244   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17245   // than a variably modified type.
17246   else if (T->isVariablyModifiedType()) {
17247     if (!tryToFixVariablyModifiedVarType(
17248             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17249       D.setInvalidType();
17250   }
17251 
17252   // Get the visibility (access control) for this ivar.
17253   ObjCIvarDecl::AccessControl ac =
17254     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17255                                         : ObjCIvarDecl::None;
17256   // Must set ivar's DeclContext to its enclosing interface.
17257   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17258   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17259     return nullptr;
17260   ObjCContainerDecl *EnclosingContext;
17261   if (ObjCImplementationDecl *IMPDecl =
17262       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17263     if (LangOpts.ObjCRuntime.isFragile()) {
17264     // Case of ivar declared in an implementation. Context is that of its class.
17265       EnclosingContext = IMPDecl->getClassInterface();
17266       assert(EnclosingContext && "Implementation has no class interface!");
17267     }
17268     else
17269       EnclosingContext = EnclosingDecl;
17270   } else {
17271     if (ObjCCategoryDecl *CDecl =
17272         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17273       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17274         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17275         return nullptr;
17276       }
17277     }
17278     EnclosingContext = EnclosingDecl;
17279   }
17280 
17281   // Construct the decl.
17282   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17283                                              DeclStart, Loc, II, T,
17284                                              TInfo, ac, (Expr *)BitfieldWidth);
17285 
17286   if (II) {
17287     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17288                                            ForVisibleRedeclaration);
17289     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17290         && !isa<TagDecl>(PrevDecl)) {
17291       Diag(Loc, diag::err_duplicate_member) << II;
17292       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17293       NewID->setInvalidDecl();
17294     }
17295   }
17296 
17297   // Process attributes attached to the ivar.
17298   ProcessDeclAttributes(S, NewID, D);
17299 
17300   if (D.isInvalidType())
17301     NewID->setInvalidDecl();
17302 
17303   // In ARC, infer 'retaining' for ivars of retainable type.
17304   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17305     NewID->setInvalidDecl();
17306 
17307   if (D.getDeclSpec().isModulePrivateSpecified())
17308     NewID->setModulePrivate();
17309 
17310   if (II) {
17311     // FIXME: When interfaces are DeclContexts, we'll need to add
17312     // these to the interface.
17313     S->AddDecl(NewID);
17314     IdResolver.AddDecl(NewID);
17315   }
17316 
17317   if (LangOpts.ObjCRuntime.isNonFragile() &&
17318       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17319     Diag(Loc, diag::warn_ivars_in_interface);
17320 
17321   return NewID;
17322 }
17323 
17324 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17325 /// class and class extensions. For every class \@interface and class
17326 /// extension \@interface, if the last ivar is a bitfield of any type,
17327 /// then add an implicit `char :0` ivar to the end of that interface.
17328 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17329                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17330   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17331     return;
17332 
17333   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17334   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17335 
17336   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17337     return;
17338   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17339   if (!ID) {
17340     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17341       if (!CD->IsClassExtension())
17342         return;
17343     }
17344     // No need to add this to end of @implementation.
17345     else
17346       return;
17347   }
17348   // All conditions are met. Add a new bitfield to the tail end of ivars.
17349   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17350   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17351 
17352   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17353                               DeclLoc, DeclLoc, nullptr,
17354                               Context.CharTy,
17355                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17356                                                                DeclLoc),
17357                               ObjCIvarDecl::Private, BW,
17358                               true);
17359   AllIvarDecls.push_back(Ivar);
17360 }
17361 
17362 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17363                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17364                        SourceLocation RBrac,
17365                        const ParsedAttributesView &Attrs) {
17366   assert(EnclosingDecl && "missing record or interface decl");
17367 
17368   // If this is an Objective-C @implementation or category and we have
17369   // new fields here we should reset the layout of the interface since
17370   // it will now change.
17371   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17372     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17373     switch (DC->getKind()) {
17374     default: break;
17375     case Decl::ObjCCategory:
17376       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17377       break;
17378     case Decl::ObjCImplementation:
17379       Context.
17380         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17381       break;
17382     }
17383   }
17384 
17385   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17386   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17387 
17388   // Start counting up the number of named members; make sure to include
17389   // members of anonymous structs and unions in the total.
17390   unsigned NumNamedMembers = 0;
17391   if (Record) {
17392     for (const auto *I : Record->decls()) {
17393       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17394         if (IFD->getDeclName())
17395           ++NumNamedMembers;
17396     }
17397   }
17398 
17399   // Verify that all the fields are okay.
17400   SmallVector<FieldDecl*, 32> RecFields;
17401 
17402   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17403        i != end; ++i) {
17404     FieldDecl *FD = cast<FieldDecl>(*i);
17405 
17406     // Get the type for the field.
17407     const Type *FDTy = FD->getType().getTypePtr();
17408 
17409     if (!FD->isAnonymousStructOrUnion()) {
17410       // Remember all fields written by the user.
17411       RecFields.push_back(FD);
17412     }
17413 
17414     // If the field is already invalid for some reason, don't emit more
17415     // diagnostics about it.
17416     if (FD->isInvalidDecl()) {
17417       EnclosingDecl->setInvalidDecl();
17418       continue;
17419     }
17420 
17421     // C99 6.7.2.1p2:
17422     //   A structure or union shall not contain a member with
17423     //   incomplete or function type (hence, a structure shall not
17424     //   contain an instance of itself, but may contain a pointer to
17425     //   an instance of itself), except that the last member of a
17426     //   structure with more than one named member may have incomplete
17427     //   array type; such a structure (and any union containing,
17428     //   possibly recursively, a member that is such a structure)
17429     //   shall not be a member of a structure or an element of an
17430     //   array.
17431     bool IsLastField = (i + 1 == Fields.end());
17432     if (FDTy->isFunctionType()) {
17433       // Field declared as a function.
17434       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17435         << FD->getDeclName();
17436       FD->setInvalidDecl();
17437       EnclosingDecl->setInvalidDecl();
17438       continue;
17439     } else if (FDTy->isIncompleteArrayType() &&
17440                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17441       if (Record) {
17442         // Flexible array member.
17443         // Microsoft and g++ is more permissive regarding flexible array.
17444         // It will accept flexible array in union and also
17445         // as the sole element of a struct/class.
17446         unsigned DiagID = 0;
17447         if (!Record->isUnion() && !IsLastField) {
17448           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17449             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17450           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17451           FD->setInvalidDecl();
17452           EnclosingDecl->setInvalidDecl();
17453           continue;
17454         } else if (Record->isUnion())
17455           DiagID = getLangOpts().MicrosoftExt
17456                        ? diag::ext_flexible_array_union_ms
17457                        : getLangOpts().CPlusPlus
17458                              ? diag::ext_flexible_array_union_gnu
17459                              : diag::err_flexible_array_union;
17460         else if (NumNamedMembers < 1)
17461           DiagID = getLangOpts().MicrosoftExt
17462                        ? diag::ext_flexible_array_empty_aggregate_ms
17463                        : getLangOpts().CPlusPlus
17464                              ? diag::ext_flexible_array_empty_aggregate_gnu
17465                              : diag::err_flexible_array_empty_aggregate;
17466 
17467         if (DiagID)
17468           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17469                                           << Record->getTagKind();
17470         // While the layout of types that contain virtual bases is not specified
17471         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17472         // virtual bases after the derived members.  This would make a flexible
17473         // array member declared at the end of an object not adjacent to the end
17474         // of the type.
17475         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17476           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17477               << FD->getDeclName() << Record->getTagKind();
17478         if (!getLangOpts().C99)
17479           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17480             << FD->getDeclName() << Record->getTagKind();
17481 
17482         // If the element type has a non-trivial destructor, we would not
17483         // implicitly destroy the elements, so disallow it for now.
17484         //
17485         // FIXME: GCC allows this. We should probably either implicitly delete
17486         // the destructor of the containing class, or just allow this.
17487         QualType BaseElem = Context.getBaseElementType(FD->getType());
17488         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17489           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17490             << FD->getDeclName() << FD->getType();
17491           FD->setInvalidDecl();
17492           EnclosingDecl->setInvalidDecl();
17493           continue;
17494         }
17495         // Okay, we have a legal flexible array member at the end of the struct.
17496         Record->setHasFlexibleArrayMember(true);
17497       } else {
17498         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17499         // unless they are followed by another ivar. That check is done
17500         // elsewhere, after synthesized ivars are known.
17501       }
17502     } else if (!FDTy->isDependentType() &&
17503                RequireCompleteSizedType(
17504                    FD->getLocation(), FD->getType(),
17505                    diag::err_field_incomplete_or_sizeless)) {
17506       // Incomplete type
17507       FD->setInvalidDecl();
17508       EnclosingDecl->setInvalidDecl();
17509       continue;
17510     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17511       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17512         // A type which contains a flexible array member is considered to be a
17513         // flexible array member.
17514         Record->setHasFlexibleArrayMember(true);
17515         if (!Record->isUnion()) {
17516           // If this is a struct/class and this is not the last element, reject
17517           // it.  Note that GCC supports variable sized arrays in the middle of
17518           // structures.
17519           if (!IsLastField)
17520             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17521               << FD->getDeclName() << FD->getType();
17522           else {
17523             // We support flexible arrays at the end of structs in
17524             // other structs as an extension.
17525             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17526               << FD->getDeclName();
17527           }
17528         }
17529       }
17530       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17531           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17532                                  diag::err_abstract_type_in_decl,
17533                                  AbstractIvarType)) {
17534         // Ivars can not have abstract class types
17535         FD->setInvalidDecl();
17536       }
17537       if (Record && FDTTy->getDecl()->hasObjectMember())
17538         Record->setHasObjectMember(true);
17539       if (Record && FDTTy->getDecl()->hasVolatileMember())
17540         Record->setHasVolatileMember(true);
17541     } else if (FDTy->isObjCObjectType()) {
17542       /// A field cannot be an Objective-c object
17543       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17544         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17545       QualType T = Context.getObjCObjectPointerType(FD->getType());
17546       FD->setType(T);
17547     } else if (Record && Record->isUnion() &&
17548                FD->getType().hasNonTrivialObjCLifetime() &&
17549                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17550                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17551                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17552                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17553       // For backward compatibility, fields of C unions declared in system
17554       // headers that have non-trivial ObjC ownership qualifications are marked
17555       // as unavailable unless the qualifier is explicit and __strong. This can
17556       // break ABI compatibility between programs compiled with ARC and MRR, but
17557       // is a better option than rejecting programs using those unions under
17558       // ARC.
17559       FD->addAttr(UnavailableAttr::CreateImplicit(
17560           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17561           FD->getLocation()));
17562     } else if (getLangOpts().ObjC &&
17563                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17564                !Record->hasObjectMember()) {
17565       if (FD->getType()->isObjCObjectPointerType() ||
17566           FD->getType().isObjCGCStrong())
17567         Record->setHasObjectMember(true);
17568       else if (Context.getAsArrayType(FD->getType())) {
17569         QualType BaseType = Context.getBaseElementType(FD->getType());
17570         if (BaseType->isRecordType() &&
17571             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17572           Record->setHasObjectMember(true);
17573         else if (BaseType->isObjCObjectPointerType() ||
17574                  BaseType.isObjCGCStrong())
17575                Record->setHasObjectMember(true);
17576       }
17577     }
17578 
17579     if (Record && !getLangOpts().CPlusPlus &&
17580         !shouldIgnoreForRecordTriviality(FD)) {
17581       QualType FT = FD->getType();
17582       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17583         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17584         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17585             Record->isUnion())
17586           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17587       }
17588       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17589       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17590         Record->setNonTrivialToPrimitiveCopy(true);
17591         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17592           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17593       }
17594       if (FT.isDestructedType()) {
17595         Record->setNonTrivialToPrimitiveDestroy(true);
17596         Record->setParamDestroyedInCallee(true);
17597         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17598           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17599       }
17600 
17601       if (const auto *RT = FT->getAs<RecordType>()) {
17602         if (RT->getDecl()->getArgPassingRestrictions() ==
17603             RecordDecl::APK_CanNeverPassInRegs)
17604           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17605       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17606         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17607     }
17608 
17609     if (Record && FD->getType().isVolatileQualified())
17610       Record->setHasVolatileMember(true);
17611     // Keep track of the number of named members.
17612     if (FD->getIdentifier())
17613       ++NumNamedMembers;
17614   }
17615 
17616   // Okay, we successfully defined 'Record'.
17617   if (Record) {
17618     bool Completed = false;
17619     if (CXXRecord) {
17620       if (!CXXRecord->isInvalidDecl()) {
17621         // Set access bits correctly on the directly-declared conversions.
17622         for (CXXRecordDecl::conversion_iterator
17623                I = CXXRecord->conversion_begin(),
17624                E = CXXRecord->conversion_end(); I != E; ++I)
17625           I.setAccess((*I)->getAccess());
17626       }
17627 
17628       // Add any implicitly-declared members to this class.
17629       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17630 
17631       if (!CXXRecord->isDependentType()) {
17632         if (!CXXRecord->isInvalidDecl()) {
17633           // If we have virtual base classes, we may end up finding multiple
17634           // final overriders for a given virtual function. Check for this
17635           // problem now.
17636           if (CXXRecord->getNumVBases()) {
17637             CXXFinalOverriderMap FinalOverriders;
17638             CXXRecord->getFinalOverriders(FinalOverriders);
17639 
17640             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17641                                              MEnd = FinalOverriders.end();
17642                  M != MEnd; ++M) {
17643               for (OverridingMethods::iterator SO = M->second.begin(),
17644                                             SOEnd = M->second.end();
17645                    SO != SOEnd; ++SO) {
17646                 assert(SO->second.size() > 0 &&
17647                        "Virtual function without overriding functions?");
17648                 if (SO->second.size() == 1)
17649                   continue;
17650 
17651                 // C++ [class.virtual]p2:
17652                 //   In a derived class, if a virtual member function of a base
17653                 //   class subobject has more than one final overrider the
17654                 //   program is ill-formed.
17655                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17656                   << (const NamedDecl *)M->first << Record;
17657                 Diag(M->first->getLocation(),
17658                      diag::note_overridden_virtual_function);
17659                 for (OverridingMethods::overriding_iterator
17660                           OM = SO->second.begin(),
17661                        OMEnd = SO->second.end();
17662                      OM != OMEnd; ++OM)
17663                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17664                     << (const NamedDecl *)M->first << OM->Method->getParent();
17665 
17666                 Record->setInvalidDecl();
17667               }
17668             }
17669             CXXRecord->completeDefinition(&FinalOverriders);
17670             Completed = true;
17671           }
17672         }
17673       }
17674     }
17675 
17676     if (!Completed)
17677       Record->completeDefinition();
17678 
17679     // Handle attributes before checking the layout.
17680     ProcessDeclAttributeList(S, Record, Attrs);
17681 
17682     // We may have deferred checking for a deleted destructor. Check now.
17683     if (CXXRecord) {
17684       auto *Dtor = CXXRecord->getDestructor();
17685       if (Dtor && Dtor->isImplicit() &&
17686           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17687         CXXRecord->setImplicitDestructorIsDeleted();
17688         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17689       }
17690     }
17691 
17692     if (Record->hasAttrs()) {
17693       CheckAlignasUnderalignment(Record);
17694 
17695       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17696         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17697                                            IA->getRange(), IA->getBestCase(),
17698                                            IA->getInheritanceModel());
17699     }
17700 
17701     // Check if the structure/union declaration is a type that can have zero
17702     // size in C. For C this is a language extension, for C++ it may cause
17703     // compatibility problems.
17704     bool CheckForZeroSize;
17705     if (!getLangOpts().CPlusPlus) {
17706       CheckForZeroSize = true;
17707     } else {
17708       // For C++ filter out types that cannot be referenced in C code.
17709       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17710       CheckForZeroSize =
17711           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17712           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17713           CXXRecord->isCLike();
17714     }
17715     if (CheckForZeroSize) {
17716       bool ZeroSize = true;
17717       bool IsEmpty = true;
17718       unsigned NonBitFields = 0;
17719       for (RecordDecl::field_iterator I = Record->field_begin(),
17720                                       E = Record->field_end();
17721            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17722         IsEmpty = false;
17723         if (I->isUnnamedBitfield()) {
17724           if (!I->isZeroLengthBitField(Context))
17725             ZeroSize = false;
17726         } else {
17727           ++NonBitFields;
17728           QualType FieldType = I->getType();
17729           if (FieldType->isIncompleteType() ||
17730               !Context.getTypeSizeInChars(FieldType).isZero())
17731             ZeroSize = false;
17732         }
17733       }
17734 
17735       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17736       // allowed in C++, but warn if its declaration is inside
17737       // extern "C" block.
17738       if (ZeroSize) {
17739         Diag(RecLoc, getLangOpts().CPlusPlus ?
17740                          diag::warn_zero_size_struct_union_in_extern_c :
17741                          diag::warn_zero_size_struct_union_compat)
17742           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17743       }
17744 
17745       // Structs without named members are extension in C (C99 6.7.2.1p7),
17746       // but are accepted by GCC.
17747       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17748         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17749                                diag::ext_no_named_members_in_struct_union)
17750           << Record->isUnion();
17751       }
17752     }
17753   } else {
17754     ObjCIvarDecl **ClsFields =
17755       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17756     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17757       ID->setEndOfDefinitionLoc(RBrac);
17758       // Add ivar's to class's DeclContext.
17759       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17760         ClsFields[i]->setLexicalDeclContext(ID);
17761         ID->addDecl(ClsFields[i]);
17762       }
17763       // Must enforce the rule that ivars in the base classes may not be
17764       // duplicates.
17765       if (ID->getSuperClass())
17766         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17767     } else if (ObjCImplementationDecl *IMPDecl =
17768                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17769       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17770       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17771         // Ivar declared in @implementation never belongs to the implementation.
17772         // Only it is in implementation's lexical context.
17773         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17774       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17775       IMPDecl->setIvarLBraceLoc(LBrac);
17776       IMPDecl->setIvarRBraceLoc(RBrac);
17777     } else if (ObjCCategoryDecl *CDecl =
17778                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17779       // case of ivars in class extension; all other cases have been
17780       // reported as errors elsewhere.
17781       // FIXME. Class extension does not have a LocEnd field.
17782       // CDecl->setLocEnd(RBrac);
17783       // Add ivar's to class extension's DeclContext.
17784       // Diagnose redeclaration of private ivars.
17785       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17786       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17787         if (IDecl) {
17788           if (const ObjCIvarDecl *ClsIvar =
17789               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17790             Diag(ClsFields[i]->getLocation(),
17791                  diag::err_duplicate_ivar_declaration);
17792             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17793             continue;
17794           }
17795           for (const auto *Ext : IDecl->known_extensions()) {
17796             if (const ObjCIvarDecl *ClsExtIvar
17797                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17798               Diag(ClsFields[i]->getLocation(),
17799                    diag::err_duplicate_ivar_declaration);
17800               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17801               continue;
17802             }
17803           }
17804         }
17805         ClsFields[i]->setLexicalDeclContext(CDecl);
17806         CDecl->addDecl(ClsFields[i]);
17807       }
17808       CDecl->setIvarLBraceLoc(LBrac);
17809       CDecl->setIvarRBraceLoc(RBrac);
17810     }
17811   }
17812 }
17813 
17814 /// Determine whether the given integral value is representable within
17815 /// the given type T.
17816 static bool isRepresentableIntegerValue(ASTContext &Context,
17817                                         llvm::APSInt &Value,
17818                                         QualType T) {
17819   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17820          "Integral type required!");
17821   unsigned BitWidth = Context.getIntWidth(T);
17822 
17823   if (Value.isUnsigned() || Value.isNonNegative()) {
17824     if (T->isSignedIntegerOrEnumerationType())
17825       --BitWidth;
17826     return Value.getActiveBits() <= BitWidth;
17827   }
17828   return Value.getMinSignedBits() <= BitWidth;
17829 }
17830 
17831 // Given an integral type, return the next larger integral type
17832 // (or a NULL type of no such type exists).
17833 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17834   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17835   // enum checking below.
17836   assert((T->isIntegralType(Context) ||
17837          T->isEnumeralType()) && "Integral type required!");
17838   const unsigned NumTypes = 4;
17839   QualType SignedIntegralTypes[NumTypes] = {
17840     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17841   };
17842   QualType UnsignedIntegralTypes[NumTypes] = {
17843     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17844     Context.UnsignedLongLongTy
17845   };
17846 
17847   unsigned BitWidth = Context.getTypeSize(T);
17848   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17849                                                         : UnsignedIntegralTypes;
17850   for (unsigned I = 0; I != NumTypes; ++I)
17851     if (Context.getTypeSize(Types[I]) > BitWidth)
17852       return Types[I];
17853 
17854   return QualType();
17855 }
17856 
17857 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17858                                           EnumConstantDecl *LastEnumConst,
17859                                           SourceLocation IdLoc,
17860                                           IdentifierInfo *Id,
17861                                           Expr *Val) {
17862   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17863   llvm::APSInt EnumVal(IntWidth);
17864   QualType EltTy;
17865 
17866   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17867     Val = nullptr;
17868 
17869   if (Val)
17870     Val = DefaultLvalueConversion(Val).get();
17871 
17872   if (Val) {
17873     if (Enum->isDependentType() || Val->isTypeDependent() ||
17874         Val->containsErrors())
17875       EltTy = Context.DependentTy;
17876     else {
17877       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17878       // underlying type, but do allow it in all other contexts.
17879       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17880         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17881         // constant-expression in the enumerator-definition shall be a converted
17882         // constant expression of the underlying type.
17883         EltTy = Enum->getIntegerType();
17884         ExprResult Converted =
17885           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17886                                            CCEK_Enumerator);
17887         if (Converted.isInvalid())
17888           Val = nullptr;
17889         else
17890           Val = Converted.get();
17891       } else if (!Val->isValueDependent() &&
17892                  !(Val =
17893                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17894                            .get())) {
17895         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17896       } else {
17897         if (Enum->isComplete()) {
17898           EltTy = Enum->getIntegerType();
17899 
17900           // In Obj-C and Microsoft mode, require the enumeration value to be
17901           // representable in the underlying type of the enumeration. In C++11,
17902           // we perform a non-narrowing conversion as part of converted constant
17903           // expression checking.
17904           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17905             if (Context.getTargetInfo()
17906                     .getTriple()
17907                     .isWindowsMSVCEnvironment()) {
17908               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17909             } else {
17910               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17911             }
17912           }
17913 
17914           // Cast to the underlying type.
17915           Val = ImpCastExprToType(Val, EltTy,
17916                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17917                                                          : CK_IntegralCast)
17918                     .get();
17919         } else if (getLangOpts().CPlusPlus) {
17920           // C++11 [dcl.enum]p5:
17921           //   If the underlying type is not fixed, the type of each enumerator
17922           //   is the type of its initializing value:
17923           //     - If an initializer is specified for an enumerator, the
17924           //       initializing value has the same type as the expression.
17925           EltTy = Val->getType();
17926         } else {
17927           // C99 6.7.2.2p2:
17928           //   The expression that defines the value of an enumeration constant
17929           //   shall be an integer constant expression that has a value
17930           //   representable as an int.
17931 
17932           // Complain if the value is not representable in an int.
17933           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17934             Diag(IdLoc, diag::ext_enum_value_not_int)
17935               << toString(EnumVal, 10) << Val->getSourceRange()
17936               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17937           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17938             // Force the type of the expression to 'int'.
17939             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17940           }
17941           EltTy = Val->getType();
17942         }
17943       }
17944     }
17945   }
17946 
17947   if (!Val) {
17948     if (Enum->isDependentType())
17949       EltTy = Context.DependentTy;
17950     else if (!LastEnumConst) {
17951       // C++0x [dcl.enum]p5:
17952       //   If the underlying type is not fixed, the type of each enumerator
17953       //   is the type of its initializing value:
17954       //     - If no initializer is specified for the first enumerator, the
17955       //       initializing value has an unspecified integral type.
17956       //
17957       // GCC uses 'int' for its unspecified integral type, as does
17958       // C99 6.7.2.2p3.
17959       if (Enum->isFixed()) {
17960         EltTy = Enum->getIntegerType();
17961       }
17962       else {
17963         EltTy = Context.IntTy;
17964       }
17965     } else {
17966       // Assign the last value + 1.
17967       EnumVal = LastEnumConst->getInitVal();
17968       ++EnumVal;
17969       EltTy = LastEnumConst->getType();
17970 
17971       // Check for overflow on increment.
17972       if (EnumVal < LastEnumConst->getInitVal()) {
17973         // C++0x [dcl.enum]p5:
17974         //   If the underlying type is not fixed, the type of each enumerator
17975         //   is the type of its initializing value:
17976         //
17977         //     - Otherwise the type of the initializing value is the same as
17978         //       the type of the initializing value of the preceding enumerator
17979         //       unless the incremented value is not representable in that type,
17980         //       in which case the type is an unspecified integral type
17981         //       sufficient to contain the incremented value. If no such type
17982         //       exists, the program is ill-formed.
17983         QualType T = getNextLargerIntegralType(Context, EltTy);
17984         if (T.isNull() || Enum->isFixed()) {
17985           // There is no integral type larger enough to represent this
17986           // value. Complain, then allow the value to wrap around.
17987           EnumVal = LastEnumConst->getInitVal();
17988           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17989           ++EnumVal;
17990           if (Enum->isFixed())
17991             // When the underlying type is fixed, this is ill-formed.
17992             Diag(IdLoc, diag::err_enumerator_wrapped)
17993               << toString(EnumVal, 10)
17994               << EltTy;
17995           else
17996             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17997               << toString(EnumVal, 10);
17998         } else {
17999           EltTy = T;
18000         }
18001 
18002         // Retrieve the last enumerator's value, extent that type to the
18003         // type that is supposed to be large enough to represent the incremented
18004         // value, then increment.
18005         EnumVal = LastEnumConst->getInitVal();
18006         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18007         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18008         ++EnumVal;
18009 
18010         // If we're not in C++, diagnose the overflow of enumerator values,
18011         // which in C99 means that the enumerator value is not representable in
18012         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18013         // permits enumerator values that are representable in some larger
18014         // integral type.
18015         if (!getLangOpts().CPlusPlus && !T.isNull())
18016           Diag(IdLoc, diag::warn_enum_value_overflow);
18017       } else if (!getLangOpts().CPlusPlus &&
18018                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18019         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18020         Diag(IdLoc, diag::ext_enum_value_not_int)
18021           << toString(EnumVal, 10) << 1;
18022       }
18023     }
18024   }
18025 
18026   if (!EltTy->isDependentType()) {
18027     // Make the enumerator value match the signedness and size of the
18028     // enumerator's type.
18029     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18030     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18031   }
18032 
18033   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18034                                   Val, EnumVal);
18035 }
18036 
18037 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18038                                                 SourceLocation IILoc) {
18039   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18040       !getLangOpts().CPlusPlus)
18041     return SkipBodyInfo();
18042 
18043   // We have an anonymous enum definition. Look up the first enumerator to
18044   // determine if we should merge the definition with an existing one and
18045   // skip the body.
18046   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18047                                          forRedeclarationInCurContext());
18048   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18049   if (!PrevECD)
18050     return SkipBodyInfo();
18051 
18052   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18053   NamedDecl *Hidden;
18054   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18055     SkipBodyInfo Skip;
18056     Skip.Previous = Hidden;
18057     return Skip;
18058   }
18059 
18060   return SkipBodyInfo();
18061 }
18062 
18063 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18064                               SourceLocation IdLoc, IdentifierInfo *Id,
18065                               const ParsedAttributesView &Attrs,
18066                               SourceLocation EqualLoc, Expr *Val) {
18067   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18068   EnumConstantDecl *LastEnumConst =
18069     cast_or_null<EnumConstantDecl>(lastEnumConst);
18070 
18071   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18072   // we find one that is.
18073   S = getNonFieldDeclScope(S);
18074 
18075   // Verify that there isn't already something declared with this name in this
18076   // scope.
18077   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18078   LookupName(R, S);
18079   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18080 
18081   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18082     // Maybe we will complain about the shadowed template parameter.
18083     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18084     // Just pretend that we didn't see the previous declaration.
18085     PrevDecl = nullptr;
18086   }
18087 
18088   // C++ [class.mem]p15:
18089   // If T is the name of a class, then each of the following shall have a name
18090   // different from T:
18091   // - every enumerator of every member of class T that is an unscoped
18092   // enumerated type
18093   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18094     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18095                             DeclarationNameInfo(Id, IdLoc));
18096 
18097   EnumConstantDecl *New =
18098     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18099   if (!New)
18100     return nullptr;
18101 
18102   if (PrevDecl) {
18103     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18104       // Check for other kinds of shadowing not already handled.
18105       CheckShadow(New, PrevDecl, R);
18106     }
18107 
18108     // When in C++, we may get a TagDecl with the same name; in this case the
18109     // enum constant will 'hide' the tag.
18110     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18111            "Received TagDecl when not in C++!");
18112     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18113       if (isa<EnumConstantDecl>(PrevDecl))
18114         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18115       else
18116         Diag(IdLoc, diag::err_redefinition) << Id;
18117       notePreviousDefinition(PrevDecl, IdLoc);
18118       return nullptr;
18119     }
18120   }
18121 
18122   // Process attributes.
18123   ProcessDeclAttributeList(S, New, Attrs);
18124   AddPragmaAttributes(S, New);
18125 
18126   // Register this decl in the current scope stack.
18127   New->setAccess(TheEnumDecl->getAccess());
18128   PushOnScopeChains(New, S);
18129 
18130   ActOnDocumentableDecl(New);
18131 
18132   return New;
18133 }
18134 
18135 // Returns true when the enum initial expression does not trigger the
18136 // duplicate enum warning.  A few common cases are exempted as follows:
18137 // Element2 = Element1
18138 // Element2 = Element1 + 1
18139 // Element2 = Element1 - 1
18140 // Where Element2 and Element1 are from the same enum.
18141 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18142   Expr *InitExpr = ECD->getInitExpr();
18143   if (!InitExpr)
18144     return true;
18145   InitExpr = InitExpr->IgnoreImpCasts();
18146 
18147   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18148     if (!BO->isAdditiveOp())
18149       return true;
18150     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18151     if (!IL)
18152       return true;
18153     if (IL->getValue() != 1)
18154       return true;
18155 
18156     InitExpr = BO->getLHS();
18157   }
18158 
18159   // This checks if the elements are from the same enum.
18160   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18161   if (!DRE)
18162     return true;
18163 
18164   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18165   if (!EnumConstant)
18166     return true;
18167 
18168   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18169       Enum)
18170     return true;
18171 
18172   return false;
18173 }
18174 
18175 // Emits a warning when an element is implicitly set a value that
18176 // a previous element has already been set to.
18177 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18178                                         EnumDecl *Enum, QualType EnumType) {
18179   // Avoid anonymous enums
18180   if (!Enum->getIdentifier())
18181     return;
18182 
18183   // Only check for small enums.
18184   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18185     return;
18186 
18187   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18188     return;
18189 
18190   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18191   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18192 
18193   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18194 
18195   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18196   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18197 
18198   // Use int64_t as a key to avoid needing special handling for map keys.
18199   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18200     llvm::APSInt Val = D->getInitVal();
18201     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18202   };
18203 
18204   DuplicatesVector DupVector;
18205   ValueToVectorMap EnumMap;
18206 
18207   // Populate the EnumMap with all values represented by enum constants without
18208   // an initializer.
18209   for (auto *Element : Elements) {
18210     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18211 
18212     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18213     // this constant.  Skip this enum since it may be ill-formed.
18214     if (!ECD) {
18215       return;
18216     }
18217 
18218     // Constants with initalizers are handled in the next loop.
18219     if (ECD->getInitExpr())
18220       continue;
18221 
18222     // Duplicate values are handled in the next loop.
18223     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18224   }
18225 
18226   if (EnumMap.size() == 0)
18227     return;
18228 
18229   // Create vectors for any values that has duplicates.
18230   for (auto *Element : Elements) {
18231     // The last loop returned if any constant was null.
18232     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18233     if (!ValidDuplicateEnum(ECD, Enum))
18234       continue;
18235 
18236     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18237     if (Iter == EnumMap.end())
18238       continue;
18239 
18240     DeclOrVector& Entry = Iter->second;
18241     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18242       // Ensure constants are different.
18243       if (D == ECD)
18244         continue;
18245 
18246       // Create new vector and push values onto it.
18247       auto Vec = std::make_unique<ECDVector>();
18248       Vec->push_back(D);
18249       Vec->push_back(ECD);
18250 
18251       // Update entry to point to the duplicates vector.
18252       Entry = Vec.get();
18253 
18254       // Store the vector somewhere we can consult later for quick emission of
18255       // diagnostics.
18256       DupVector.emplace_back(std::move(Vec));
18257       continue;
18258     }
18259 
18260     ECDVector *Vec = Entry.get<ECDVector*>();
18261     // Make sure constants are not added more than once.
18262     if (*Vec->begin() == ECD)
18263       continue;
18264 
18265     Vec->push_back(ECD);
18266   }
18267 
18268   // Emit diagnostics.
18269   for (const auto &Vec : DupVector) {
18270     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18271 
18272     // Emit warning for one enum constant.
18273     auto *FirstECD = Vec->front();
18274     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18275       << FirstECD << toString(FirstECD->getInitVal(), 10)
18276       << FirstECD->getSourceRange();
18277 
18278     // Emit one note for each of the remaining enum constants with
18279     // the same value.
18280     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18281       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18282         << ECD << toString(ECD->getInitVal(), 10)
18283         << ECD->getSourceRange();
18284   }
18285 }
18286 
18287 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18288                              bool AllowMask) const {
18289   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18290   assert(ED->isCompleteDefinition() && "expected enum definition");
18291 
18292   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18293   llvm::APInt &FlagBits = R.first->second;
18294 
18295   if (R.second) {
18296     for (auto *E : ED->enumerators()) {
18297       const auto &EVal = E->getInitVal();
18298       // Only single-bit enumerators introduce new flag values.
18299       if (EVal.isPowerOf2())
18300         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18301     }
18302   }
18303 
18304   // A value is in a flag enum if either its bits are a subset of the enum's
18305   // flag bits (the first condition) or we are allowing masks and the same is
18306   // true of its complement (the second condition). When masks are allowed, we
18307   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18308   //
18309   // While it's true that any value could be used as a mask, the assumption is
18310   // that a mask will have all of the insignificant bits set. Anything else is
18311   // likely a logic error.
18312   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18313   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18314 }
18315 
18316 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18317                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18318                          const ParsedAttributesView &Attrs) {
18319   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18320   QualType EnumType = Context.getTypeDeclType(Enum);
18321 
18322   ProcessDeclAttributeList(S, Enum, Attrs);
18323 
18324   if (Enum->isDependentType()) {
18325     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18326       EnumConstantDecl *ECD =
18327         cast_or_null<EnumConstantDecl>(Elements[i]);
18328       if (!ECD) continue;
18329 
18330       ECD->setType(EnumType);
18331     }
18332 
18333     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18334     return;
18335   }
18336 
18337   // TODO: If the result value doesn't fit in an int, it must be a long or long
18338   // long value.  ISO C does not support this, but GCC does as an extension,
18339   // emit a warning.
18340   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18341   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18342   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18343 
18344   // Verify that all the values are okay, compute the size of the values, and
18345   // reverse the list.
18346   unsigned NumNegativeBits = 0;
18347   unsigned NumPositiveBits = 0;
18348 
18349   // Keep track of whether all elements have type int.
18350   bool AllElementsInt = true;
18351 
18352   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18353     EnumConstantDecl *ECD =
18354       cast_or_null<EnumConstantDecl>(Elements[i]);
18355     if (!ECD) continue;  // Already issued a diagnostic.
18356 
18357     const llvm::APSInt &InitVal = ECD->getInitVal();
18358 
18359     // Keep track of the size of positive and negative values.
18360     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18361       NumPositiveBits = std::max(NumPositiveBits,
18362                                  (unsigned)InitVal.getActiveBits());
18363     else
18364       NumNegativeBits = std::max(NumNegativeBits,
18365                                  (unsigned)InitVal.getMinSignedBits());
18366 
18367     // Keep track of whether every enum element has type int (very common).
18368     if (AllElementsInt)
18369       AllElementsInt = ECD->getType() == Context.IntTy;
18370   }
18371 
18372   // Figure out the type that should be used for this enum.
18373   QualType BestType;
18374   unsigned BestWidth;
18375 
18376   // C++0x N3000 [conv.prom]p3:
18377   //   An rvalue of an unscoped enumeration type whose underlying
18378   //   type is not fixed can be converted to an rvalue of the first
18379   //   of the following types that can represent all the values of
18380   //   the enumeration: int, unsigned int, long int, unsigned long
18381   //   int, long long int, or unsigned long long int.
18382   // C99 6.4.4.3p2:
18383   //   An identifier declared as an enumeration constant has type int.
18384   // The C99 rule is modified by a gcc extension
18385   QualType BestPromotionType;
18386 
18387   bool Packed = Enum->hasAttr<PackedAttr>();
18388   // -fshort-enums is the equivalent to specifying the packed attribute on all
18389   // enum definitions.
18390   if (LangOpts.ShortEnums)
18391     Packed = true;
18392 
18393   // If the enum already has a type because it is fixed or dictated by the
18394   // target, promote that type instead of analyzing the enumerators.
18395   if (Enum->isComplete()) {
18396     BestType = Enum->getIntegerType();
18397     if (BestType->isPromotableIntegerType())
18398       BestPromotionType = Context.getPromotedIntegerType(BestType);
18399     else
18400       BestPromotionType = BestType;
18401 
18402     BestWidth = Context.getIntWidth(BestType);
18403   }
18404   else if (NumNegativeBits) {
18405     // If there is a negative value, figure out the smallest integer type (of
18406     // int/long/longlong) that fits.
18407     // If it's packed, check also if it fits a char or a short.
18408     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18409       BestType = Context.SignedCharTy;
18410       BestWidth = CharWidth;
18411     } else if (Packed && NumNegativeBits <= ShortWidth &&
18412                NumPositiveBits < ShortWidth) {
18413       BestType = Context.ShortTy;
18414       BestWidth = ShortWidth;
18415     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18416       BestType = Context.IntTy;
18417       BestWidth = IntWidth;
18418     } else {
18419       BestWidth = Context.getTargetInfo().getLongWidth();
18420 
18421       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18422         BestType = Context.LongTy;
18423       } else {
18424         BestWidth = Context.getTargetInfo().getLongLongWidth();
18425 
18426         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18427           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18428         BestType = Context.LongLongTy;
18429       }
18430     }
18431     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18432   } else {
18433     // If there is no negative value, figure out the smallest type that fits
18434     // all of the enumerator values.
18435     // If it's packed, check also if it fits a char or a short.
18436     if (Packed && NumPositiveBits <= CharWidth) {
18437       BestType = Context.UnsignedCharTy;
18438       BestPromotionType = Context.IntTy;
18439       BestWidth = CharWidth;
18440     } else if (Packed && NumPositiveBits <= ShortWidth) {
18441       BestType = Context.UnsignedShortTy;
18442       BestPromotionType = Context.IntTy;
18443       BestWidth = ShortWidth;
18444     } else if (NumPositiveBits <= IntWidth) {
18445       BestType = Context.UnsignedIntTy;
18446       BestWidth = IntWidth;
18447       BestPromotionType
18448         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18449                            ? Context.UnsignedIntTy : Context.IntTy;
18450     } else if (NumPositiveBits <=
18451                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18452       BestType = Context.UnsignedLongTy;
18453       BestPromotionType
18454         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18455                            ? Context.UnsignedLongTy : Context.LongTy;
18456     } else {
18457       BestWidth = Context.getTargetInfo().getLongLongWidth();
18458       assert(NumPositiveBits <= BestWidth &&
18459              "How could an initializer get larger than ULL?");
18460       BestType = Context.UnsignedLongLongTy;
18461       BestPromotionType
18462         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18463                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18464     }
18465   }
18466 
18467   // Loop over all of the enumerator constants, changing their types to match
18468   // the type of the enum if needed.
18469   for (auto *D : Elements) {
18470     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18471     if (!ECD) continue;  // Already issued a diagnostic.
18472 
18473     // Standard C says the enumerators have int type, but we allow, as an
18474     // extension, the enumerators to be larger than int size.  If each
18475     // enumerator value fits in an int, type it as an int, otherwise type it the
18476     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18477     // that X has type 'int', not 'unsigned'.
18478 
18479     // Determine whether the value fits into an int.
18480     llvm::APSInt InitVal = ECD->getInitVal();
18481 
18482     // If it fits into an integer type, force it.  Otherwise force it to match
18483     // the enum decl type.
18484     QualType NewTy;
18485     unsigned NewWidth;
18486     bool NewSign;
18487     if (!getLangOpts().CPlusPlus &&
18488         !Enum->isFixed() &&
18489         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18490       NewTy = Context.IntTy;
18491       NewWidth = IntWidth;
18492       NewSign = true;
18493     } else if (ECD->getType() == BestType) {
18494       // Already the right type!
18495       if (getLangOpts().CPlusPlus)
18496         // C++ [dcl.enum]p4: Following the closing brace of an
18497         // enum-specifier, each enumerator has the type of its
18498         // enumeration.
18499         ECD->setType(EnumType);
18500       continue;
18501     } else {
18502       NewTy = BestType;
18503       NewWidth = BestWidth;
18504       NewSign = BestType->isSignedIntegerOrEnumerationType();
18505     }
18506 
18507     // Adjust the APSInt value.
18508     InitVal = InitVal.extOrTrunc(NewWidth);
18509     InitVal.setIsSigned(NewSign);
18510     ECD->setInitVal(InitVal);
18511 
18512     // Adjust the Expr initializer and type.
18513     if (ECD->getInitExpr() &&
18514         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18515       ECD->setInitExpr(ImplicitCastExpr::Create(
18516           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18517           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18518     if (getLangOpts().CPlusPlus)
18519       // C++ [dcl.enum]p4: Following the closing brace of an
18520       // enum-specifier, each enumerator has the type of its
18521       // enumeration.
18522       ECD->setType(EnumType);
18523     else
18524       ECD->setType(NewTy);
18525   }
18526 
18527   Enum->completeDefinition(BestType, BestPromotionType,
18528                            NumPositiveBits, NumNegativeBits);
18529 
18530   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18531 
18532   if (Enum->isClosedFlag()) {
18533     for (Decl *D : Elements) {
18534       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18535       if (!ECD) continue;  // Already issued a diagnostic.
18536 
18537       llvm::APSInt InitVal = ECD->getInitVal();
18538       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18539           !IsValueInFlagEnum(Enum, InitVal, true))
18540         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18541           << ECD << Enum;
18542     }
18543   }
18544 
18545   // Now that the enum type is defined, ensure it's not been underaligned.
18546   if (Enum->hasAttrs())
18547     CheckAlignasUnderalignment(Enum);
18548 }
18549 
18550 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18551                                   SourceLocation StartLoc,
18552                                   SourceLocation EndLoc) {
18553   StringLiteral *AsmString = cast<StringLiteral>(expr);
18554 
18555   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18556                                                    AsmString, StartLoc,
18557                                                    EndLoc);
18558   CurContext->addDecl(New);
18559   return New;
18560 }
18561 
18562 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18563                                       IdentifierInfo* AliasName,
18564                                       SourceLocation PragmaLoc,
18565                                       SourceLocation NameLoc,
18566                                       SourceLocation AliasNameLoc) {
18567   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18568                                          LookupOrdinaryName);
18569   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18570                            AttributeCommonInfo::AS_Pragma);
18571   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18572       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18573 
18574   // If a declaration that:
18575   // 1) declares a function or a variable
18576   // 2) has external linkage
18577   // already exists, add a label attribute to it.
18578   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18579     if (isDeclExternC(PrevDecl))
18580       PrevDecl->addAttr(Attr);
18581     else
18582       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18583           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18584   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18585   } else
18586     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18587 }
18588 
18589 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18590                              SourceLocation PragmaLoc,
18591                              SourceLocation NameLoc) {
18592   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18593 
18594   if (PrevDecl) {
18595     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18596   } else {
18597     (void)WeakUndeclaredIdentifiers.insert(
18598       std::pair<IdentifierInfo*,WeakInfo>
18599         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18600   }
18601 }
18602 
18603 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18604                                 IdentifierInfo* AliasName,
18605                                 SourceLocation PragmaLoc,
18606                                 SourceLocation NameLoc,
18607                                 SourceLocation AliasNameLoc) {
18608   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18609                                     LookupOrdinaryName);
18610   WeakInfo W = WeakInfo(Name, NameLoc);
18611 
18612   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18613     if (!PrevDecl->hasAttr<AliasAttr>())
18614       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18615         DeclApplyPragmaWeak(TUScope, ND, W);
18616   } else {
18617     (void)WeakUndeclaredIdentifiers.insert(
18618       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18619   }
18620 }
18621 
18622 Decl *Sema::getObjCDeclContext() const {
18623   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18624 }
18625 
18626 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18627                                                      bool Final) {
18628   assert(FD && "Expected non-null FunctionDecl");
18629 
18630   // SYCL functions can be template, so we check if they have appropriate
18631   // attribute prior to checking if it is a template.
18632   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18633     return FunctionEmissionStatus::Emitted;
18634 
18635   // Templates are emitted when they're instantiated.
18636   if (FD->isDependentContext())
18637     return FunctionEmissionStatus::TemplateDiscarded;
18638 
18639   // Check whether this function is an externally visible definition.
18640   auto IsEmittedForExternalSymbol = [this, FD]() {
18641     // We have to check the GVA linkage of the function's *definition* -- if we
18642     // only have a declaration, we don't know whether or not the function will
18643     // be emitted, because (say) the definition could include "inline".
18644     FunctionDecl *Def = FD->getDefinition();
18645 
18646     return Def && !isDiscardableGVALinkage(
18647                       getASTContext().GetGVALinkageForFunction(Def));
18648   };
18649 
18650   if (LangOpts.OpenMPIsDevice) {
18651     // In OpenMP device mode we will not emit host only functions, or functions
18652     // we don't need due to their linkage.
18653     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18654         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18655     // DevTy may be changed later by
18656     //  #pragma omp declare target to(*) device_type(*).
18657     // Therefore DevTy having no value does not imply host. The emission status
18658     // will be checked again at the end of compilation unit with Final = true.
18659     if (DevTy.hasValue())
18660       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18661         return FunctionEmissionStatus::OMPDiscarded;
18662     // If we have an explicit value for the device type, or we are in a target
18663     // declare context, we need to emit all extern and used symbols.
18664     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18665       if (IsEmittedForExternalSymbol())
18666         return FunctionEmissionStatus::Emitted;
18667     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18668     // we'll omit it.
18669     if (Final)
18670       return FunctionEmissionStatus::OMPDiscarded;
18671   } else if (LangOpts.OpenMP > 45) {
18672     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18673     // function. In 5.0, no_host was introduced which might cause a function to
18674     // be ommitted.
18675     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18676         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18677     if (DevTy.hasValue())
18678       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18679         return FunctionEmissionStatus::OMPDiscarded;
18680   }
18681 
18682   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18683     return FunctionEmissionStatus::Emitted;
18684 
18685   if (LangOpts.CUDA) {
18686     // When compiling for device, host functions are never emitted.  Similarly,
18687     // when compiling for host, device and global functions are never emitted.
18688     // (Technically, we do emit a host-side stub for global functions, but this
18689     // doesn't count for our purposes here.)
18690     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18691     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18692       return FunctionEmissionStatus::CUDADiscarded;
18693     if (!LangOpts.CUDAIsDevice &&
18694         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18695       return FunctionEmissionStatus::CUDADiscarded;
18696 
18697     if (IsEmittedForExternalSymbol())
18698       return FunctionEmissionStatus::Emitted;
18699   }
18700 
18701   // Otherwise, the function is known-emitted if it's in our set of
18702   // known-emitted functions.
18703   return FunctionEmissionStatus::Unknown;
18704 }
18705 
18706 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18707   // Host-side references to a __global__ function refer to the stub, so the
18708   // function itself is never emitted and therefore should not be marked.
18709   // If we have host fn calls kernel fn calls host+device, the HD function
18710   // does not get instantiated on the host. We model this by omitting at the
18711   // call to the kernel from the callgraph. This ensures that, when compiling
18712   // for host, only HD functions actually called from the host get marked as
18713   // known-emitted.
18714   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18715          IdentifyCUDATarget(Callee) == CFT_Global;
18716 }
18717