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_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439               RealRes) ||
440           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
441         if (!IIDecl ||
442             // Make the selection of the recovery decl deterministic.
443             RealRes->getLocation() < IIDecl->getLocation())
444           IIDecl = RealRes;
445       }
446     }
447 
448     if (!IIDecl) {
449       // None of the entities we found is a type, so there is no way
450       // to even assume that the result is a type. In this case, don't
451       // complain about the ambiguity. The parser will either try to
452       // perform this lookup again (e.g., as an object name), which
453       // will produce the ambiguity, or will complain that it expected
454       // a type name.
455       Result.suppressDiagnostics();
456       return nullptr;
457     }
458 
459     // We found a type within the ambiguous lookup; diagnose the
460     // ambiguity and then return that type. This might be the right
461     // answer, or it might not be, but it suppresses any attempt to
462     // perform the name lookup again.
463     break;
464 
465   case LookupResult::Found:
466     IIDecl = Result.getFoundDecl();
467     break;
468   }
469 
470   assert(IIDecl && "Didn't find decl");
471 
472   QualType T;
473   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474     // C++ [class.qual]p2: A lookup that would find the injected-class-name
475     // instead names the constructors of the class, except when naming a class.
476     // This is ill-formed when we're not actually forming a ctor or dtor name.
477     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
480         FoundRD->isInjectedClassName() &&
481         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
482       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483           << &II << /*Type*/1;
484 
485     DiagnoseUseOfDecl(IIDecl, NameLoc);
486 
487     T = Context.getTypeDeclType(TD);
488     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491     if (!HasTrailingDot)
492       T = Context.getObjCInterfaceType(IDecl);
493   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494     (void)DiagnoseUseOfDecl(UD, NameLoc);
495     // Recover with 'int'
496     T = Context.IntTy;
497   } else if (AllowDeducedTemplate) {
498     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500                                                        QualType(), false);
501   }
502 
503   if (T.isNull()) {
504     // If it's not plausibly a type, suppress diagnostics.
505     Result.suppressDiagnostics();
506     return nullptr;
507   }
508 
509   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510   // constructor or destructor name (in such a case, the scope specifier
511   // will be attached to the enclosing Expr or Decl node).
512   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
513       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
514     if (WantNontrivialTypeSourceInfo) {
515       // Construct a type with type-source information.
516       TypeLocBuilder Builder;
517       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518 
519       T = getElaboratedType(ETK_None, *SS, T);
520       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521       ElabTL.setElaboratedKeywordLoc(SourceLocation());
522       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524     } else {
525       T = getElaboratedType(ETK_None, *SS, T);
526     }
527   }
528 
529   return ParsedType::make(T);
530 }
531 
532 // Builds a fake NNS for the given decl context.
533 static NestedNameSpecifier *
534 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535   for (;; DC = DC->getLookupParent()) {
536     DC = DC->getPrimaryContext();
537     auto *ND = dyn_cast<NamespaceDecl>(DC);
538     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
539       return NestedNameSpecifier::Create(Context, nullptr, ND);
540     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542                                          RD->getTypeForDecl());
543     else if (isa<TranslationUnitDecl>(DC))
544       return NestedNameSpecifier::GlobalSpecifier(Context);
545   }
546   llvm_unreachable("something isn't in TU scope?");
547 }
548 
549 /// Find the parent class with dependent bases of the innermost enclosing method
550 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551 /// up allowing unqualified dependent type names at class-level, which MSVC
552 /// correctly rejects.
553 static const CXXRecordDecl *
554 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
556     DC = DC->getPrimaryContext();
557     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558       if (MD->getParent()->hasAnyDependentBases())
559         return MD->getParent();
560   }
561   return nullptr;
562 }
563 
564 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565                                           SourceLocation NameLoc,
566                                           bool IsTemplateTypeArg) {
567   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
568 
569   NestedNameSpecifier *NNS = nullptr;
570   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
571     // If we weren't able to parse a default template argument, delay lookup
572     // until instantiation time by making a non-dependent DependentTypeName. We
573     // pretend we saw a NestedNameSpecifier referring to the current scope, and
574     // lookup is retried.
575     // FIXME: This hurts our diagnostic quality, since we get errors like "no
576     // type named 'Foo' in 'current_namespace'" when the user didn't write any
577     // name specifiers.
578     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580   } else if (const CXXRecordDecl *RD =
581                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582     // Build a DependentNameType that will perform lookup into RD at
583     // instantiation time.
584     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585                                       RD->getTypeForDecl());
586 
587     // Diagnose that this identifier was undeclared, and retry the lookup during
588     // template instantiation.
589     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590                                                                       << RD;
591   } else {
592     // This is not a situation that we should recover from.
593     return ParsedType();
594   }
595 
596   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597 
598   // Build type location information.  We synthesized the qualifier, so we have
599   // to build a fake NestedNameSpecifierLoc.
600   NestedNameSpecifierLocBuilder NNSLocBuilder;
601   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603 
604   TypeLocBuilder Builder;
605   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606   DepTL.setNameLoc(NameLoc);
607   DepTL.setElaboratedKeywordLoc(SourceLocation());
608   DepTL.setQualifierLoc(QualifierLoc);
609   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610 }
611 
612 /// isTagName() - This method is called *for error recovery purposes only*
613 /// to determine if the specified name is a valid tag name ("struct foo").  If
614 /// so, this returns the TST for the tag corresponding to it (TST_enum,
615 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
616 /// cases in C where the user forgot to specify the tag.
617 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618   // Do a tag name lookup in this scope.
619   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620   LookupName(R, S, false);
621   R.suppressDiagnostics();
622   if (R.getResultKind() == LookupResult::Found)
623     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624       switch (TD->getTagKind()) {
625       case TTK_Struct: return DeclSpec::TST_struct;
626       case TTK_Interface: return DeclSpec::TST_interface;
627       case TTK_Union:  return DeclSpec::TST_union;
628       case TTK_Class:  return DeclSpec::TST_class;
629       case TTK_Enum:   return DeclSpec::TST_enum;
630       }
631     }
632 
633   return DeclSpec::TST_unspecified;
634 }
635 
636 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
638 /// then downgrade the missing typename error to a warning.
639 /// This is needed for MSVC compatibility; Example:
640 /// @code
641 /// template<class T> class A {
642 /// public:
643 ///   typedef int TYPE;
644 /// };
645 /// template<class T> class B : public A<T> {
646 /// public:
647 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
648 /// };
649 /// @endcode
650 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651   if (CurContext->isRecord()) {
652     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653       return true;
654 
655     const Type *Ty = SS->getScopeRep()->getAsType();
656 
657     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658     for (const auto &Base : RD->bases())
659       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
660         return true;
661     return S->isFunctionPrototypeScope();
662   }
663   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
664 }
665 
666 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667                                    SourceLocation IILoc,
668                                    Scope *S,
669                                    CXXScopeSpec *SS,
670                                    ParsedType &SuggestedType,
671                                    bool IsTemplateName) {
672   // Don't report typename errors for editor placeholders.
673   if (II->isEditorPlaceholder())
674     return;
675   // We don't have anything to suggest (yet).
676   SuggestedType = nullptr;
677 
678   // There may have been a typo in the name of the type. Look up typo
679   // results, in case we have something that we can suggest.
680   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681                            /*AllowTemplates=*/IsTemplateName,
682                            /*AllowNonTemplates=*/!IsTemplateName);
683   if (TypoCorrection Corrected =
684           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685                       CCC, CTK_ErrorRecovery)) {
686     // FIXME: Support error recovery for the template-name case.
687     bool CanRecover = !IsTemplateName;
688     if (Corrected.isKeyword()) {
689       // We corrected to a keyword.
690       diagnoseTypo(Corrected,
691                    PDiag(IsTemplateName ? diag::err_no_template_suggest
692                                         : diag::err_unknown_typename_suggest)
693                        << II);
694       II = Corrected.getCorrectionAsIdentifierInfo();
695     } else {
696       // We found a similarly-named type or interface; suggest that.
697       if (!SS || !SS->isSet()) {
698         diagnoseTypo(Corrected,
699                      PDiag(IsTemplateName ? diag::err_no_template_suggest
700                                           : diag::err_unknown_typename_suggest)
701                          << II, CanRecover);
702       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
703         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705                                 II->getName().equals(CorrectedStr);
706         diagnoseTypo(Corrected,
707                      PDiag(IsTemplateName
708                                ? diag::err_no_member_template_suggest
709                                : diag::err_unknown_nested_typename_suggest)
710                          << II << DC << DroppedSpecifier << SS->getRange(),
711                      CanRecover);
712       } else {
713         llvm_unreachable("could not have corrected a typo here");
714       }
715 
716       if (!CanRecover)
717         return;
718 
719       CXXScopeSpec tmpSS;
720       if (Corrected.getCorrectionSpecifier())
721         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722                           SourceRange(IILoc));
723       // FIXME: Support class template argument deduction here.
724       SuggestedType =
725           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
727                       /*IsCtorOrDtorName=*/false,
728                       /*WantNontrivialTypeSourceInfo=*/true);
729     }
730     return;
731   }
732 
733   if (getLangOpts().CPlusPlus && !IsTemplateName) {
734     // See if II is a class template that the user forgot to pass arguments to.
735     UnqualifiedId Name;
736     Name.setIdentifier(II, IILoc);
737     CXXScopeSpec EmptySS;
738     TemplateTy TemplateResult;
739     bool MemberOfUnknownSpecialization;
740     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
741                        Name, nullptr, true, TemplateResult,
742                        MemberOfUnknownSpecialization) == TNK_Type_template) {
743       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744       return;
745     }
746   }
747 
748   // FIXME: Should we move the logic that tries to recover from a missing tag
749   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750 
751   if (!SS || (!SS->isSet() && !SS->isInvalid()))
752     Diag(IILoc, IsTemplateName ? diag::err_no_template
753                                : diag::err_unknown_typename)
754         << II;
755   else if (DeclContext *DC = computeDeclContext(*SS, false))
756     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
757                                : diag::err_typename_nested_not_found)
758         << II << DC << SS->getRange();
759   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
760     SuggestedType =
761         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762   } else if (isDependentScopeSpecifier(*SS)) {
763     unsigned DiagID = diag::err_typename_missing;
764     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
765       DiagID = diag::ext_typename_missing;
766 
767     Diag(SS->getRange().getBegin(), DiagID)
768       << SS->getScopeRep() << II->getName()
769       << SourceRange(SS->getRange().getBegin(), IILoc)
770       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771     SuggestedType = ActOnTypenameType(S, SourceLocation(),
772                                       *SS, *II, IILoc).get();
773   } else {
774     assert(SS && SS->isInvalid() &&
775            "Invalid scope specifier has already been diagnosed");
776   }
777 }
778 
779 /// Determine whether the given result set contains either a type name
780 /// or
781 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783                        NextToken.is(tok::less);
784 
785   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
786     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
787       return true;
788 
789     if (CheckTemplate && isa<TemplateDecl>(*I))
790       return true;
791   }
792 
793   return false;
794 }
795 
796 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797                                     Scope *S, CXXScopeSpec &SS,
798                                     IdentifierInfo *&Name,
799                                     SourceLocation NameLoc) {
800   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801   SemaRef.LookupParsedName(R, S, &SS);
802   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803     StringRef FixItTagName;
804     switch (Tag->getTagKind()) {
805       case TTK_Class:
806         FixItTagName = "class ";
807         break;
808 
809       case TTK_Enum:
810         FixItTagName = "enum ";
811         break;
812 
813       case TTK_Struct:
814         FixItTagName = "struct ";
815         break;
816 
817       case TTK_Interface:
818         FixItTagName = "__interface ";
819         break;
820 
821       case TTK_Union:
822         FixItTagName = "union ";
823         break;
824     }
825 
826     StringRef TagName = FixItTagName.drop_back();
827     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830 
831     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832          I != IEnd; ++I)
833       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834         << Name << TagName;
835 
836     // Replace lookup results with just the tag decl.
837     Result.clear(Sema::LookupTagName);
838     SemaRef.LookupParsedName(Result, S, &SS);
839     return true;
840   }
841 
842   return false;
843 }
844 
845 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847                                   QualType T, SourceLocation NameLoc) {
848   ASTContext &Context = S.Context;
849 
850   TypeLocBuilder Builder;
851   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852 
853   T = S.getElaboratedType(ETK_None, SS, T);
854   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855   ElabTL.setElaboratedKeywordLoc(SourceLocation());
856   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
858 }
859 
860 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861                                             IdentifierInfo *&Name,
862                                             SourceLocation NameLoc,
863                                             const Token &NextToken,
864                                             CorrectionCandidateCallback *CCC) {
865   DeclarationNameInfo NameInfo(Name, NameLoc);
866   ObjCMethodDecl *CurMethod = getCurMethodDecl();
867 
868   assert(NextToken.isNot(tok::coloncolon) &&
869          "parse nested name specifiers before calling ClassifyName");
870   if (getLangOpts().CPlusPlus && SS.isSet() &&
871       isCurrentClassName(*Name, S, &SS)) {
872     // Per [class.qual]p2, this names the constructors of SS, not the
873     // injected-class-name. We don't have a classification for that.
874     // There's not much point caching this result, since the parser
875     // will reject it later.
876     return NameClassification::Unknown();
877   }
878 
879   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880   LookupParsedName(Result, S, &SS, !CurMethod);
881 
882   if (SS.isInvalid())
883     return NameClassification::Error();
884 
885   // For unqualified lookup in a class template in MSVC mode, look into
886   // dependent base classes where the primary class template is known.
887   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888     if (ParsedType TypeInBase =
889             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890       return TypeInBase;
891   }
892 
893   // Perform lookup for Objective-C instance variables (including automatically
894   // synthesized instance variables), if we're in an Objective-C method.
895   // FIXME: This lookup really, really needs to be folded in to the normal
896   // unqualified lookup mechanism.
897   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899     if (Ivar.isInvalid())
900       return NameClassification::Error();
901     if (Ivar.isUsable())
902       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903 
904     // We defer builtin creation until after ivar lookup inside ObjC methods.
905     if (Result.empty())
906       LookupBuiltin(Result);
907   }
908 
909   bool SecondTry = false;
910   bool IsFilteredTemplateName = false;
911 
912 Corrected:
913   switch (Result.getResultKind()) {
914   case LookupResult::NotFound:
915     // If an unqualified-id is followed by a '(', then we have a function
916     // call.
917     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918       // In C++, this is an ADL-only call.
919       // FIXME: Reference?
920       if (getLangOpts().CPlusPlus)
921         return NameClassification::UndeclaredNonType();
922 
923       // C90 6.3.2.2:
924       //   If the expression that precedes the parenthesized argument list in a
925       //   function call consists solely of an identifier, and if no
926       //   declaration is visible for this identifier, the identifier is
927       //   implicitly declared exactly as if, in the innermost block containing
928       //   the function call, the declaration
929       //
930       //     extern int identifier ();
931       //
932       //   appeared.
933       //
934       // We also allow this in C99 as an extension.
935       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936         return NameClassification::NonType(D);
937     }
938 
939     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
940       // In C++20 onwards, this could be an ADL-only call to a function
941       // template, and we're required to assume that this is a template name.
942       //
943       // FIXME: Find a way to still do typo correction in this case.
944       TemplateName Template =
945           Context.getAssumedTemplateName(NameInfo.getName());
946       return NameClassification::UndeclaredTemplate(Template);
947     }
948 
949     // In C, we first see whether there is a tag type by the same name, in
950     // which case it's likely that the user just forgot to write "enum",
951     // "struct", or "union".
952     if (!getLangOpts().CPlusPlus && !SecondTry &&
953         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
954       break;
955     }
956 
957     // Perform typo correction to determine if there is another name that is
958     // close to this name.
959     if (!SecondTry && CCC) {
960       SecondTry = true;
961       if (TypoCorrection Corrected =
962               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963                           &SS, *CCC, CTK_ErrorRecovery)) {
964         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965         unsigned QualifiedDiag = diag::err_no_member_suggest;
966 
967         NamedDecl *FirstDecl = Corrected.getFoundDecl();
968         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
970             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
971           UnqualifiedDiag = diag::err_no_template_suggest;
972           QualifiedDiag = diag::err_no_member_template_suggest;
973         } else if (UnderlyingFirstDecl &&
974                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
975                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
976                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
977           UnqualifiedDiag = diag::err_unknown_typename_suggest;
978           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979         }
980 
981         if (SS.isEmpty()) {
982           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983         } else {// FIXME: is this even reachable? Test it.
984           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986                                   Name->getName().equals(CorrectedStr);
987           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988                                     << Name << computeDeclContext(SS, false)
989                                     << DroppedSpecifier << SS.getRange());
990         }
991 
992         // Update the name, so that the caller has the new name.
993         Name = Corrected.getCorrectionAsIdentifierInfo();
994 
995         // Typo correction corrected to a keyword.
996         if (Corrected.isKeyword())
997           return Name;
998 
999         // Also update the LookupResult...
1000         // FIXME: This should probably go away at some point
1001         Result.clear();
1002         Result.setLookupName(Corrected.getCorrection());
1003         if (FirstDecl)
1004           Result.addDecl(FirstDecl);
1005 
1006         // If we found an Objective-C instance variable, let
1007         // LookupInObjCMethod build the appropriate expression to
1008         // reference the ivar.
1009         // FIXME: This is a gross hack.
1010         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011           DeclResult R =
1012               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013           if (R.isInvalid())
1014             return NameClassification::Error();
1015           if (R.isUsable())
1016             return NameClassification::NonType(Ivar);
1017         }
1018 
1019         goto Corrected;
1020       }
1021     }
1022 
1023     // We failed to correct; just fall through and let the parser deal with it.
1024     Result.suppressDiagnostics();
1025     return NameClassification::Unknown();
1026 
1027   case LookupResult::NotFoundInCurrentInstantiation: {
1028     // We performed name lookup into the current instantiation, and there were
1029     // dependent bases, so we treat this result the same way as any other
1030     // dependent nested-name-specifier.
1031 
1032     // C++ [temp.res]p2:
1033     //   A name used in a template declaration or definition and that is
1034     //   dependent on a template-parameter is assumed not to name a type
1035     //   unless the applicable name lookup finds a type name or the name is
1036     //   qualified by the keyword typename.
1037     //
1038     // FIXME: If the next token is '<', we might want to ask the parser to
1039     // perform some heroics to see if we actually have a
1040     // template-argument-list, which would indicate a missing 'template'
1041     // keyword here.
1042     return NameClassification::DependentNonType();
1043   }
1044 
1045   case LookupResult::Found:
1046   case LookupResult::FoundOverloaded:
1047   case LookupResult::FoundUnresolvedValue:
1048     break;
1049 
1050   case LookupResult::Ambiguous:
1051     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1052         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053                                       /*AllowDependent=*/false)) {
1054       // C++ [temp.local]p3:
1055       //   A lookup that finds an injected-class-name (10.2) can result in an
1056       //   ambiguity in certain cases (for example, if it is found in more than
1057       //   one base class). If all of the injected-class-names that are found
1058       //   refer to specializations of the same class template, and if the name
1059       //   is followed by a template-argument-list, the reference refers to the
1060       //   class template itself and not a specialization thereof, and is not
1061       //   ambiguous.
1062       //
1063       // This filtering can make an ambiguous result into an unambiguous one,
1064       // so try again after filtering out template names.
1065       FilterAcceptableTemplateNames(Result);
1066       if (!Result.isAmbiguous()) {
1067         IsFilteredTemplateName = true;
1068         break;
1069       }
1070     }
1071 
1072     // Diagnose the ambiguity and return an error.
1073     return NameClassification::Error();
1074   }
1075 
1076   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077       (IsFilteredTemplateName ||
1078        hasAnyAcceptableTemplateNames(
1079            Result, /*AllowFunctionTemplates=*/true,
1080            /*AllowDependent=*/false,
1081            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082                getLangOpts().CPlusPlus20))) {
1083     // C++ [temp.names]p3:
1084     //   After name lookup (3.4) finds that a name is a template-name or that
1085     //   an operator-function-id or a literal- operator-id refers to a set of
1086     //   overloaded functions any member of which is a function template if
1087     //   this is followed by a <, the < is always taken as the delimiter of a
1088     //   template-argument-list and never as the less-than operator.
1089     // C++2a [temp.names]p2:
1090     //   A name is also considered to refer to a template if it is an
1091     //   unqualified-id followed by a < and name lookup finds either one
1092     //   or more functions or finds nothing.
1093     if (!IsFilteredTemplateName)
1094       FilterAcceptableTemplateNames(Result);
1095 
1096     bool IsFunctionTemplate;
1097     bool IsVarTemplate;
1098     TemplateName Template;
1099     if (Result.end() - Result.begin() > 1) {
1100       IsFunctionTemplate = true;
1101       Template = Context.getOverloadedTemplateName(Result.begin(),
1102                                                    Result.end());
1103     } else if (!Result.empty()) {
1104       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105           *Result.begin(), /*AllowFunctionTemplates=*/true,
1106           /*AllowDependent=*/false));
1107       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108       IsVarTemplate = isa<VarTemplateDecl>(TD);
1109 
1110       if (SS.isNotEmpty())
1111         Template =
1112             Context.getQualifiedTemplateName(SS.getScopeRep(),
1113                                              /*TemplateKeyword=*/false, TD);
1114       else
1115         Template = TemplateName(TD);
1116     } else {
1117       // All results were non-template functions. This is a function template
1118       // name.
1119       IsFunctionTemplate = true;
1120       Template = Context.getAssumedTemplateName(NameInfo.getName());
1121     }
1122 
1123     if (IsFunctionTemplate) {
1124       // Function templates always go through overload resolution, at which
1125       // point we'll perform the various checks (e.g., accessibility) we need
1126       // to based on which function we selected.
1127       Result.suppressDiagnostics();
1128 
1129       return NameClassification::FunctionTemplate(Template);
1130     }
1131 
1132     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133                          : NameClassification::TypeTemplate(Template);
1134   }
1135 
1136   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138     DiagnoseUseOfDecl(Type, NameLoc);
1139     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140     QualType T = Context.getTypeDeclType(Type);
1141     if (SS.isNotEmpty())
1142       return buildNestedType(*this, SS, T, NameLoc);
1143     return ParsedType::make(T);
1144   }
1145 
1146   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147   if (!Class) {
1148     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149     if (ObjCCompatibleAliasDecl *Alias =
1150             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151       Class = Alias->getClassInterface();
1152   }
1153 
1154   if (Class) {
1155     DiagnoseUseOfDecl(Class, NameLoc);
1156 
1157     if (NextToken.is(tok::period)) {
1158       // Interface. <something> is parsed as a property reference expression.
1159       // Just return "unknown" as a fall-through for now.
1160       Result.suppressDiagnostics();
1161       return NameClassification::Unknown();
1162     }
1163 
1164     QualType T = Context.getObjCInterfaceType(Class);
1165     return ParsedType::make(T);
1166   }
1167 
1168   if (isa<ConceptDecl>(FirstDecl))
1169     return NameClassification::Concept(
1170         TemplateName(cast<TemplateDecl>(FirstDecl)));
1171 
1172   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174     return NameClassification::Error();
1175   }
1176 
1177   // We can have a type template here if we're classifying a template argument.
1178   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1179       !isa<VarTemplateDecl>(FirstDecl))
1180     return NameClassification::TypeTemplate(
1181         TemplateName(cast<TemplateDecl>(FirstDecl)));
1182 
1183   // Check for a tag type hidden by a non-type decl in a few cases where it
1184   // seems likely a type is wanted instead of the non-type that was found.
1185   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186   if ((NextToken.is(tok::identifier) ||
1187        (NextIsOp &&
1188         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1189       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1190     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191     DiagnoseUseOfDecl(Type, NameLoc);
1192     QualType T = Context.getTypeDeclType(Type);
1193     if (SS.isNotEmpty())
1194       return buildNestedType(*this, SS, T, NameLoc);
1195     return ParsedType::make(T);
1196   }
1197 
1198   // If we already know which single declaration is referenced, just annotate
1199   // that declaration directly. Defer resolving even non-overloaded class
1200   // member accesses, as we need to defer certain access checks until we know
1201   // the context.
1202   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1204     return NameClassification::NonType(Result.getRepresentativeDecl());
1205 
1206   // Otherwise, this is an overload set that we will need to resolve later.
1207   Result.suppressDiagnostics();
1208   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211       Result.begin(), Result.end()));
1212 }
1213 
1214 ExprResult
1215 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216                                              SourceLocation NameLoc) {
1217   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1218   CXXScopeSpec SS;
1219   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221 }
1222 
1223 ExprResult
1224 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225                                             IdentifierInfo *Name,
1226                                             SourceLocation NameLoc,
1227                                             bool IsAddressOfOperand) {
1228   DeclarationNameInfo NameInfo(Name, NameLoc);
1229   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230                                     NameInfo, IsAddressOfOperand,
1231                                     /*TemplateArgs=*/nullptr);
1232 }
1233 
1234 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235                                               NamedDecl *Found,
1236                                               SourceLocation NameLoc,
1237                                               const Token &NextToken) {
1238   if (getCurMethodDecl() && SS.isEmpty())
1239     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240       return BuildIvarRefExpr(S, NameLoc, Ivar);
1241 
1242   // Reconstruct the lookup result.
1243   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244   Result.addDecl(Found);
1245   Result.resolveKind();
1246 
1247   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248   return BuildDeclarationNameExpr(SS, Result, ADL);
1249 }
1250 
1251 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252   // For an implicit class member access, transform the result into a member
1253   // access expression if necessary.
1254   auto *ULE = cast<UnresolvedLookupExpr>(E);
1255   if ((*ULE->decls_begin())->isCXXClassMember()) {
1256     CXXScopeSpec SS;
1257     SS.Adopt(ULE->getQualifierLoc());
1258 
1259     // Reconstruct the lookup result.
1260     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261                         LookupOrdinaryName);
1262     Result.setNamingClass(ULE->getNamingClass());
1263     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1264       Result.addDecl(*I, I.getAccess());
1265     Result.resolveKind();
1266     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267                                            nullptr, S);
1268   }
1269 
1270   // Otherwise, this is already in the form we needed, and no further checks
1271   // are necessary.
1272   return ULE;
1273 }
1274 
1275 Sema::TemplateNameKindForDiagnostics
1276 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277   auto *TD = Name.getAsTemplateDecl();
1278   if (!TD)
1279     return TemplateNameKindForDiagnostics::DependentTemplate;
1280   if (isa<ClassTemplateDecl>(TD))
1281     return TemplateNameKindForDiagnostics::ClassTemplate;
1282   if (isa<FunctionTemplateDecl>(TD))
1283     return TemplateNameKindForDiagnostics::FunctionTemplate;
1284   if (isa<VarTemplateDecl>(TD))
1285     return TemplateNameKindForDiagnostics::VarTemplate;
1286   if (isa<TypeAliasTemplateDecl>(TD))
1287     return TemplateNameKindForDiagnostics::AliasTemplate;
1288   if (isa<TemplateTemplateParmDecl>(TD))
1289     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290   if (isa<ConceptDecl>(TD))
1291     return TemplateNameKindForDiagnostics::Concept;
1292   return TemplateNameKindForDiagnostics::DependentTemplate;
1293 }
1294 
1295 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296   assert(DC->getLexicalParent() == CurContext &&
1297       "The next DeclContext should be lexically contained in the current one.");
1298   CurContext = DC;
1299   S->setEntity(DC);
1300 }
1301 
1302 void Sema::PopDeclContext() {
1303   assert(CurContext && "DeclContext imbalance!");
1304 
1305   CurContext = CurContext->getLexicalParent();
1306   assert(CurContext && "Popped translation unit!");
1307 }
1308 
1309 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310                                                                     Decl *D) {
1311   // Unlike PushDeclContext, the context to which we return is not necessarily
1312   // the containing DC of TD, because the new context will be some pre-existing
1313   // TagDecl definition instead of a fresh one.
1314   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315   CurContext = cast<TagDecl>(D)->getDefinition();
1316   assert(CurContext && "skipping definition of undefined tag");
1317   // Start lookups from the parent of the current context; we don't want to look
1318   // into the pre-existing complete definition.
1319   S->setEntity(CurContext->getLookupParent());
1320   return Result;
1321 }
1322 
1323 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324   CurContext = static_cast<decltype(CurContext)>(Context);
1325 }
1326 
1327 /// EnterDeclaratorContext - Used when we must lookup names in the context
1328 /// of a declarator's nested name specifier.
1329 ///
1330 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331   // C++0x [basic.lookup.unqual]p13:
1332   //   A name used in the definition of a static data member of class
1333   //   X (after the qualified-id of the static member) is looked up as
1334   //   if the name was used in a member function of X.
1335   // C++0x [basic.lookup.unqual]p14:
1336   //   If a variable member of a namespace is defined outside of the
1337   //   scope of its namespace then any name used in the definition of
1338   //   the variable member (after the declarator-id) is looked up as
1339   //   if the definition of the variable member occurred in its
1340   //   namespace.
1341   // Both of these imply that we should push a scope whose context
1342   // is the semantic context of the declaration.  We can't use
1343   // PushDeclContext here because that context is not necessarily
1344   // lexically contained in the current context.  Fortunately,
1345   // the containing scope should have the appropriate information.
1346 
1347   assert(!S->getEntity() && "scope already has entity");
1348 
1349 #ifndef NDEBUG
1350   Scope *Ancestor = S->getParent();
1351   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1352   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1353 #endif
1354 
1355   CurContext = DC;
1356   S->setEntity(DC);
1357 
1358   if (S->getParent()->isTemplateParamScope()) {
1359     // Also set the corresponding entities for all immediately-enclosing
1360     // template parameter scopes.
1361     EnterTemplatedContext(S->getParent(), DC);
1362   }
1363 }
1364 
1365 void Sema::ExitDeclaratorContext(Scope *S) {
1366   assert(S->getEntity() == CurContext && "Context imbalance!");
1367 
1368   // Switch back to the lexical context.  The safety of this is
1369   // enforced by an assert in EnterDeclaratorContext.
1370   Scope *Ancestor = S->getParent();
1371   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372   CurContext = Ancestor->getEntity();
1373 
1374   // We don't need to do anything with the scope, which is going to
1375   // disappear.
1376 }
1377 
1378 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379   assert(S->isTemplateParamScope() &&
1380          "expected to be initializing a template parameter scope");
1381 
1382   // C++20 [temp.local]p7:
1383   //   In the definition of a member of a class template that appears outside
1384   //   of the class template definition, the name of a member of the class
1385   //   template hides the name of a template-parameter of any enclosing class
1386   //   templates (but not a template-parameter of the member if the member is a
1387   //   class or function template).
1388   // C++20 [temp.local]p9:
1389   //   In the definition of a class template or in the definition of a member
1390   //   of such a template that appears outside of the template definition, for
1391   //   each non-dependent base class (13.8.2.1), if the name of the base class
1392   //   or the name of a member of the base class is the same as the name of a
1393   //   template-parameter, the base class name or member name hides the
1394   //   template-parameter name (6.4.10).
1395   //
1396   // This means that a template parameter scope should be searched immediately
1397   // after searching the DeclContext for which it is a template parameter
1398   // scope. For example, for
1399   //   template<typename T> template<typename U> template<typename V>
1400   //     void N::A<T>::B<U>::f(...)
1401   // we search V then B<U> (and base classes) then U then A<T> (and base
1402   // classes) then T then N then ::.
1403   unsigned ScopeDepth = getTemplateDepth(S);
1404   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1405     DeclContext *SearchDCAfterScope = DC;
1406     for (; DC; DC = DC->getLookupParent()) {
1407       if (const TemplateParameterList *TPL =
1408               cast<Decl>(DC)->getDescribedTemplateParams()) {
1409         unsigned DCDepth = TPL->getDepth() + 1;
1410         if (DCDepth > ScopeDepth)
1411           continue;
1412         if (ScopeDepth == DCDepth)
1413           SearchDCAfterScope = DC = DC->getLookupParent();
1414         break;
1415       }
1416     }
1417     S->setLookupEntity(SearchDCAfterScope);
1418   }
1419 }
1420 
1421 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422   // We assume that the caller has already called
1423   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424   FunctionDecl *FD = D->getAsFunction();
1425   if (!FD)
1426     return;
1427 
1428   // Same implementation as PushDeclContext, but enters the context
1429   // from the lexical parent, rather than the top-level class.
1430   assert(CurContext == FD->getLexicalParent() &&
1431     "The next DeclContext should be lexically contained in the current one.");
1432   CurContext = FD;
1433   S->setEntity(CurContext);
1434 
1435   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1436     ParmVarDecl *Param = FD->getParamDecl(P);
1437     // If the parameter has an identifier, then add it to the scope
1438     if (Param->getIdentifier()) {
1439       S->AddDecl(Param);
1440       IdResolver.AddDecl(Param);
1441     }
1442   }
1443 }
1444 
1445 void Sema::ActOnExitFunctionContext() {
1446   // Same implementation as PopDeclContext, but returns to the lexical parent,
1447   // rather than the top-level class.
1448   assert(CurContext && "DeclContext imbalance!");
1449   CurContext = CurContext->getLexicalParent();
1450   assert(CurContext && "Popped translation unit!");
1451 }
1452 
1453 /// Determine whether we allow overloading of the function
1454 /// PrevDecl with another declaration.
1455 ///
1456 /// This routine determines whether overloading is possible, not
1457 /// whether some new function is actually an overload. It will return
1458 /// true in C++ (where we can always provide overloads) or, as an
1459 /// extension, in C when the previous function is already an
1460 /// overloaded function declaration or has the "overloadable"
1461 /// attribute.
1462 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463                                        ASTContext &Context,
1464                                        const FunctionDecl *New) {
1465   if (Context.getLangOpts().CPlusPlus)
1466     return true;
1467 
1468   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469     return true;
1470 
1471   return Previous.getResultKind() == LookupResult::Found &&
1472          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1473           New->hasAttr<OverloadableAttr>());
1474 }
1475 
1476 /// Add this decl to the scope shadowed decl chains.
1477 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478   // Move up the scope chain until we find the nearest enclosing
1479   // non-transparent context. The declaration will be introduced into this
1480   // scope.
1481   while (S->getEntity() && S->getEntity()->isTransparentContext())
1482     S = S->getParent();
1483 
1484   // Add scoped declarations into their context, so that they can be
1485   // found later. Declarations without a context won't be inserted
1486   // into any context.
1487   if (AddToContext)
1488     CurContext->addDecl(D);
1489 
1490   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491   // are function-local declarations.
1492   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1493     return;
1494 
1495   // Template instantiations should also not be pushed into scope.
1496   if (isa<FunctionDecl>(D) &&
1497       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1498     return;
1499 
1500   // If this replaces anything in the current scope,
1501   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502                                IEnd = IdResolver.end();
1503   for (; I != IEnd; ++I) {
1504     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1505       S->RemoveDecl(*I);
1506       IdResolver.RemoveDecl(*I);
1507 
1508       // Should only need to replace one decl.
1509       break;
1510     }
1511   }
1512 
1513   S->AddDecl(D);
1514 
1515   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1516     // Implicitly-generated labels may end up getting generated in an order that
1517     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518     // the label at the appropriate place in the identifier chain.
1519     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1520       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521       if (IDC == CurContext) {
1522         if (!S->isDeclScope(*I))
1523           continue;
1524       } else if (IDC->Encloses(CurContext))
1525         break;
1526     }
1527 
1528     IdResolver.InsertDeclAfter(I, D);
1529   } else {
1530     IdResolver.AddDecl(D);
1531   }
1532   warnOnReservedIdentifier(D);
1533 }
1534 
1535 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536                          bool AllowInlineNamespace) {
1537   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538 }
1539 
1540 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541   DeclContext *TargetDC = DC->getPrimaryContext();
1542   do {
1543     if (DeclContext *ScopeDC = S->getEntity())
1544       if (ScopeDC->getPrimaryContext() == TargetDC)
1545         return S;
1546   } while ((S = S->getParent()));
1547 
1548   return nullptr;
1549 }
1550 
1551 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552                                             DeclContext*,
1553                                             ASTContext&);
1554 
1555 /// Filters out lookup results that don't fall within the given scope
1556 /// as determined by isDeclInScope.
1557 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558                                 bool ConsiderLinkage,
1559                                 bool AllowInlineNamespace) {
1560   LookupResult::Filter F = R.makeFilter();
1561   while (F.hasNext()) {
1562     NamedDecl *D = F.next();
1563 
1564     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565       continue;
1566 
1567     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1568       continue;
1569 
1570     F.erase();
1571   }
1572 
1573   F.done();
1574 }
1575 
1576 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1577 /// have compatible owning modules.
1578 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579   // FIXME: The Modules TS is not clear about how friend declarations are
1580   // to be treated. It's not meaningful to have different owning modules for
1581   // linkage in redeclarations of the same entity, so for now allow the
1582   // redeclaration and change the owning modules to match.
1583   if (New->getFriendObjectKind() &&
1584       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1585     New->setLocalOwningModule(Old->getOwningModule());
1586     makeMergedDefinitionVisible(New);
1587     return false;
1588   }
1589 
1590   Module *NewM = New->getOwningModule();
1591   Module *OldM = Old->getOwningModule();
1592 
1593   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1594     NewM = NewM->Parent;
1595   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1596     OldM = OldM->Parent;
1597 
1598   if (NewM == OldM)
1599     return false;
1600 
1601   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1602   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1603   if (NewIsModuleInterface || OldIsModuleInterface) {
1604     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605     //   if a declaration of D [...] appears in the purview of a module, all
1606     //   other such declarations shall appear in the purview of the same module
1607     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608       << New
1609       << NewIsModuleInterface
1610       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1611       << OldIsModuleInterface
1612       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1613     Diag(Old->getLocation(), diag::note_previous_declaration);
1614     New->setInvalidDecl();
1615     return true;
1616   }
1617 
1618   return false;
1619 }
1620 
1621 static bool isUsingDecl(NamedDecl *D) {
1622   return isa<UsingShadowDecl>(D) ||
1623          isa<UnresolvedUsingTypenameDecl>(D) ||
1624          isa<UnresolvedUsingValueDecl>(D);
1625 }
1626 
1627 /// Removes using shadow declarations from the lookup results.
1628 static void RemoveUsingDecls(LookupResult &R) {
1629   LookupResult::Filter F = R.makeFilter();
1630   while (F.hasNext())
1631     if (isUsingDecl(F.next()))
1632       F.erase();
1633 
1634   F.done();
1635 }
1636 
1637 /// Check for this common pattern:
1638 /// @code
1639 /// class S {
1640 ///   S(const S&); // DO NOT IMPLEMENT
1641 ///   void operator=(const S&); // DO NOT IMPLEMENT
1642 /// };
1643 /// @endcode
1644 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645   // FIXME: Should check for private access too but access is set after we get
1646   // the decl here.
1647   if (D->doesThisDeclarationHaveABody())
1648     return false;
1649 
1650   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651     return CD->isCopyConstructor();
1652   return D->isCopyAssignmentOperator();
1653 }
1654 
1655 // We need this to handle
1656 //
1657 // typedef struct {
1658 //   void *foo() { return 0; }
1659 // } A;
1660 //
1661 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662 // for example. If 'A', foo will have external linkage. If we have '*A',
1663 // foo will have no linkage. Since we can't know until we get to the end
1664 // of the typedef, this function finds out if D might have non-external linkage.
1665 // Callers should verify at the end of the TU if it D has external linkage or
1666 // not.
1667 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668   const DeclContext *DC = D->getDeclContext();
1669   while (!DC->isTranslationUnit()) {
1670     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671       if (!RD->hasNameForLinkage())
1672         return true;
1673     }
1674     DC = DC->getParent();
1675   }
1676 
1677   return !D->isExternallyVisible();
1678 }
1679 
1680 // FIXME: This needs to be refactored; some other isInMainFile users want
1681 // these semantics.
1682 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683   if (S.TUKind != TU_Complete)
1684     return false;
1685   return S.SourceMgr.isInMainFile(Loc);
1686 }
1687 
1688 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689   assert(D);
1690 
1691   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1692     return false;
1693 
1694   // Ignore all entities declared within templates, and out-of-line definitions
1695   // of members of class templates.
1696   if (D->getDeclContext()->isDependentContext() ||
1697       D->getLexicalDeclContext()->isDependentContext())
1698     return false;
1699 
1700   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702       return false;
1703     // A non-out-of-line declaration of a member specialization was implicitly
1704     // instantiated; it's the out-of-line declaration that we're interested in.
1705     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1707       return false;
1708 
1709     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1711         return false;
1712     } else {
1713       // 'static inline' functions are defined in headers; don't warn.
1714       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1715         return false;
1716     }
1717 
1718     if (FD->doesThisDeclarationHaveABody() &&
1719         Context.DeclMustBeEmitted(FD))
1720       return false;
1721   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1722     // Constants and utility variables are defined in headers with internal
1723     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1724     // like "inline".)
1725     if (!isMainFileLoc(*this, VD->getLocation()))
1726       return false;
1727 
1728     if (Context.DeclMustBeEmitted(VD))
1729       return false;
1730 
1731     if (VD->isStaticDataMember() &&
1732         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1733       return false;
1734     if (VD->isStaticDataMember() &&
1735         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1736         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1737       return false;
1738 
1739     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1740       return false;
1741   } else {
1742     return false;
1743   }
1744 
1745   // Only warn for unused decls internal to the translation unit.
1746   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747   // for inline functions defined in the main source file, for instance.
1748   return mightHaveNonExternalLinkage(D);
1749 }
1750 
1751 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752   if (!D)
1753     return;
1754 
1755   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756     const FunctionDecl *First = FD->getFirstDecl();
1757     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1758       return; // First should already be in the vector.
1759   }
1760 
1761   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762     const VarDecl *First = VD->getFirstDecl();
1763     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1764       return; // First should already be in the vector.
1765   }
1766 
1767   if (ShouldWarnIfUnusedFileScopedDecl(D))
1768     UnusedFileScopedDecls.push_back(D);
1769 }
1770 
1771 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772   if (D->isInvalidDecl())
1773     return false;
1774 
1775   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776     // For a decomposition declaration, warn if none of the bindings are
1777     // referenced, instead of if the variable itself is referenced (which
1778     // it is, by the bindings' expressions).
1779     for (auto *BD : DD->bindings())
1780       if (BD->isReferenced())
1781         return false;
1782   } else if (!D->getDeclName()) {
1783     return false;
1784   } else if (D->isReferenced() || D->isUsed()) {
1785     return false;
1786   }
1787 
1788   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1789     return false;
1790 
1791   if (isa<LabelDecl>(D))
1792     return true;
1793 
1794   // Except for labels, we only care about unused decls that are local to
1795   // functions.
1796   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798     // For dependent types, the diagnostic is deferred.
1799     WithinFunction =
1800         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1801   if (!WithinFunction)
1802     return false;
1803 
1804   if (isa<TypedefNameDecl>(D))
1805     return true;
1806 
1807   // White-list anything that isn't a local variable.
1808   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1809     return false;
1810 
1811   // Types of valid local variables should be complete, so this should succeed.
1812   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813 
1814     // White-list anything with an __attribute__((unused)) type.
1815     const auto *Ty = VD->getType().getTypePtr();
1816 
1817     // Only look at the outermost level of typedef.
1818     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819       if (TT->getDecl()->hasAttr<UnusedAttr>())
1820         return false;
1821     }
1822 
1823     // If we failed to complete the type for some reason, or if the type is
1824     // dependent, don't diagnose the variable.
1825     if (Ty->isIncompleteType() || Ty->isDependentType())
1826       return false;
1827 
1828     // Look at the element type to ensure that the warning behaviour is
1829     // consistent for both scalars and arrays.
1830     Ty = Ty->getBaseElementTypeUnsafe();
1831 
1832     if (const TagType *TT = Ty->getAs<TagType>()) {
1833       const TagDecl *Tag = TT->getDecl();
1834       if (Tag->hasAttr<UnusedAttr>())
1835         return false;
1836 
1837       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1839           return false;
1840 
1841         if (const Expr *Init = VD->getInit()) {
1842           if (const ExprWithCleanups *Cleanups =
1843                   dyn_cast<ExprWithCleanups>(Init))
1844             Init = Cleanups->getSubExpr();
1845           const CXXConstructExpr *Construct =
1846             dyn_cast<CXXConstructExpr>(Init);
1847           if (Construct && !Construct->isElidable()) {
1848             CXXConstructorDecl *CD = Construct->getConstructor();
1849             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1850                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1851               return false;
1852           }
1853 
1854           // Suppress the warning if we don't know how this is constructed, and
1855           // it could possibly be non-trivial constructor.
1856           if (Init->isTypeDependent())
1857             for (const CXXConstructorDecl *Ctor : RD->ctors())
1858               if (!Ctor->isTrivial())
1859                 return false;
1860         }
1861       }
1862     }
1863 
1864     // TODO: __attribute__((unused)) templates?
1865   }
1866 
1867   return true;
1868 }
1869 
1870 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871                                      FixItHint &Hint) {
1872   if (isa<LabelDecl>(D)) {
1873     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875         true);
1876     if (AfterColon.isInvalid())
1877       return;
1878     Hint = FixItHint::CreateRemoval(
1879         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880   }
1881 }
1882 
1883 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884   if (D->getTypeForDecl()->isDependentType())
1885     return;
1886 
1887   for (auto *TmpD : D->decls()) {
1888     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889       DiagnoseUnusedDecl(T);
1890     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891       DiagnoseUnusedNestedTypedefs(R);
1892   }
1893 }
1894 
1895 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896 /// unless they are marked attr(unused).
1897 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898   if (!ShouldDiagnoseUnusedDecl(D))
1899     return;
1900 
1901   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902     // typedefs can be referenced later on, so the diagnostics are emitted
1903     // at end-of-translation-unit.
1904     UnusedLocalTypedefNameCandidates.insert(TD);
1905     return;
1906   }
1907 
1908   FixItHint Hint;
1909   GenerateFixForUnusedDecl(D, Context, Hint);
1910 
1911   unsigned DiagID;
1912   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1913     DiagID = diag::warn_unused_exception_param;
1914   else if (isa<LabelDecl>(D))
1915     DiagID = diag::warn_unused_label;
1916   else
1917     DiagID = diag::warn_unused_variable;
1918 
1919   Diag(D->getLocation(), DiagID) << D << Hint;
1920 }
1921 
1922 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923   // If it's not referenced, it can't be set.
1924   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
1925     return;
1926 
1927   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928 
1929   if (Ty->isReferenceType() || Ty->isDependentType())
1930     return;
1931 
1932   if (const TagType *TT = Ty->getAs<TagType>()) {
1933     const TagDecl *Tag = TT->getDecl();
1934     if (Tag->hasAttr<UnusedAttr>())
1935       return;
1936     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937     // mimic gcc's behavior.
1938     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939       if (!RD->hasAttr<WarnUnusedAttr>())
1940         return;
1941     }
1942   }
1943 
1944   auto iter = RefsMinusAssignments.find(VD);
1945   if (iter == RefsMinusAssignments.end())
1946     return;
1947 
1948   assert(iter->getSecond() >= 0 &&
1949          "Found a negative number of references to a VarDecl");
1950   if (iter->getSecond() != 0)
1951     return;
1952   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1953                                          : diag::warn_unused_but_set_variable;
1954   Diag(VD->getLocation(), DiagID) << VD;
1955 }
1956 
1957 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958   // Verify that we have no forward references left.  If so, there was a goto
1959   // or address of a label taken, but no definition of it.  Label fwd
1960   // definitions are indicated with a null substmt which is also not a resolved
1961   // MS inline assembly label name.
1962   bool Diagnose = false;
1963   if (L->isMSAsmLabel())
1964     Diagnose = !L->isResolvedMSAsmLabel();
1965   else
1966     Diagnose = L->getStmt() == nullptr;
1967   if (Diagnose)
1968     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969 }
1970 
1971 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972   S->mergeNRVOIntoParent();
1973 
1974   if (S->decl_empty()) return;
1975   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1976          "Scope shouldn't contain decls!");
1977 
1978   for (auto *TmpD : S->decls()) {
1979     assert(TmpD && "This decl didn't get pushed??");
1980 
1981     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1982     NamedDecl *D = cast<NamedDecl>(TmpD);
1983 
1984     // Diagnose unused variables in this scope.
1985     if (!S->hasUnrecoverableErrorOccurred()) {
1986       DiagnoseUnusedDecl(D);
1987       if (const auto *RD = dyn_cast<RecordDecl>(D))
1988         DiagnoseUnusedNestedTypedefs(RD);
1989       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990         DiagnoseUnusedButSetDecl(VD);
1991         RefsMinusAssignments.erase(VD);
1992       }
1993     }
1994 
1995     if (!D->getDeclName()) continue;
1996 
1997     // If this was a forward reference to a label, verify it was defined.
1998     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999       CheckPoppedLabel(LD, *this);
2000 
2001     // Remove this name from our lexical scope, and warn on it if we haven't
2002     // already.
2003     IdResolver.RemoveDecl(D);
2004     auto ShadowI = ShadowingDecls.find(D);
2005     if (ShadowI != ShadowingDecls.end()) {
2006       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008             << D << FD << FD->getParent();
2009         Diag(FD->getLocation(), diag::note_previous_declaration);
2010       }
2011       ShadowingDecls.erase(ShadowI);
2012     }
2013   }
2014 }
2015 
2016 /// Look for an Objective-C class in the translation unit.
2017 ///
2018 /// \param Id The name of the Objective-C class we're looking for. If
2019 /// typo-correction fixes this name, the Id will be updated
2020 /// to the fixed name.
2021 ///
2022 /// \param IdLoc The location of the name in the translation unit.
2023 ///
2024 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2025 /// if there is no class with the given name.
2026 ///
2027 /// \returns The declaration of the named Objective-C class, or NULL if the
2028 /// class could not be found.
2029 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030                                               SourceLocation IdLoc,
2031                                               bool DoTypoCorrection) {
2032   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033   // creation from this context.
2034   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035 
2036   if (!IDecl && DoTypoCorrection) {
2037     // Perform typo correction at the given location, but only if we
2038     // find an Objective-C class name.
2039     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040     if (TypoCorrection C =
2041             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045       Id = IDecl->getIdentifier();
2046     }
2047   }
2048   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049   // This routine must always return a class definition, if any.
2050   if (Def && Def->getDefinition())
2051       Def = Def->getDefinition();
2052   return Def;
2053 }
2054 
2055 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056 /// from S, where a non-field would be declared. This routine copes
2057 /// with the difference between C and C++ scoping rules in structs and
2058 /// unions. For example, the following code is well-formed in C but
2059 /// ill-formed in C++:
2060 /// @code
2061 /// struct S6 {
2062 ///   enum { BAR } e;
2063 /// };
2064 ///
2065 /// void test_S6() {
2066 ///   struct S6 a;
2067 ///   a.e = BAR;
2068 /// }
2069 /// @endcode
2070 /// For the declaration of BAR, this routine will return a different
2071 /// scope. The scope S will be the scope of the unnamed enumeration
2072 /// within S6. In C++, this routine will return the scope associated
2073 /// with S6, because the enumeration's scope is a transparent
2074 /// context but structures can contain non-field names. In C, this
2075 /// routine will return the translation unit scope, since the
2076 /// enumeration's scope is a transparent context and structures cannot
2077 /// contain non-field names.
2078 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2081          (S->isClassScope() && !getLangOpts().CPlusPlus))
2082     S = S->getParent();
2083   return S;
2084 }
2085 
2086 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087                                ASTContext::GetBuiltinTypeError Error) {
2088   switch (Error) {
2089   case ASTContext::GE_None:
2090     return "";
2091   case ASTContext::GE_Missing_type:
2092     return BuiltinInfo.getHeaderName(ID);
2093   case ASTContext::GE_Missing_stdio:
2094     return "stdio.h";
2095   case ASTContext::GE_Missing_setjmp:
2096     return "setjmp.h";
2097   case ASTContext::GE_Missing_ucontext:
2098     return "ucontext.h";
2099   }
2100   llvm_unreachable("unhandled error kind");
2101 }
2102 
2103 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104                                   unsigned ID, SourceLocation Loc) {
2105   DeclContext *Parent = Context.getTranslationUnitDecl();
2106 
2107   if (getLangOpts().CPlusPlus) {
2108     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110     CLinkageDecl->setImplicit();
2111     Parent->addDecl(CLinkageDecl);
2112     Parent = CLinkageDecl;
2113   }
2114 
2115   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116                                            /*TInfo=*/nullptr, SC_Extern,
2117                                            getCurFPFeatures().isFPConstrained(),
2118                                            false, Type->isFunctionProtoType());
2119   New->setImplicit();
2120   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2121 
2122   // Create Decl objects for each parameter, adding them to the
2123   // FunctionDecl.
2124   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2125     SmallVector<ParmVarDecl *, 16> Params;
2126     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2127       ParmVarDecl *parm = ParmVarDecl::Create(
2128           Context, New, SourceLocation(), SourceLocation(), nullptr,
2129           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2130       parm->setScopeInfo(0, i);
2131       Params.push_back(parm);
2132     }
2133     New->setParams(Params);
2134   }
2135 
2136   AddKnownFunctionAttributes(New);
2137   return New;
2138 }
2139 
2140 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2141 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2142 /// if we're creating this built-in in anticipation of redeclaring the
2143 /// built-in.
2144 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2145                                      Scope *S, bool ForRedeclaration,
2146                                      SourceLocation Loc) {
2147   LookupNecessaryTypesForBuiltin(S, ID);
2148 
2149   ASTContext::GetBuiltinTypeError Error;
2150   QualType R = Context.GetBuiltinType(ID, Error);
2151   if (Error) {
2152     if (!ForRedeclaration)
2153       return nullptr;
2154 
2155     // If we have a builtin without an associated type we should not emit a
2156     // warning when we were not able to find a type for it.
2157     if (Error == ASTContext::GE_Missing_type ||
2158         Context.BuiltinInfo.allowTypeMismatch(ID))
2159       return nullptr;
2160 
2161     // If we could not find a type for setjmp it is because the jmp_buf type was
2162     // not defined prior to the setjmp declaration.
2163     if (Error == ASTContext::GE_Missing_setjmp) {
2164       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2165           << Context.BuiltinInfo.getName(ID);
2166       return nullptr;
2167     }
2168 
2169     // Generally, we emit a warning that the declaration requires the
2170     // appropriate header.
2171     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2172         << getHeaderName(Context.BuiltinInfo, ID, Error)
2173         << Context.BuiltinInfo.getName(ID);
2174     return nullptr;
2175   }
2176 
2177   if (!ForRedeclaration &&
2178       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2179        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2180     Diag(Loc, diag::ext_implicit_lib_function_decl)
2181         << Context.BuiltinInfo.getName(ID) << R;
2182     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2183       Diag(Loc, diag::note_include_header_or_declare)
2184           << Header << Context.BuiltinInfo.getName(ID);
2185   }
2186 
2187   if (R.isNull())
2188     return nullptr;
2189 
2190   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2191   RegisterLocallyScopedExternCDecl(New, S);
2192 
2193   // TUScope is the translation-unit scope to insert this function into.
2194   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2195   // relate Scopes to DeclContexts, and probably eliminate CurContext
2196   // entirely, but we're not there yet.
2197   DeclContext *SavedContext = CurContext;
2198   CurContext = New->getDeclContext();
2199   PushOnScopeChains(New, TUScope);
2200   CurContext = SavedContext;
2201   return New;
2202 }
2203 
2204 /// Typedef declarations don't have linkage, but they still denote the same
2205 /// entity if their types are the same.
2206 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2207 /// isSameEntity.
2208 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2209                                                      TypedefNameDecl *Decl,
2210                                                      LookupResult &Previous) {
2211   // This is only interesting when modules are enabled.
2212   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2213     return;
2214 
2215   // Empty sets are uninteresting.
2216   if (Previous.empty())
2217     return;
2218 
2219   LookupResult::Filter Filter = Previous.makeFilter();
2220   while (Filter.hasNext()) {
2221     NamedDecl *Old = Filter.next();
2222 
2223     // Non-hidden declarations are never ignored.
2224     if (S.isVisible(Old))
2225       continue;
2226 
2227     // Declarations of the same entity are not ignored, even if they have
2228     // different linkages.
2229     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2230       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2231                                 Decl->getUnderlyingType()))
2232         continue;
2233 
2234       // If both declarations give a tag declaration a typedef name for linkage
2235       // purposes, then they declare the same entity.
2236       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2237           Decl->getAnonDeclWithTypedefName())
2238         continue;
2239     }
2240 
2241     Filter.erase();
2242   }
2243 
2244   Filter.done();
2245 }
2246 
2247 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2248   QualType OldType;
2249   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2250     OldType = OldTypedef->getUnderlyingType();
2251   else
2252     OldType = Context.getTypeDeclType(Old);
2253   QualType NewType = New->getUnderlyingType();
2254 
2255   if (NewType->isVariablyModifiedType()) {
2256     // Must not redefine a typedef with a variably-modified type.
2257     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2258     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2259       << Kind << NewType;
2260     if (Old->getLocation().isValid())
2261       notePreviousDefinition(Old, New->getLocation());
2262     New->setInvalidDecl();
2263     return true;
2264   }
2265 
2266   if (OldType != NewType &&
2267       !OldType->isDependentType() &&
2268       !NewType->isDependentType() &&
2269       !Context.hasSameType(OldType, NewType)) {
2270     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2271     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2272       << Kind << NewType << OldType;
2273     if (Old->getLocation().isValid())
2274       notePreviousDefinition(Old, New->getLocation());
2275     New->setInvalidDecl();
2276     return true;
2277   }
2278   return false;
2279 }
2280 
2281 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2282 /// same name and scope as a previous declaration 'Old'.  Figure out
2283 /// how to resolve this situation, merging decls or emitting
2284 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2285 ///
2286 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2287                                 LookupResult &OldDecls) {
2288   // If the new decl is known invalid already, don't bother doing any
2289   // merging checks.
2290   if (New->isInvalidDecl()) return;
2291 
2292   // Allow multiple definitions for ObjC built-in typedefs.
2293   // FIXME: Verify the underlying types are equivalent!
2294   if (getLangOpts().ObjC) {
2295     const IdentifierInfo *TypeID = New->getIdentifier();
2296     switch (TypeID->getLength()) {
2297     default: break;
2298     case 2:
2299       {
2300         if (!TypeID->isStr("id"))
2301           break;
2302         QualType T = New->getUnderlyingType();
2303         if (!T->isPointerType())
2304           break;
2305         if (!T->isVoidPointerType()) {
2306           QualType PT = T->castAs<PointerType>()->getPointeeType();
2307           if (!PT->isStructureType())
2308             break;
2309         }
2310         Context.setObjCIdRedefinitionType(T);
2311         // Install the built-in type for 'id', ignoring the current definition.
2312         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2313         return;
2314       }
2315     case 5:
2316       if (!TypeID->isStr("Class"))
2317         break;
2318       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2319       // Install the built-in type for 'Class', ignoring the current definition.
2320       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2321       return;
2322     case 3:
2323       if (!TypeID->isStr("SEL"))
2324         break;
2325       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2326       // Install the built-in type for 'SEL', ignoring the current definition.
2327       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2328       return;
2329     }
2330     // Fall through - the typedef name was not a builtin type.
2331   }
2332 
2333   // Verify the old decl was also a type.
2334   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2335   if (!Old) {
2336     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2337       << New->getDeclName();
2338 
2339     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2340     if (OldD->getLocation().isValid())
2341       notePreviousDefinition(OldD, New->getLocation());
2342 
2343     return New->setInvalidDecl();
2344   }
2345 
2346   // If the old declaration is invalid, just give up here.
2347   if (Old->isInvalidDecl())
2348     return New->setInvalidDecl();
2349 
2350   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2351     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2352     auto *NewTag = New->getAnonDeclWithTypedefName();
2353     NamedDecl *Hidden = nullptr;
2354     if (OldTag && NewTag &&
2355         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2356         !hasVisibleDefinition(OldTag, &Hidden)) {
2357       // There is a definition of this tag, but it is not visible. Use it
2358       // instead of our tag.
2359       New->setTypeForDecl(OldTD->getTypeForDecl());
2360       if (OldTD->isModed())
2361         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2362                                     OldTD->getUnderlyingType());
2363       else
2364         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2365 
2366       // Make the old tag definition visible.
2367       makeMergedDefinitionVisible(Hidden);
2368 
2369       // If this was an unscoped enumeration, yank all of its enumerators
2370       // out of the scope.
2371       if (isa<EnumDecl>(NewTag)) {
2372         Scope *EnumScope = getNonFieldDeclScope(S);
2373         for (auto *D : NewTag->decls()) {
2374           auto *ED = cast<EnumConstantDecl>(D);
2375           assert(EnumScope->isDeclScope(ED));
2376           EnumScope->RemoveDecl(ED);
2377           IdResolver.RemoveDecl(ED);
2378           ED->getLexicalDeclContext()->removeDecl(ED);
2379         }
2380       }
2381     }
2382   }
2383 
2384   // If the typedef types are not identical, reject them in all languages and
2385   // with any extensions enabled.
2386   if (isIncompatibleTypedef(Old, New))
2387     return;
2388 
2389   // The types match.  Link up the redeclaration chain and merge attributes if
2390   // the old declaration was a typedef.
2391   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2392     New->setPreviousDecl(Typedef);
2393     mergeDeclAttributes(New, Old);
2394   }
2395 
2396   if (getLangOpts().MicrosoftExt)
2397     return;
2398 
2399   if (getLangOpts().CPlusPlus) {
2400     // C++ [dcl.typedef]p2:
2401     //   In a given non-class scope, a typedef specifier can be used to
2402     //   redefine the name of any type declared in that scope to refer
2403     //   to the type to which it already refers.
2404     if (!isa<CXXRecordDecl>(CurContext))
2405       return;
2406 
2407     // C++0x [dcl.typedef]p4:
2408     //   In a given class scope, a typedef specifier can be used to redefine
2409     //   any class-name declared in that scope that is not also a typedef-name
2410     //   to refer to the type to which it already refers.
2411     //
2412     // This wording came in via DR424, which was a correction to the
2413     // wording in DR56, which accidentally banned code like:
2414     //
2415     //   struct S {
2416     //     typedef struct A { } A;
2417     //   };
2418     //
2419     // in the C++03 standard. We implement the C++0x semantics, which
2420     // allow the above but disallow
2421     //
2422     //   struct S {
2423     //     typedef int I;
2424     //     typedef int I;
2425     //   };
2426     //
2427     // since that was the intent of DR56.
2428     if (!isa<TypedefNameDecl>(Old))
2429       return;
2430 
2431     Diag(New->getLocation(), diag::err_redefinition)
2432       << New->getDeclName();
2433     notePreviousDefinition(Old, New->getLocation());
2434     return New->setInvalidDecl();
2435   }
2436 
2437   // Modules always permit redefinition of typedefs, as does C11.
2438   if (getLangOpts().Modules || getLangOpts().C11)
2439     return;
2440 
2441   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2442   // is normally mapped to an error, but can be controlled with
2443   // -Wtypedef-redefinition.  If either the original or the redefinition is
2444   // in a system header, don't emit this for compatibility with GCC.
2445   if (getDiagnostics().getSuppressSystemWarnings() &&
2446       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2447       (Old->isImplicit() ||
2448        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2449        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2450     return;
2451 
2452   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2453     << New->getDeclName();
2454   notePreviousDefinition(Old, New->getLocation());
2455 }
2456 
2457 /// DeclhasAttr - returns true if decl Declaration already has the target
2458 /// attribute.
2459 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2460   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2461   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2462   for (const auto *i : D->attrs())
2463     if (i->getKind() == A->getKind()) {
2464       if (Ann) {
2465         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2466           return true;
2467         continue;
2468       }
2469       // FIXME: Don't hardcode this check
2470       if (OA && isa<OwnershipAttr>(i))
2471         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2472       return true;
2473     }
2474 
2475   return false;
2476 }
2477 
2478 static bool isAttributeTargetADefinition(Decl *D) {
2479   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2480     return VD->isThisDeclarationADefinition();
2481   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2482     return TD->isCompleteDefinition() || TD->isBeingDefined();
2483   return true;
2484 }
2485 
2486 /// Merge alignment attributes from \p Old to \p New, taking into account the
2487 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2488 ///
2489 /// \return \c true if any attributes were added to \p New.
2490 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2491   // Look for alignas attributes on Old, and pick out whichever attribute
2492   // specifies the strictest alignment requirement.
2493   AlignedAttr *OldAlignasAttr = nullptr;
2494   AlignedAttr *OldStrictestAlignAttr = nullptr;
2495   unsigned OldAlign = 0;
2496   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2497     // FIXME: We have no way of representing inherited dependent alignments
2498     // in a case like:
2499     //   template<int A, int B> struct alignas(A) X;
2500     //   template<int A, int B> struct alignas(B) X {};
2501     // For now, we just ignore any alignas attributes which are not on the
2502     // definition in such a case.
2503     if (I->isAlignmentDependent())
2504       return false;
2505 
2506     if (I->isAlignas())
2507       OldAlignasAttr = I;
2508 
2509     unsigned Align = I->getAlignment(S.Context);
2510     if (Align > OldAlign) {
2511       OldAlign = Align;
2512       OldStrictestAlignAttr = I;
2513     }
2514   }
2515 
2516   // Look for alignas attributes on New.
2517   AlignedAttr *NewAlignasAttr = nullptr;
2518   unsigned NewAlign = 0;
2519   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2520     if (I->isAlignmentDependent())
2521       return false;
2522 
2523     if (I->isAlignas())
2524       NewAlignasAttr = I;
2525 
2526     unsigned Align = I->getAlignment(S.Context);
2527     if (Align > NewAlign)
2528       NewAlign = Align;
2529   }
2530 
2531   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2532     // Both declarations have 'alignas' attributes. We require them to match.
2533     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2534     // fall short. (If two declarations both have alignas, they must both match
2535     // every definition, and so must match each other if there is a definition.)
2536 
2537     // If either declaration only contains 'alignas(0)' specifiers, then it
2538     // specifies the natural alignment for the type.
2539     if (OldAlign == 0 || NewAlign == 0) {
2540       QualType Ty;
2541       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2542         Ty = VD->getType();
2543       else
2544         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2545 
2546       if (OldAlign == 0)
2547         OldAlign = S.Context.getTypeAlign(Ty);
2548       if (NewAlign == 0)
2549         NewAlign = S.Context.getTypeAlign(Ty);
2550     }
2551 
2552     if (OldAlign != NewAlign) {
2553       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2554         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2555         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2556       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2557     }
2558   }
2559 
2560   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2561     // C++11 [dcl.align]p6:
2562     //   if any declaration of an entity has an alignment-specifier,
2563     //   every defining declaration of that entity shall specify an
2564     //   equivalent alignment.
2565     // C11 6.7.5/7:
2566     //   If the definition of an object does not have an alignment
2567     //   specifier, any other declaration of that object shall also
2568     //   have no alignment specifier.
2569     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2570       << OldAlignasAttr;
2571     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2572       << OldAlignasAttr;
2573   }
2574 
2575   bool AnyAdded = false;
2576 
2577   // Ensure we have an attribute representing the strictest alignment.
2578   if (OldAlign > NewAlign) {
2579     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2580     Clone->setInherited(true);
2581     New->addAttr(Clone);
2582     AnyAdded = true;
2583   }
2584 
2585   // Ensure we have an alignas attribute if the old declaration had one.
2586   if (OldAlignasAttr && !NewAlignasAttr &&
2587       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2588     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2589     Clone->setInherited(true);
2590     New->addAttr(Clone);
2591     AnyAdded = true;
2592   }
2593 
2594   return AnyAdded;
2595 }
2596 
2597 #define WANT_DECL_MERGE_LOGIC
2598 #include "clang/Sema/AttrParsedAttrImpl.inc"
2599 #undef WANT_DECL_MERGE_LOGIC
2600 
2601 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2602                                const InheritableAttr *Attr,
2603                                Sema::AvailabilityMergeKind AMK) {
2604   // Diagnose any mutual exclusions between the attribute that we want to add
2605   // and attributes that already exist on the declaration.
2606   if (!DiagnoseMutualExclusions(S, D, Attr))
2607     return false;
2608 
2609   // This function copies an attribute Attr from a previous declaration to the
2610   // new declaration D if the new declaration doesn't itself have that attribute
2611   // yet or if that attribute allows duplicates.
2612   // If you're adding a new attribute that requires logic different from
2613   // "use explicit attribute on decl if present, else use attribute from
2614   // previous decl", for example if the attribute needs to be consistent
2615   // between redeclarations, you need to call a custom merge function here.
2616   InheritableAttr *NewAttr = nullptr;
2617   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2618     NewAttr = S.mergeAvailabilityAttr(
2619         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2620         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2621         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2622         AA->getPriority());
2623   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2624     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2625   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2626     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2627   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2628     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2629   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2630     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2631   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2632     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2633                                 FA->getFirstArg());
2634   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2635     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2636   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2637     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2638   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2639     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2640                                        IA->getInheritanceModel());
2641   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2642     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2643                                       &S.Context.Idents.get(AA->getSpelling()));
2644   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2645            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2646             isa<CUDAGlobalAttr>(Attr))) {
2647     // CUDA target attributes are part of function signature for
2648     // overloading purposes and must not be merged.
2649     return false;
2650   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2651     NewAttr = S.mergeMinSizeAttr(D, *MA);
2652   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2653     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2654   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2655     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2656   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2657     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2658   else if (isa<AlignedAttr>(Attr))
2659     // AlignedAttrs are handled separately, because we need to handle all
2660     // such attributes on a declaration at the same time.
2661     NewAttr = nullptr;
2662   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2663            (AMK == Sema::AMK_Override ||
2664             AMK == Sema::AMK_ProtocolImplementation ||
2665             AMK == Sema::AMK_OptionalProtocolImplementation))
2666     NewAttr = nullptr;
2667   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2668     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2669   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2670     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2671   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2672     NewAttr = S.mergeImportNameAttr(D, *INA);
2673   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2674     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2675   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2676     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2677   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2678     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2679 
2680   if (NewAttr) {
2681     NewAttr->setInherited(true);
2682     D->addAttr(NewAttr);
2683     if (isa<MSInheritanceAttr>(NewAttr))
2684       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2685     return true;
2686   }
2687 
2688   return false;
2689 }
2690 
2691 static const NamedDecl *getDefinition(const Decl *D) {
2692   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2693     return TD->getDefinition();
2694   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2695     const VarDecl *Def = VD->getDefinition();
2696     if (Def)
2697       return Def;
2698     return VD->getActingDefinition();
2699   }
2700   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2701     const FunctionDecl *Def = nullptr;
2702     if (FD->isDefined(Def, true))
2703       return Def;
2704   }
2705   return nullptr;
2706 }
2707 
2708 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2709   for (const auto *Attribute : D->attrs())
2710     if (Attribute->getKind() == Kind)
2711       return true;
2712   return false;
2713 }
2714 
2715 /// checkNewAttributesAfterDef - If we already have a definition, check that
2716 /// there are no new attributes in this declaration.
2717 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2718   if (!New->hasAttrs())
2719     return;
2720 
2721   const NamedDecl *Def = getDefinition(Old);
2722   if (!Def || Def == New)
2723     return;
2724 
2725   AttrVec &NewAttributes = New->getAttrs();
2726   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2727     const Attr *NewAttribute = NewAttributes[I];
2728 
2729     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2730       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2731         Sema::SkipBodyInfo SkipBody;
2732         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2733 
2734         // If we're skipping this definition, drop the "alias" attribute.
2735         if (SkipBody.ShouldSkip) {
2736           NewAttributes.erase(NewAttributes.begin() + I);
2737           --E;
2738           continue;
2739         }
2740       } else {
2741         VarDecl *VD = cast<VarDecl>(New);
2742         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2743                                 VarDecl::TentativeDefinition
2744                             ? diag::err_alias_after_tentative
2745                             : diag::err_redefinition;
2746         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2747         if (Diag == diag::err_redefinition)
2748           S.notePreviousDefinition(Def, VD->getLocation());
2749         else
2750           S.Diag(Def->getLocation(), diag::note_previous_definition);
2751         VD->setInvalidDecl();
2752       }
2753       ++I;
2754       continue;
2755     }
2756 
2757     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2758       // Tentative definitions are only interesting for the alias check above.
2759       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2760         ++I;
2761         continue;
2762       }
2763     }
2764 
2765     if (hasAttribute(Def, NewAttribute->getKind())) {
2766       ++I;
2767       continue; // regular attr merging will take care of validating this.
2768     }
2769 
2770     if (isa<C11NoReturnAttr>(NewAttribute)) {
2771       // C's _Noreturn is allowed to be added to a function after it is defined.
2772       ++I;
2773       continue;
2774     } else if (isa<UuidAttr>(NewAttribute)) {
2775       // msvc will allow a subsequent definition to add an uuid to a class
2776       ++I;
2777       continue;
2778     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2779       if (AA->isAlignas()) {
2780         // C++11 [dcl.align]p6:
2781         //   if any declaration of an entity has an alignment-specifier,
2782         //   every defining declaration of that entity shall specify an
2783         //   equivalent alignment.
2784         // C11 6.7.5/7:
2785         //   If the definition of an object does not have an alignment
2786         //   specifier, any other declaration of that object shall also
2787         //   have no alignment specifier.
2788         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2789           << AA;
2790         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2791           << AA;
2792         NewAttributes.erase(NewAttributes.begin() + I);
2793         --E;
2794         continue;
2795       }
2796     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2797       // If there is a C definition followed by a redeclaration with this
2798       // attribute then there are two different definitions. In C++, prefer the
2799       // standard diagnostics.
2800       if (!S.getLangOpts().CPlusPlus) {
2801         S.Diag(NewAttribute->getLocation(),
2802                diag::err_loader_uninitialized_redeclaration);
2803         S.Diag(Def->getLocation(), diag::note_previous_definition);
2804         NewAttributes.erase(NewAttributes.begin() + I);
2805         --E;
2806         continue;
2807       }
2808     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2809                cast<VarDecl>(New)->isInline() &&
2810                !cast<VarDecl>(New)->isInlineSpecified()) {
2811       // Don't warn about applying selectany to implicitly inline variables.
2812       // Older compilers and language modes would require the use of selectany
2813       // to make such variables inline, and it would have no effect if we
2814       // honored it.
2815       ++I;
2816       continue;
2817     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2818       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2819       // declarations after defintions.
2820       ++I;
2821       continue;
2822     }
2823 
2824     S.Diag(NewAttribute->getLocation(),
2825            diag::warn_attribute_precede_definition);
2826     S.Diag(Def->getLocation(), diag::note_previous_definition);
2827     NewAttributes.erase(NewAttributes.begin() + I);
2828     --E;
2829   }
2830 }
2831 
2832 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2833                                      const ConstInitAttr *CIAttr,
2834                                      bool AttrBeforeInit) {
2835   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2836 
2837   // Figure out a good way to write this specifier on the old declaration.
2838   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2839   // enough of the attribute list spelling information to extract that without
2840   // heroics.
2841   std::string SuitableSpelling;
2842   if (S.getLangOpts().CPlusPlus20)
2843     SuitableSpelling = std::string(
2844         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2845   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2846     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2847         InsertLoc, {tok::l_square, tok::l_square,
2848                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2849                     S.PP.getIdentifierInfo("require_constant_initialization"),
2850                     tok::r_square, tok::r_square}));
2851   if (SuitableSpelling.empty())
2852     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2853         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2854                     S.PP.getIdentifierInfo("require_constant_initialization"),
2855                     tok::r_paren, tok::r_paren}));
2856   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2857     SuitableSpelling = "constinit";
2858   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2859     SuitableSpelling = "[[clang::require_constant_initialization]]";
2860   if (SuitableSpelling.empty())
2861     SuitableSpelling = "__attribute__((require_constant_initialization))";
2862   SuitableSpelling += " ";
2863 
2864   if (AttrBeforeInit) {
2865     // extern constinit int a;
2866     // int a = 0; // error (missing 'constinit'), accepted as extension
2867     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2868     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2869         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2870     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2871   } else {
2872     // int a = 0;
2873     // constinit extern int a; // error (missing 'constinit')
2874     S.Diag(CIAttr->getLocation(),
2875            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2876                                  : diag::warn_require_const_init_added_too_late)
2877         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2878     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2879         << CIAttr->isConstinit()
2880         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2881   }
2882 }
2883 
2884 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2885 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2886                                AvailabilityMergeKind AMK) {
2887   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2888     UsedAttr *NewAttr = OldAttr->clone(Context);
2889     NewAttr->setInherited(true);
2890     New->addAttr(NewAttr);
2891   }
2892   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2893     RetainAttr *NewAttr = OldAttr->clone(Context);
2894     NewAttr->setInherited(true);
2895     New->addAttr(NewAttr);
2896   }
2897 
2898   if (!Old->hasAttrs() && !New->hasAttrs())
2899     return;
2900 
2901   // [dcl.constinit]p1:
2902   //   If the [constinit] specifier is applied to any declaration of a
2903   //   variable, it shall be applied to the initializing declaration.
2904   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2905   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2906   if (bool(OldConstInit) != bool(NewConstInit)) {
2907     const auto *OldVD = cast<VarDecl>(Old);
2908     auto *NewVD = cast<VarDecl>(New);
2909 
2910     // Find the initializing declaration. Note that we might not have linked
2911     // the new declaration into the redeclaration chain yet.
2912     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2913     if (!InitDecl &&
2914         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2915       InitDecl = NewVD;
2916 
2917     if (InitDecl == NewVD) {
2918       // This is the initializing declaration. If it would inherit 'constinit',
2919       // that's ill-formed. (Note that we do not apply this to the attribute
2920       // form).
2921       if (OldConstInit && OldConstInit->isConstinit())
2922         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2923                                  /*AttrBeforeInit=*/true);
2924     } else if (NewConstInit) {
2925       // This is the first time we've been told that this declaration should
2926       // have a constant initializer. If we already saw the initializing
2927       // declaration, this is too late.
2928       if (InitDecl && InitDecl != NewVD) {
2929         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2930                                  /*AttrBeforeInit=*/false);
2931         NewVD->dropAttr<ConstInitAttr>();
2932       }
2933     }
2934   }
2935 
2936   // Attributes declared post-definition are currently ignored.
2937   checkNewAttributesAfterDef(*this, New, Old);
2938 
2939   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2940     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2941       if (!OldA->isEquivalent(NewA)) {
2942         // This redeclaration changes __asm__ label.
2943         Diag(New->getLocation(), diag::err_different_asm_label);
2944         Diag(OldA->getLocation(), diag::note_previous_declaration);
2945       }
2946     } else if (Old->isUsed()) {
2947       // This redeclaration adds an __asm__ label to a declaration that has
2948       // already been ODR-used.
2949       Diag(New->getLocation(), diag::err_late_asm_label_name)
2950         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2951     }
2952   }
2953 
2954   // Re-declaration cannot add abi_tag's.
2955   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2956     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2957       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2958         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2959                       NewTag) == OldAbiTagAttr->tags_end()) {
2960           Diag(NewAbiTagAttr->getLocation(),
2961                diag::err_new_abi_tag_on_redeclaration)
2962               << NewTag;
2963           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2964         }
2965       }
2966     } else {
2967       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2968       Diag(Old->getLocation(), diag::note_previous_declaration);
2969     }
2970   }
2971 
2972   // This redeclaration adds a section attribute.
2973   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2974     if (auto *VD = dyn_cast<VarDecl>(New)) {
2975       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2976         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2977         Diag(Old->getLocation(), diag::note_previous_declaration);
2978       }
2979     }
2980   }
2981 
2982   // Redeclaration adds code-seg attribute.
2983   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2984   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2985       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2986     Diag(New->getLocation(), diag::warn_mismatched_section)
2987          << 0 /*codeseg*/;
2988     Diag(Old->getLocation(), diag::note_previous_declaration);
2989   }
2990 
2991   if (!Old->hasAttrs())
2992     return;
2993 
2994   bool foundAny = New->hasAttrs();
2995 
2996   // Ensure that any moving of objects within the allocated map is done before
2997   // we process them.
2998   if (!foundAny) New->setAttrs(AttrVec());
2999 
3000   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3001     // Ignore deprecated/unavailable/availability attributes if requested.
3002     AvailabilityMergeKind LocalAMK = AMK_None;
3003     if (isa<DeprecatedAttr>(I) ||
3004         isa<UnavailableAttr>(I) ||
3005         isa<AvailabilityAttr>(I)) {
3006       switch (AMK) {
3007       case AMK_None:
3008         continue;
3009 
3010       case AMK_Redeclaration:
3011       case AMK_Override:
3012       case AMK_ProtocolImplementation:
3013       case AMK_OptionalProtocolImplementation:
3014         LocalAMK = AMK;
3015         break;
3016       }
3017     }
3018 
3019     // Already handled.
3020     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3021       continue;
3022 
3023     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3024       foundAny = true;
3025   }
3026 
3027   if (mergeAlignedAttrs(*this, New, Old))
3028     foundAny = true;
3029 
3030   if (!foundAny) New->dropAttrs();
3031 }
3032 
3033 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3034 /// to the new one.
3035 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3036                                      const ParmVarDecl *oldDecl,
3037                                      Sema &S) {
3038   // C++11 [dcl.attr.depend]p2:
3039   //   The first declaration of a function shall specify the
3040   //   carries_dependency attribute for its declarator-id if any declaration
3041   //   of the function specifies the carries_dependency attribute.
3042   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3043   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3044     S.Diag(CDA->getLocation(),
3045            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3046     // Find the first declaration of the parameter.
3047     // FIXME: Should we build redeclaration chains for function parameters?
3048     const FunctionDecl *FirstFD =
3049       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3050     const ParmVarDecl *FirstVD =
3051       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3052     S.Diag(FirstVD->getLocation(),
3053            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3054   }
3055 
3056   if (!oldDecl->hasAttrs())
3057     return;
3058 
3059   bool foundAny = newDecl->hasAttrs();
3060 
3061   // Ensure that any moving of objects within the allocated map is
3062   // done before we process them.
3063   if (!foundAny) newDecl->setAttrs(AttrVec());
3064 
3065   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3066     if (!DeclHasAttr(newDecl, I)) {
3067       InheritableAttr *newAttr =
3068         cast<InheritableParamAttr>(I->clone(S.Context));
3069       newAttr->setInherited(true);
3070       newDecl->addAttr(newAttr);
3071       foundAny = true;
3072     }
3073   }
3074 
3075   if (!foundAny) newDecl->dropAttrs();
3076 }
3077 
3078 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3079                                 const ParmVarDecl *OldParam,
3080                                 Sema &S) {
3081   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3082     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3083       if (*Oldnullability != *Newnullability) {
3084         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3085           << DiagNullabilityKind(
3086                *Newnullability,
3087                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3088                 != 0))
3089           << DiagNullabilityKind(
3090                *Oldnullability,
3091                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3092                 != 0));
3093         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3094       }
3095     } else {
3096       QualType NewT = NewParam->getType();
3097       NewT = S.Context.getAttributedType(
3098                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3099                          NewT, NewT);
3100       NewParam->setType(NewT);
3101     }
3102   }
3103 }
3104 
3105 namespace {
3106 
3107 /// Used in MergeFunctionDecl to keep track of function parameters in
3108 /// C.
3109 struct GNUCompatibleParamWarning {
3110   ParmVarDecl *OldParm;
3111   ParmVarDecl *NewParm;
3112   QualType PromotedType;
3113 };
3114 
3115 } // end anonymous namespace
3116 
3117 // Determine whether the previous declaration was a definition, implicit
3118 // declaration, or a declaration.
3119 template <typename T>
3120 static std::pair<diag::kind, SourceLocation>
3121 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3122   diag::kind PrevDiag;
3123   SourceLocation OldLocation = Old->getLocation();
3124   if (Old->isThisDeclarationADefinition())
3125     PrevDiag = diag::note_previous_definition;
3126   else if (Old->isImplicit()) {
3127     PrevDiag = diag::note_previous_implicit_declaration;
3128     if (OldLocation.isInvalid())
3129       OldLocation = New->getLocation();
3130   } else
3131     PrevDiag = diag::note_previous_declaration;
3132   return std::make_pair(PrevDiag, OldLocation);
3133 }
3134 
3135 /// canRedefineFunction - checks if a function can be redefined. Currently,
3136 /// only extern inline functions can be redefined, and even then only in
3137 /// GNU89 mode.
3138 static bool canRedefineFunction(const FunctionDecl *FD,
3139                                 const LangOptions& LangOpts) {
3140   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3141           !LangOpts.CPlusPlus &&
3142           FD->isInlineSpecified() &&
3143           FD->getStorageClass() == SC_Extern);
3144 }
3145 
3146 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3147   const AttributedType *AT = T->getAs<AttributedType>();
3148   while (AT && !AT->isCallingConv())
3149     AT = AT->getModifiedType()->getAs<AttributedType>();
3150   return AT;
3151 }
3152 
3153 template <typename T>
3154 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3155   const DeclContext *DC = Old->getDeclContext();
3156   if (DC->isRecord())
3157     return false;
3158 
3159   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3160   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3161     return true;
3162   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3163     return true;
3164   return false;
3165 }
3166 
3167 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3168 static bool isExternC(VarTemplateDecl *) { return false; }
3169 static bool isExternC(FunctionTemplateDecl *) { return false; }
3170 
3171 /// Check whether a redeclaration of an entity introduced by a
3172 /// using-declaration is valid, given that we know it's not an overload
3173 /// (nor a hidden tag declaration).
3174 template<typename ExpectedDecl>
3175 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3176                                    ExpectedDecl *New) {
3177   // C++11 [basic.scope.declarative]p4:
3178   //   Given a set of declarations in a single declarative region, each of
3179   //   which specifies the same unqualified name,
3180   //   -- they shall all refer to the same entity, or all refer to functions
3181   //      and function templates; or
3182   //   -- exactly one declaration shall declare a class name or enumeration
3183   //      name that is not a typedef name and the other declarations shall all
3184   //      refer to the same variable or enumerator, or all refer to functions
3185   //      and function templates; in this case the class name or enumeration
3186   //      name is hidden (3.3.10).
3187 
3188   // C++11 [namespace.udecl]p14:
3189   //   If a function declaration in namespace scope or block scope has the
3190   //   same name and the same parameter-type-list as a function introduced
3191   //   by a using-declaration, and the declarations do not declare the same
3192   //   function, the program is ill-formed.
3193 
3194   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3195   if (Old &&
3196       !Old->getDeclContext()->getRedeclContext()->Equals(
3197           New->getDeclContext()->getRedeclContext()) &&
3198       !(isExternC(Old) && isExternC(New)))
3199     Old = nullptr;
3200 
3201   if (!Old) {
3202     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3203     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3204     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3205     return true;
3206   }
3207   return false;
3208 }
3209 
3210 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3211                                             const FunctionDecl *B) {
3212   assert(A->getNumParams() == B->getNumParams());
3213 
3214   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3215     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3216     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3217     if (AttrA == AttrB)
3218       return true;
3219     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3220            AttrA->isDynamic() == AttrB->isDynamic();
3221   };
3222 
3223   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3224 }
3225 
3226 /// If necessary, adjust the semantic declaration context for a qualified
3227 /// declaration to name the correct inline namespace within the qualifier.
3228 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3229                                                DeclaratorDecl *OldD) {
3230   // The only case where we need to update the DeclContext is when
3231   // redeclaration lookup for a qualified name finds a declaration
3232   // in an inline namespace within the context named by the qualifier:
3233   //
3234   //   inline namespace N { int f(); }
3235   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3236   //
3237   // For unqualified declarations, the semantic context *can* change
3238   // along the redeclaration chain (for local extern declarations,
3239   // extern "C" declarations, and friend declarations in particular).
3240   if (!NewD->getQualifier())
3241     return;
3242 
3243   // NewD is probably already in the right context.
3244   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3245   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3246   if (NamedDC->Equals(SemaDC))
3247     return;
3248 
3249   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3250           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3251          "unexpected context for redeclaration");
3252 
3253   auto *LexDC = NewD->getLexicalDeclContext();
3254   auto FixSemaDC = [=](NamedDecl *D) {
3255     if (!D)
3256       return;
3257     D->setDeclContext(SemaDC);
3258     D->setLexicalDeclContext(LexDC);
3259   };
3260 
3261   FixSemaDC(NewD);
3262   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3263     FixSemaDC(FD->getDescribedFunctionTemplate());
3264   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3265     FixSemaDC(VD->getDescribedVarTemplate());
3266 }
3267 
3268 /// MergeFunctionDecl - We just parsed a function 'New' from
3269 /// declarator D which has the same name and scope as a previous
3270 /// declaration 'Old'.  Figure out how to resolve this situation,
3271 /// merging decls or emitting diagnostics as appropriate.
3272 ///
3273 /// In C++, New and Old must be declarations that are not
3274 /// overloaded. Use IsOverload to determine whether New and Old are
3275 /// overloaded, and to select the Old declaration that New should be
3276 /// merged with.
3277 ///
3278 /// Returns true if there was an error, false otherwise.
3279 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3280                              Scope *S, bool MergeTypeWithOld) {
3281   // Verify the old decl was also a function.
3282   FunctionDecl *Old = OldD->getAsFunction();
3283   if (!Old) {
3284     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3285       if (New->getFriendObjectKind()) {
3286         Diag(New->getLocation(), diag::err_using_decl_friend);
3287         Diag(Shadow->getTargetDecl()->getLocation(),
3288              diag::note_using_decl_target);
3289         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3290             << 0;
3291         return true;
3292       }
3293 
3294       // Check whether the two declarations might declare the same function or
3295       // function template.
3296       if (FunctionTemplateDecl *NewTemplate =
3297               New->getDescribedFunctionTemplate()) {
3298         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3299                                                          NewTemplate))
3300           return true;
3301         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3302                          ->getAsFunction();
3303       } else {
3304         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3305           return true;
3306         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3307       }
3308     } else {
3309       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3310         << New->getDeclName();
3311       notePreviousDefinition(OldD, New->getLocation());
3312       return true;
3313     }
3314   }
3315 
3316   // If the old declaration was found in an inline namespace and the new
3317   // declaration was qualified, update the DeclContext to match.
3318   adjustDeclContextForDeclaratorDecl(New, Old);
3319 
3320   // If the old declaration is invalid, just give up here.
3321   if (Old->isInvalidDecl())
3322     return true;
3323 
3324   // Disallow redeclaration of some builtins.
3325   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3326     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3327     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3328         << Old << Old->getType();
3329     return true;
3330   }
3331 
3332   diag::kind PrevDiag;
3333   SourceLocation OldLocation;
3334   std::tie(PrevDiag, OldLocation) =
3335       getNoteDiagForInvalidRedeclaration(Old, New);
3336 
3337   // Don't complain about this if we're in GNU89 mode and the old function
3338   // is an extern inline function.
3339   // Don't complain about specializations. They are not supposed to have
3340   // storage classes.
3341   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3342       New->getStorageClass() == SC_Static &&
3343       Old->hasExternalFormalLinkage() &&
3344       !New->getTemplateSpecializationInfo() &&
3345       !canRedefineFunction(Old, getLangOpts())) {
3346     if (getLangOpts().MicrosoftExt) {
3347       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3348       Diag(OldLocation, PrevDiag);
3349     } else {
3350       Diag(New->getLocation(), diag::err_static_non_static) << New;
3351       Diag(OldLocation, PrevDiag);
3352       return true;
3353     }
3354   }
3355 
3356   if (New->hasAttr<InternalLinkageAttr>() &&
3357       !Old->hasAttr<InternalLinkageAttr>()) {
3358     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3359         << New->getDeclName();
3360     notePreviousDefinition(Old, New->getLocation());
3361     New->dropAttr<InternalLinkageAttr>();
3362   }
3363 
3364   if (CheckRedeclarationModuleOwnership(New, Old))
3365     return true;
3366 
3367   if (!getLangOpts().CPlusPlus) {
3368     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3369     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3370       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3371         << New << OldOvl;
3372 
3373       // Try our best to find a decl that actually has the overloadable
3374       // attribute for the note. In most cases (e.g. programs with only one
3375       // broken declaration/definition), this won't matter.
3376       //
3377       // FIXME: We could do this if we juggled some extra state in
3378       // OverloadableAttr, rather than just removing it.
3379       const Decl *DiagOld = Old;
3380       if (OldOvl) {
3381         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3382           const auto *A = D->getAttr<OverloadableAttr>();
3383           return A && !A->isImplicit();
3384         });
3385         // If we've implicitly added *all* of the overloadable attrs to this
3386         // chain, emitting a "previous redecl" note is pointless.
3387         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3388       }
3389 
3390       if (DiagOld)
3391         Diag(DiagOld->getLocation(),
3392              diag::note_attribute_overloadable_prev_overload)
3393           << OldOvl;
3394 
3395       if (OldOvl)
3396         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3397       else
3398         New->dropAttr<OverloadableAttr>();
3399     }
3400   }
3401 
3402   // If a function is first declared with a calling convention, but is later
3403   // declared or defined without one, all following decls assume the calling
3404   // convention of the first.
3405   //
3406   // It's OK if a function is first declared without a calling convention,
3407   // but is later declared or defined with the default calling convention.
3408   //
3409   // To test if either decl has an explicit calling convention, we look for
3410   // AttributedType sugar nodes on the type as written.  If they are missing or
3411   // were canonicalized away, we assume the calling convention was implicit.
3412   //
3413   // Note also that we DO NOT return at this point, because we still have
3414   // other tests to run.
3415   QualType OldQType = Context.getCanonicalType(Old->getType());
3416   QualType NewQType = Context.getCanonicalType(New->getType());
3417   const FunctionType *OldType = cast<FunctionType>(OldQType);
3418   const FunctionType *NewType = cast<FunctionType>(NewQType);
3419   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3420   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3421   bool RequiresAdjustment = false;
3422 
3423   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3424     FunctionDecl *First = Old->getFirstDecl();
3425     const FunctionType *FT =
3426         First->getType().getCanonicalType()->castAs<FunctionType>();
3427     FunctionType::ExtInfo FI = FT->getExtInfo();
3428     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3429     if (!NewCCExplicit) {
3430       // Inherit the CC from the previous declaration if it was specified
3431       // there but not here.
3432       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3433       RequiresAdjustment = true;
3434     } else if (Old->getBuiltinID()) {
3435       // Builtin attribute isn't propagated to the new one yet at this point,
3436       // so we check if the old one is a builtin.
3437 
3438       // Calling Conventions on a Builtin aren't really useful and setting a
3439       // default calling convention and cdecl'ing some builtin redeclarations is
3440       // common, so warn and ignore the calling convention on the redeclaration.
3441       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3442           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3443           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3444       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3445       RequiresAdjustment = true;
3446     } else {
3447       // Calling conventions aren't compatible, so complain.
3448       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3449       Diag(New->getLocation(), diag::err_cconv_change)
3450         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3451         << !FirstCCExplicit
3452         << (!FirstCCExplicit ? "" :
3453             FunctionType::getNameForCallConv(FI.getCC()));
3454 
3455       // Put the note on the first decl, since it is the one that matters.
3456       Diag(First->getLocation(), diag::note_previous_declaration);
3457       return true;
3458     }
3459   }
3460 
3461   // FIXME: diagnose the other way around?
3462   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3463     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3464     RequiresAdjustment = true;
3465   }
3466 
3467   // Merge regparm attribute.
3468   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3469       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3470     if (NewTypeInfo.getHasRegParm()) {
3471       Diag(New->getLocation(), diag::err_regparm_mismatch)
3472         << NewType->getRegParmType()
3473         << OldType->getRegParmType();
3474       Diag(OldLocation, diag::note_previous_declaration);
3475       return true;
3476     }
3477 
3478     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3479     RequiresAdjustment = true;
3480   }
3481 
3482   // Merge ns_returns_retained attribute.
3483   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3484     if (NewTypeInfo.getProducesResult()) {
3485       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3486           << "'ns_returns_retained'";
3487       Diag(OldLocation, diag::note_previous_declaration);
3488       return true;
3489     }
3490 
3491     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3492     RequiresAdjustment = true;
3493   }
3494 
3495   if (OldTypeInfo.getNoCallerSavedRegs() !=
3496       NewTypeInfo.getNoCallerSavedRegs()) {
3497     if (NewTypeInfo.getNoCallerSavedRegs()) {
3498       AnyX86NoCallerSavedRegistersAttr *Attr =
3499         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3500       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3501       Diag(OldLocation, diag::note_previous_declaration);
3502       return true;
3503     }
3504 
3505     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3506     RequiresAdjustment = true;
3507   }
3508 
3509   if (RequiresAdjustment) {
3510     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3511     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3512     New->setType(QualType(AdjustedType, 0));
3513     NewQType = Context.getCanonicalType(New->getType());
3514   }
3515 
3516   // If this redeclaration makes the function inline, we may need to add it to
3517   // UndefinedButUsed.
3518   if (!Old->isInlined() && New->isInlined() &&
3519       !New->hasAttr<GNUInlineAttr>() &&
3520       !getLangOpts().GNUInline &&
3521       Old->isUsed(false) &&
3522       !Old->isDefined() && !New->isThisDeclarationADefinition())
3523     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3524                                            SourceLocation()));
3525 
3526   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3527   // about it.
3528   if (New->hasAttr<GNUInlineAttr>() &&
3529       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3530     UndefinedButUsed.erase(Old->getCanonicalDecl());
3531   }
3532 
3533   // If pass_object_size params don't match up perfectly, this isn't a valid
3534   // redeclaration.
3535   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3536       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3537     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3538         << New->getDeclName();
3539     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3540     return true;
3541   }
3542 
3543   if (getLangOpts().CPlusPlus) {
3544     // C++1z [over.load]p2
3545     //   Certain function declarations cannot be overloaded:
3546     //     -- Function declarations that differ only in the return type,
3547     //        the exception specification, or both cannot be overloaded.
3548 
3549     // Check the exception specifications match. This may recompute the type of
3550     // both Old and New if it resolved exception specifications, so grab the
3551     // types again after this. Because this updates the type, we do this before
3552     // any of the other checks below, which may update the "de facto" NewQType
3553     // but do not necessarily update the type of New.
3554     if (CheckEquivalentExceptionSpec(Old, New))
3555       return true;
3556     OldQType = Context.getCanonicalType(Old->getType());
3557     NewQType = Context.getCanonicalType(New->getType());
3558 
3559     // Go back to the type source info to compare the declared return types,
3560     // per C++1y [dcl.type.auto]p13:
3561     //   Redeclarations or specializations of a function or function template
3562     //   with a declared return type that uses a placeholder type shall also
3563     //   use that placeholder, not a deduced type.
3564     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3565     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3566     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3567         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3568                                        OldDeclaredReturnType)) {
3569       QualType ResQT;
3570       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3571           OldDeclaredReturnType->isObjCObjectPointerType())
3572         // FIXME: This does the wrong thing for a deduced return type.
3573         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3574       if (ResQT.isNull()) {
3575         if (New->isCXXClassMember() && New->isOutOfLine())
3576           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3577               << New << New->getReturnTypeSourceRange();
3578         else
3579           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3580               << New->getReturnTypeSourceRange();
3581         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3582                                     << Old->getReturnTypeSourceRange();
3583         return true;
3584       }
3585       else
3586         NewQType = ResQT;
3587     }
3588 
3589     QualType OldReturnType = OldType->getReturnType();
3590     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3591     if (OldReturnType != NewReturnType) {
3592       // If this function has a deduced return type and has already been
3593       // defined, copy the deduced value from the old declaration.
3594       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3595       if (OldAT && OldAT->isDeduced()) {
3596         New->setType(
3597             SubstAutoType(New->getType(),
3598                           OldAT->isDependentType() ? Context.DependentTy
3599                                                    : OldAT->getDeducedType()));
3600         NewQType = Context.getCanonicalType(
3601             SubstAutoType(NewQType,
3602                           OldAT->isDependentType() ? Context.DependentTy
3603                                                    : OldAT->getDeducedType()));
3604       }
3605     }
3606 
3607     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3608     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3609     if (OldMethod && NewMethod) {
3610       // Preserve triviality.
3611       NewMethod->setTrivial(OldMethod->isTrivial());
3612 
3613       // MSVC allows explicit template specialization at class scope:
3614       // 2 CXXMethodDecls referring to the same function will be injected.
3615       // We don't want a redeclaration error.
3616       bool IsClassScopeExplicitSpecialization =
3617                               OldMethod->isFunctionTemplateSpecialization() &&
3618                               NewMethod->isFunctionTemplateSpecialization();
3619       bool isFriend = NewMethod->getFriendObjectKind();
3620 
3621       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3622           !IsClassScopeExplicitSpecialization) {
3623         //    -- Member function declarations with the same name and the
3624         //       same parameter types cannot be overloaded if any of them
3625         //       is a static member function declaration.
3626         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3627           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3628           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3629           return true;
3630         }
3631 
3632         // C++ [class.mem]p1:
3633         //   [...] A member shall not be declared twice in the
3634         //   member-specification, except that a nested class or member
3635         //   class template can be declared and then later defined.
3636         if (!inTemplateInstantiation()) {
3637           unsigned NewDiag;
3638           if (isa<CXXConstructorDecl>(OldMethod))
3639             NewDiag = diag::err_constructor_redeclared;
3640           else if (isa<CXXDestructorDecl>(NewMethod))
3641             NewDiag = diag::err_destructor_redeclared;
3642           else if (isa<CXXConversionDecl>(NewMethod))
3643             NewDiag = diag::err_conv_function_redeclared;
3644           else
3645             NewDiag = diag::err_member_redeclared;
3646 
3647           Diag(New->getLocation(), NewDiag);
3648         } else {
3649           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3650             << New << New->getType();
3651         }
3652         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3653         return true;
3654 
3655       // Complain if this is an explicit declaration of a special
3656       // member that was initially declared implicitly.
3657       //
3658       // As an exception, it's okay to befriend such methods in order
3659       // to permit the implicit constructor/destructor/operator calls.
3660       } else if (OldMethod->isImplicit()) {
3661         if (isFriend) {
3662           NewMethod->setImplicit();
3663         } else {
3664           Diag(NewMethod->getLocation(),
3665                diag::err_definition_of_implicitly_declared_member)
3666             << New << getSpecialMember(OldMethod);
3667           return true;
3668         }
3669       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3670         Diag(NewMethod->getLocation(),
3671              diag::err_definition_of_explicitly_defaulted_member)
3672           << getSpecialMember(OldMethod);
3673         return true;
3674       }
3675     }
3676 
3677     // C++11 [dcl.attr.noreturn]p1:
3678     //   The first declaration of a function shall specify the noreturn
3679     //   attribute if any declaration of that function specifies the noreturn
3680     //   attribute.
3681     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3682     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3683       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3684       Diag(Old->getFirstDecl()->getLocation(),
3685            diag::note_noreturn_missing_first_decl);
3686     }
3687 
3688     // C++11 [dcl.attr.depend]p2:
3689     //   The first declaration of a function shall specify the
3690     //   carries_dependency attribute for its declarator-id if any declaration
3691     //   of the function specifies the carries_dependency attribute.
3692     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3693     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3694       Diag(CDA->getLocation(),
3695            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3696       Diag(Old->getFirstDecl()->getLocation(),
3697            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3698     }
3699 
3700     // (C++98 8.3.5p3):
3701     //   All declarations for a function shall agree exactly in both the
3702     //   return type and the parameter-type-list.
3703     // We also want to respect all the extended bits except noreturn.
3704 
3705     // noreturn should now match unless the old type info didn't have it.
3706     QualType OldQTypeForComparison = OldQType;
3707     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3708       auto *OldType = OldQType->castAs<FunctionProtoType>();
3709       const FunctionType *OldTypeForComparison
3710         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3711       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3712       assert(OldQTypeForComparison.isCanonical());
3713     }
3714 
3715     if (haveIncompatibleLanguageLinkages(Old, New)) {
3716       // As a special case, retain the language linkage from previous
3717       // declarations of a friend function as an extension.
3718       //
3719       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3720       // and is useful because there's otherwise no way to specify language
3721       // linkage within class scope.
3722       //
3723       // Check cautiously as the friend object kind isn't yet complete.
3724       if (New->getFriendObjectKind() != Decl::FOK_None) {
3725         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3726         Diag(OldLocation, PrevDiag);
3727       } else {
3728         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3729         Diag(OldLocation, PrevDiag);
3730         return true;
3731       }
3732     }
3733 
3734     // If the function types are compatible, merge the declarations. Ignore the
3735     // exception specifier because it was already checked above in
3736     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3737     // about incompatible types under -fms-compatibility.
3738     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3739                                                          NewQType))
3740       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3741 
3742     // If the types are imprecise (due to dependent constructs in friends or
3743     // local extern declarations), it's OK if they differ. We'll check again
3744     // during instantiation.
3745     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3746       return false;
3747 
3748     // Fall through for conflicting redeclarations and redefinitions.
3749   }
3750 
3751   // C: Function types need to be compatible, not identical. This handles
3752   // duplicate function decls like "void f(int); void f(enum X);" properly.
3753   if (!getLangOpts().CPlusPlus &&
3754       Context.typesAreCompatible(OldQType, NewQType)) {
3755     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3756     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3757     const FunctionProtoType *OldProto = nullptr;
3758     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3759         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3760       // The old declaration provided a function prototype, but the
3761       // new declaration does not. Merge in the prototype.
3762       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3763       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3764       NewQType =
3765           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3766                                   OldProto->getExtProtoInfo());
3767       New->setType(NewQType);
3768       New->setHasInheritedPrototype();
3769 
3770       // Synthesize parameters with the same types.
3771       SmallVector<ParmVarDecl*, 16> Params;
3772       for (const auto &ParamType : OldProto->param_types()) {
3773         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3774                                                  SourceLocation(), nullptr,
3775                                                  ParamType, /*TInfo=*/nullptr,
3776                                                  SC_None, nullptr);
3777         Param->setScopeInfo(0, Params.size());
3778         Param->setImplicit();
3779         Params.push_back(Param);
3780       }
3781 
3782       New->setParams(Params);
3783     }
3784 
3785     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3786   }
3787 
3788   // Check if the function types are compatible when pointer size address
3789   // spaces are ignored.
3790   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3791     return false;
3792 
3793   // GNU C permits a K&R definition to follow a prototype declaration
3794   // if the declared types of the parameters in the K&R definition
3795   // match the types in the prototype declaration, even when the
3796   // promoted types of the parameters from the K&R definition differ
3797   // from the types in the prototype. GCC then keeps the types from
3798   // the prototype.
3799   //
3800   // If a variadic prototype is followed by a non-variadic K&R definition,
3801   // the K&R definition becomes variadic.  This is sort of an edge case, but
3802   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3803   // C99 6.9.1p8.
3804   if (!getLangOpts().CPlusPlus &&
3805       Old->hasPrototype() && !New->hasPrototype() &&
3806       New->getType()->getAs<FunctionProtoType>() &&
3807       Old->getNumParams() == New->getNumParams()) {
3808     SmallVector<QualType, 16> ArgTypes;
3809     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3810     const FunctionProtoType *OldProto
3811       = Old->getType()->getAs<FunctionProtoType>();
3812     const FunctionProtoType *NewProto
3813       = New->getType()->getAs<FunctionProtoType>();
3814 
3815     // Determine whether this is the GNU C extension.
3816     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3817                                                NewProto->getReturnType());
3818     bool LooseCompatible = !MergedReturn.isNull();
3819     for (unsigned Idx = 0, End = Old->getNumParams();
3820          LooseCompatible && Idx != End; ++Idx) {
3821       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3822       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3823       if (Context.typesAreCompatible(OldParm->getType(),
3824                                      NewProto->getParamType(Idx))) {
3825         ArgTypes.push_back(NewParm->getType());
3826       } else if (Context.typesAreCompatible(OldParm->getType(),
3827                                             NewParm->getType(),
3828                                             /*CompareUnqualified=*/true)) {
3829         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3830                                            NewProto->getParamType(Idx) };
3831         Warnings.push_back(Warn);
3832         ArgTypes.push_back(NewParm->getType());
3833       } else
3834         LooseCompatible = false;
3835     }
3836 
3837     if (LooseCompatible) {
3838       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3839         Diag(Warnings[Warn].NewParm->getLocation(),
3840              diag::ext_param_promoted_not_compatible_with_prototype)
3841           << Warnings[Warn].PromotedType
3842           << Warnings[Warn].OldParm->getType();
3843         if (Warnings[Warn].OldParm->getLocation().isValid())
3844           Diag(Warnings[Warn].OldParm->getLocation(),
3845                diag::note_previous_declaration);
3846       }
3847 
3848       if (MergeTypeWithOld)
3849         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3850                                              OldProto->getExtProtoInfo()));
3851       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3852     }
3853 
3854     // Fall through to diagnose conflicting types.
3855   }
3856 
3857   // A function that has already been declared has been redeclared or
3858   // defined with a different type; show an appropriate diagnostic.
3859 
3860   // If the previous declaration was an implicitly-generated builtin
3861   // declaration, then at the very least we should use a specialized note.
3862   unsigned BuiltinID;
3863   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3864     // If it's actually a library-defined builtin function like 'malloc'
3865     // or 'printf', just warn about the incompatible redeclaration.
3866     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3867       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3868       Diag(OldLocation, diag::note_previous_builtin_declaration)
3869         << Old << Old->getType();
3870       return false;
3871     }
3872 
3873     PrevDiag = diag::note_previous_builtin_declaration;
3874   }
3875 
3876   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3877   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3878   return true;
3879 }
3880 
3881 /// Completes the merge of two function declarations that are
3882 /// known to be compatible.
3883 ///
3884 /// This routine handles the merging of attributes and other
3885 /// properties of function declarations from the old declaration to
3886 /// the new declaration, once we know that New is in fact a
3887 /// redeclaration of Old.
3888 ///
3889 /// \returns false
3890 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3891                                         Scope *S, bool MergeTypeWithOld) {
3892   // Merge the attributes
3893   mergeDeclAttributes(New, Old);
3894 
3895   // Merge "pure" flag.
3896   if (Old->isPure())
3897     New->setPure();
3898 
3899   // Merge "used" flag.
3900   if (Old->getMostRecentDecl()->isUsed(false))
3901     New->setIsUsed();
3902 
3903   // Merge attributes from the parameters.  These can mismatch with K&R
3904   // declarations.
3905   if (New->getNumParams() == Old->getNumParams())
3906       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3907         ParmVarDecl *NewParam = New->getParamDecl(i);
3908         ParmVarDecl *OldParam = Old->getParamDecl(i);
3909         mergeParamDeclAttributes(NewParam, OldParam, *this);
3910         mergeParamDeclTypes(NewParam, OldParam, *this);
3911       }
3912 
3913   if (getLangOpts().CPlusPlus)
3914     return MergeCXXFunctionDecl(New, Old, S);
3915 
3916   // Merge the function types so the we get the composite types for the return
3917   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3918   // was visible.
3919   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3920   if (!Merged.isNull() && MergeTypeWithOld)
3921     New->setType(Merged);
3922 
3923   return false;
3924 }
3925 
3926 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3927                                 ObjCMethodDecl *oldMethod) {
3928   // Merge the attributes, including deprecated/unavailable
3929   AvailabilityMergeKind MergeKind =
3930       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3931           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3932                                      : AMK_ProtocolImplementation)
3933           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3934                                                            : AMK_Override;
3935 
3936   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3937 
3938   // Merge attributes from the parameters.
3939   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3940                                        oe = oldMethod->param_end();
3941   for (ObjCMethodDecl::param_iterator
3942          ni = newMethod->param_begin(), ne = newMethod->param_end();
3943        ni != ne && oi != oe; ++ni, ++oi)
3944     mergeParamDeclAttributes(*ni, *oi, *this);
3945 
3946   CheckObjCMethodOverride(newMethod, oldMethod);
3947 }
3948 
3949 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3950   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3951 
3952   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3953          ? diag::err_redefinition_different_type
3954          : diag::err_redeclaration_different_type)
3955     << New->getDeclName() << New->getType() << Old->getType();
3956 
3957   diag::kind PrevDiag;
3958   SourceLocation OldLocation;
3959   std::tie(PrevDiag, OldLocation)
3960     = getNoteDiagForInvalidRedeclaration(Old, New);
3961   S.Diag(OldLocation, PrevDiag);
3962   New->setInvalidDecl();
3963 }
3964 
3965 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3966 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3967 /// emitting diagnostics as appropriate.
3968 ///
3969 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3970 /// to here in AddInitializerToDecl. We can't check them before the initializer
3971 /// is attached.
3972 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3973                              bool MergeTypeWithOld) {
3974   if (New->isInvalidDecl() || Old->isInvalidDecl())
3975     return;
3976 
3977   QualType MergedT;
3978   if (getLangOpts().CPlusPlus) {
3979     if (New->getType()->isUndeducedType()) {
3980       // We don't know what the new type is until the initializer is attached.
3981       return;
3982     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3983       // These could still be something that needs exception specs checked.
3984       return MergeVarDeclExceptionSpecs(New, Old);
3985     }
3986     // C++ [basic.link]p10:
3987     //   [...] the types specified by all declarations referring to a given
3988     //   object or function shall be identical, except that declarations for an
3989     //   array object can specify array types that differ by the presence or
3990     //   absence of a major array bound (8.3.4).
3991     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3992       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3993       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3994 
3995       // We are merging a variable declaration New into Old. If it has an array
3996       // bound, and that bound differs from Old's bound, we should diagnose the
3997       // mismatch.
3998       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3999         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4000              PrevVD = PrevVD->getPreviousDecl()) {
4001           QualType PrevVDTy = PrevVD->getType();
4002           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4003             continue;
4004 
4005           if (!Context.hasSameType(New->getType(), PrevVDTy))
4006             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4007         }
4008       }
4009 
4010       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4011         if (Context.hasSameType(OldArray->getElementType(),
4012                                 NewArray->getElementType()))
4013           MergedT = New->getType();
4014       }
4015       // FIXME: Check visibility. New is hidden but has a complete type. If New
4016       // has no array bound, it should not inherit one from Old, if Old is not
4017       // visible.
4018       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4019         if (Context.hasSameType(OldArray->getElementType(),
4020                                 NewArray->getElementType()))
4021           MergedT = Old->getType();
4022       }
4023     }
4024     else if (New->getType()->isObjCObjectPointerType() &&
4025                Old->getType()->isObjCObjectPointerType()) {
4026       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4027                                               Old->getType());
4028     }
4029   } else {
4030     // C 6.2.7p2:
4031     //   All declarations that refer to the same object or function shall have
4032     //   compatible type.
4033     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4034   }
4035   if (MergedT.isNull()) {
4036     // It's OK if we couldn't merge types if either type is dependent, for a
4037     // block-scope variable. In other cases (static data members of class
4038     // templates, variable templates, ...), we require the types to be
4039     // equivalent.
4040     // FIXME: The C++ standard doesn't say anything about this.
4041     if ((New->getType()->isDependentType() ||
4042          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4043       // If the old type was dependent, we can't merge with it, so the new type
4044       // becomes dependent for now. We'll reproduce the original type when we
4045       // instantiate the TypeSourceInfo for the variable.
4046       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4047         New->setType(Context.DependentTy);
4048       return;
4049     }
4050     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4051   }
4052 
4053   // Don't actually update the type on the new declaration if the old
4054   // declaration was an extern declaration in a different scope.
4055   if (MergeTypeWithOld)
4056     New->setType(MergedT);
4057 }
4058 
4059 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4060                                   LookupResult &Previous) {
4061   // C11 6.2.7p4:
4062   //   For an identifier with internal or external linkage declared
4063   //   in a scope in which a prior declaration of that identifier is
4064   //   visible, if the prior declaration specifies internal or
4065   //   external linkage, the type of the identifier at the later
4066   //   declaration becomes the composite type.
4067   //
4068   // If the variable isn't visible, we do not merge with its type.
4069   if (Previous.isShadowed())
4070     return false;
4071 
4072   if (S.getLangOpts().CPlusPlus) {
4073     // C++11 [dcl.array]p3:
4074     //   If there is a preceding declaration of the entity in the same
4075     //   scope in which the bound was specified, an omitted array bound
4076     //   is taken to be the same as in that earlier declaration.
4077     return NewVD->isPreviousDeclInSameBlockScope() ||
4078            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4079             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4080   } else {
4081     // If the old declaration was function-local, don't merge with its
4082     // type unless we're in the same function.
4083     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4084            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4085   }
4086 }
4087 
4088 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4089 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4090 /// situation, merging decls or emitting diagnostics as appropriate.
4091 ///
4092 /// Tentative definition rules (C99 6.9.2p2) are checked by
4093 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4094 /// definitions here, since the initializer hasn't been attached.
4095 ///
4096 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4097   // If the new decl is already invalid, don't do any other checking.
4098   if (New->isInvalidDecl())
4099     return;
4100 
4101   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4102     return;
4103 
4104   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4105 
4106   // Verify the old decl was also a variable or variable template.
4107   VarDecl *Old = nullptr;
4108   VarTemplateDecl *OldTemplate = nullptr;
4109   if (Previous.isSingleResult()) {
4110     if (NewTemplate) {
4111       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4112       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4113 
4114       if (auto *Shadow =
4115               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4116         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4117           return New->setInvalidDecl();
4118     } else {
4119       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4120 
4121       if (auto *Shadow =
4122               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4123         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4124           return New->setInvalidDecl();
4125     }
4126   }
4127   if (!Old) {
4128     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4129         << New->getDeclName();
4130     notePreviousDefinition(Previous.getRepresentativeDecl(),
4131                            New->getLocation());
4132     return New->setInvalidDecl();
4133   }
4134 
4135   // If the old declaration was found in an inline namespace and the new
4136   // declaration was qualified, update the DeclContext to match.
4137   adjustDeclContextForDeclaratorDecl(New, Old);
4138 
4139   // Ensure the template parameters are compatible.
4140   if (NewTemplate &&
4141       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4142                                       OldTemplate->getTemplateParameters(),
4143                                       /*Complain=*/true, TPL_TemplateMatch))
4144     return New->setInvalidDecl();
4145 
4146   // C++ [class.mem]p1:
4147   //   A member shall not be declared twice in the member-specification [...]
4148   //
4149   // Here, we need only consider static data members.
4150   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4151     Diag(New->getLocation(), diag::err_duplicate_member)
4152       << New->getIdentifier();
4153     Diag(Old->getLocation(), diag::note_previous_declaration);
4154     New->setInvalidDecl();
4155   }
4156 
4157   mergeDeclAttributes(New, Old);
4158   // Warn if an already-declared variable is made a weak_import in a subsequent
4159   // declaration
4160   if (New->hasAttr<WeakImportAttr>() &&
4161       Old->getStorageClass() == SC_None &&
4162       !Old->hasAttr<WeakImportAttr>()) {
4163     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4164     notePreviousDefinition(Old, New->getLocation());
4165     // Remove weak_import attribute on new declaration.
4166     New->dropAttr<WeakImportAttr>();
4167   }
4168 
4169   if (New->hasAttr<InternalLinkageAttr>() &&
4170       !Old->hasAttr<InternalLinkageAttr>()) {
4171     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4172         << New->getDeclName();
4173     notePreviousDefinition(Old, New->getLocation());
4174     New->dropAttr<InternalLinkageAttr>();
4175   }
4176 
4177   // Merge the types.
4178   VarDecl *MostRecent = Old->getMostRecentDecl();
4179   if (MostRecent != Old) {
4180     MergeVarDeclTypes(New, MostRecent,
4181                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4182     if (New->isInvalidDecl())
4183       return;
4184   }
4185 
4186   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4187   if (New->isInvalidDecl())
4188     return;
4189 
4190   diag::kind PrevDiag;
4191   SourceLocation OldLocation;
4192   std::tie(PrevDiag, OldLocation) =
4193       getNoteDiagForInvalidRedeclaration(Old, New);
4194 
4195   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4196   if (New->getStorageClass() == SC_Static &&
4197       !New->isStaticDataMember() &&
4198       Old->hasExternalFormalLinkage()) {
4199     if (getLangOpts().MicrosoftExt) {
4200       Diag(New->getLocation(), diag::ext_static_non_static)
4201           << New->getDeclName();
4202       Diag(OldLocation, PrevDiag);
4203     } else {
4204       Diag(New->getLocation(), diag::err_static_non_static)
4205           << New->getDeclName();
4206       Diag(OldLocation, PrevDiag);
4207       return New->setInvalidDecl();
4208     }
4209   }
4210   // C99 6.2.2p4:
4211   //   For an identifier declared with the storage-class specifier
4212   //   extern in a scope in which a prior declaration of that
4213   //   identifier is visible,23) if the prior declaration specifies
4214   //   internal or external linkage, the linkage of the identifier at
4215   //   the later declaration is the same as the linkage specified at
4216   //   the prior declaration. If no prior declaration is visible, or
4217   //   if the prior declaration specifies no linkage, then the
4218   //   identifier has external linkage.
4219   if (New->hasExternalStorage() && Old->hasLinkage())
4220     /* Okay */;
4221   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4222            !New->isStaticDataMember() &&
4223            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4224     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4225     Diag(OldLocation, PrevDiag);
4226     return New->setInvalidDecl();
4227   }
4228 
4229   // Check if extern is followed by non-extern and vice-versa.
4230   if (New->hasExternalStorage() &&
4231       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4232     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4233     Diag(OldLocation, PrevDiag);
4234     return New->setInvalidDecl();
4235   }
4236   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4237       !New->hasExternalStorage()) {
4238     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4239     Diag(OldLocation, PrevDiag);
4240     return New->setInvalidDecl();
4241   }
4242 
4243   if (CheckRedeclarationModuleOwnership(New, Old))
4244     return;
4245 
4246   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4247 
4248   // FIXME: The test for external storage here seems wrong? We still
4249   // need to check for mismatches.
4250   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4251       // Don't complain about out-of-line definitions of static members.
4252       !(Old->getLexicalDeclContext()->isRecord() &&
4253         !New->getLexicalDeclContext()->isRecord())) {
4254     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4255     Diag(OldLocation, PrevDiag);
4256     return New->setInvalidDecl();
4257   }
4258 
4259   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4260     if (VarDecl *Def = Old->getDefinition()) {
4261       // C++1z [dcl.fcn.spec]p4:
4262       //   If the definition of a variable appears in a translation unit before
4263       //   its first declaration as inline, the program is ill-formed.
4264       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4265       Diag(Def->getLocation(), diag::note_previous_definition);
4266     }
4267   }
4268 
4269   // If this redeclaration makes the variable inline, we may need to add it to
4270   // UndefinedButUsed.
4271   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4272       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4273     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4274                                            SourceLocation()));
4275 
4276   if (New->getTLSKind() != Old->getTLSKind()) {
4277     if (!Old->getTLSKind()) {
4278       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4279       Diag(OldLocation, PrevDiag);
4280     } else if (!New->getTLSKind()) {
4281       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4282       Diag(OldLocation, PrevDiag);
4283     } else {
4284       // Do not allow redeclaration to change the variable between requiring
4285       // static and dynamic initialization.
4286       // FIXME: GCC allows this, but uses the TLS keyword on the first
4287       // declaration to determine the kind. Do we need to be compatible here?
4288       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4289         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4290       Diag(OldLocation, PrevDiag);
4291     }
4292   }
4293 
4294   // C++ doesn't have tentative definitions, so go right ahead and check here.
4295   if (getLangOpts().CPlusPlus &&
4296       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4297     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4298         Old->getCanonicalDecl()->isConstexpr()) {
4299       // This definition won't be a definition any more once it's been merged.
4300       Diag(New->getLocation(),
4301            diag::warn_deprecated_redundant_constexpr_static_def);
4302     } else if (VarDecl *Def = Old->getDefinition()) {
4303       if (checkVarDeclRedefinition(Def, New))
4304         return;
4305     }
4306   }
4307 
4308   if (haveIncompatibleLanguageLinkages(Old, New)) {
4309     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4310     Diag(OldLocation, PrevDiag);
4311     New->setInvalidDecl();
4312     return;
4313   }
4314 
4315   // Merge "used" flag.
4316   if (Old->getMostRecentDecl()->isUsed(false))
4317     New->setIsUsed();
4318 
4319   // Keep a chain of previous declarations.
4320   New->setPreviousDecl(Old);
4321   if (NewTemplate)
4322     NewTemplate->setPreviousDecl(OldTemplate);
4323 
4324   // Inherit access appropriately.
4325   New->setAccess(Old->getAccess());
4326   if (NewTemplate)
4327     NewTemplate->setAccess(New->getAccess());
4328 
4329   if (Old->isInline())
4330     New->setImplicitlyInline();
4331 }
4332 
4333 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4334   SourceManager &SrcMgr = getSourceManager();
4335   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4336   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4337   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4338   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4339   auto &HSI = PP.getHeaderSearchInfo();
4340   StringRef HdrFilename =
4341       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4342 
4343   auto noteFromModuleOrInclude = [&](Module *Mod,
4344                                      SourceLocation IncLoc) -> bool {
4345     // Redefinition errors with modules are common with non modular mapped
4346     // headers, example: a non-modular header H in module A that also gets
4347     // included directly in a TU. Pointing twice to the same header/definition
4348     // is confusing, try to get better diagnostics when modules is on.
4349     if (IncLoc.isValid()) {
4350       if (Mod) {
4351         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4352             << HdrFilename.str() << Mod->getFullModuleName();
4353         if (!Mod->DefinitionLoc.isInvalid())
4354           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4355               << Mod->getFullModuleName();
4356       } else {
4357         Diag(IncLoc, diag::note_redefinition_include_same_file)
4358             << HdrFilename.str();
4359       }
4360       return true;
4361     }
4362 
4363     return false;
4364   };
4365 
4366   // Is it the same file and same offset? Provide more information on why
4367   // this leads to a redefinition error.
4368   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4369     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4370     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4371     bool EmittedDiag =
4372         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4373     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4374 
4375     // If the header has no guards, emit a note suggesting one.
4376     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4377       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4378 
4379     if (EmittedDiag)
4380       return;
4381   }
4382 
4383   // Redefinition coming from different files or couldn't do better above.
4384   if (Old->getLocation().isValid())
4385     Diag(Old->getLocation(), diag::note_previous_definition);
4386 }
4387 
4388 /// We've just determined that \p Old and \p New both appear to be definitions
4389 /// of the same variable. Either diagnose or fix the problem.
4390 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4391   if (!hasVisibleDefinition(Old) &&
4392       (New->getFormalLinkage() == InternalLinkage ||
4393        New->isInline() ||
4394        New->getDescribedVarTemplate() ||
4395        New->getNumTemplateParameterLists() ||
4396        New->getDeclContext()->isDependentContext())) {
4397     // The previous definition is hidden, and multiple definitions are
4398     // permitted (in separate TUs). Demote this to a declaration.
4399     New->demoteThisDefinitionToDeclaration();
4400 
4401     // Make the canonical definition visible.
4402     if (auto *OldTD = Old->getDescribedVarTemplate())
4403       makeMergedDefinitionVisible(OldTD);
4404     makeMergedDefinitionVisible(Old);
4405     return false;
4406   } else {
4407     Diag(New->getLocation(), diag::err_redefinition) << New;
4408     notePreviousDefinition(Old, New->getLocation());
4409     New->setInvalidDecl();
4410     return true;
4411   }
4412 }
4413 
4414 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4415 /// no declarator (e.g. "struct foo;") is parsed.
4416 Decl *
4417 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4418                                  RecordDecl *&AnonRecord) {
4419   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4420                                     AnonRecord);
4421 }
4422 
4423 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4424 // disambiguate entities defined in different scopes.
4425 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4426 // compatibility.
4427 // We will pick our mangling number depending on which version of MSVC is being
4428 // targeted.
4429 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4430   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4431              ? S->getMSCurManglingNumber()
4432              : S->getMSLastManglingNumber();
4433 }
4434 
4435 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4436   if (!Context.getLangOpts().CPlusPlus)
4437     return;
4438 
4439   if (isa<CXXRecordDecl>(Tag->getParent())) {
4440     // If this tag is the direct child of a class, number it if
4441     // it is anonymous.
4442     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4443       return;
4444     MangleNumberingContext &MCtx =
4445         Context.getManglingNumberContext(Tag->getParent());
4446     Context.setManglingNumber(
4447         Tag, MCtx.getManglingNumber(
4448                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4449     return;
4450   }
4451 
4452   // If this tag isn't a direct child of a class, number it if it is local.
4453   MangleNumberingContext *MCtx;
4454   Decl *ManglingContextDecl;
4455   std::tie(MCtx, ManglingContextDecl) =
4456       getCurrentMangleNumberContext(Tag->getDeclContext());
4457   if (MCtx) {
4458     Context.setManglingNumber(
4459         Tag, MCtx->getManglingNumber(
4460                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4461   }
4462 }
4463 
4464 namespace {
4465 struct NonCLikeKind {
4466   enum {
4467     None,
4468     BaseClass,
4469     DefaultMemberInit,
4470     Lambda,
4471     Friend,
4472     OtherMember,
4473     Invalid,
4474   } Kind = None;
4475   SourceRange Range;
4476 
4477   explicit operator bool() { return Kind != None; }
4478 };
4479 }
4480 
4481 /// Determine whether a class is C-like, according to the rules of C++
4482 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4483 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4484   if (RD->isInvalidDecl())
4485     return {NonCLikeKind::Invalid, {}};
4486 
4487   // C++ [dcl.typedef]p9: [P1766R1]
4488   //   An unnamed class with a typedef name for linkage purposes shall not
4489   //
4490   //    -- have any base classes
4491   if (RD->getNumBases())
4492     return {NonCLikeKind::BaseClass,
4493             SourceRange(RD->bases_begin()->getBeginLoc(),
4494                         RD->bases_end()[-1].getEndLoc())};
4495   bool Invalid = false;
4496   for (Decl *D : RD->decls()) {
4497     // Don't complain about things we already diagnosed.
4498     if (D->isInvalidDecl()) {
4499       Invalid = true;
4500       continue;
4501     }
4502 
4503     //  -- have any [...] default member initializers
4504     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4505       if (FD->hasInClassInitializer()) {
4506         auto *Init = FD->getInClassInitializer();
4507         return {NonCLikeKind::DefaultMemberInit,
4508                 Init ? Init->getSourceRange() : D->getSourceRange()};
4509       }
4510       continue;
4511     }
4512 
4513     // FIXME: We don't allow friend declarations. This violates the wording of
4514     // P1766, but not the intent.
4515     if (isa<FriendDecl>(D))
4516       return {NonCLikeKind::Friend, D->getSourceRange()};
4517 
4518     //  -- declare any members other than non-static data members, member
4519     //     enumerations, or member classes,
4520     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4521         isa<EnumDecl>(D))
4522       continue;
4523     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4524     if (!MemberRD) {
4525       if (D->isImplicit())
4526         continue;
4527       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4528     }
4529 
4530     //  -- contain a lambda-expression,
4531     if (MemberRD->isLambda())
4532       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4533 
4534     //  and all member classes shall also satisfy these requirements
4535     //  (recursively).
4536     if (MemberRD->isThisDeclarationADefinition()) {
4537       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4538         return Kind;
4539     }
4540   }
4541 
4542   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4543 }
4544 
4545 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4546                                         TypedefNameDecl *NewTD) {
4547   if (TagFromDeclSpec->isInvalidDecl())
4548     return;
4549 
4550   // Do nothing if the tag already has a name for linkage purposes.
4551   if (TagFromDeclSpec->hasNameForLinkage())
4552     return;
4553 
4554   // A well-formed anonymous tag must always be a TUK_Definition.
4555   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4556 
4557   // The type must match the tag exactly;  no qualifiers allowed.
4558   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4559                            Context.getTagDeclType(TagFromDeclSpec))) {
4560     if (getLangOpts().CPlusPlus)
4561       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4562     return;
4563   }
4564 
4565   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4566   //   An unnamed class with a typedef name for linkage purposes shall [be
4567   //   C-like].
4568   //
4569   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4570   // shouldn't happen, but there are constructs that the language rule doesn't
4571   // disallow for which we can't reasonably avoid computing linkage early.
4572   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4573   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4574                              : NonCLikeKind();
4575   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4576   if (NonCLike || ChangesLinkage) {
4577     if (NonCLike.Kind == NonCLikeKind::Invalid)
4578       return;
4579 
4580     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4581     if (ChangesLinkage) {
4582       // If the linkage changes, we can't accept this as an extension.
4583       if (NonCLike.Kind == NonCLikeKind::None)
4584         DiagID = diag::err_typedef_changes_linkage;
4585       else
4586         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4587     }
4588 
4589     SourceLocation FixitLoc =
4590         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4591     llvm::SmallString<40> TextToInsert;
4592     TextToInsert += ' ';
4593     TextToInsert += NewTD->getIdentifier()->getName();
4594 
4595     Diag(FixitLoc, DiagID)
4596       << isa<TypeAliasDecl>(NewTD)
4597       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4598     if (NonCLike.Kind != NonCLikeKind::None) {
4599       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4600         << NonCLike.Kind - 1 << NonCLike.Range;
4601     }
4602     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4603       << NewTD << isa<TypeAliasDecl>(NewTD);
4604 
4605     if (ChangesLinkage)
4606       return;
4607   }
4608 
4609   // Otherwise, set this as the anon-decl typedef for the tag.
4610   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4611 }
4612 
4613 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4614   switch (T) {
4615   case DeclSpec::TST_class:
4616     return 0;
4617   case DeclSpec::TST_struct:
4618     return 1;
4619   case DeclSpec::TST_interface:
4620     return 2;
4621   case DeclSpec::TST_union:
4622     return 3;
4623   case DeclSpec::TST_enum:
4624     return 4;
4625   default:
4626     llvm_unreachable("unexpected type specifier");
4627   }
4628 }
4629 
4630 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4631 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4632 /// parameters to cope with template friend declarations.
4633 Decl *
4634 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4635                                  MultiTemplateParamsArg TemplateParams,
4636                                  bool IsExplicitInstantiation,
4637                                  RecordDecl *&AnonRecord) {
4638   Decl *TagD = nullptr;
4639   TagDecl *Tag = nullptr;
4640   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4641       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4642       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4643       DS.getTypeSpecType() == DeclSpec::TST_union ||
4644       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4645     TagD = DS.getRepAsDecl();
4646 
4647     if (!TagD) // We probably had an error
4648       return nullptr;
4649 
4650     // Note that the above type specs guarantee that the
4651     // type rep is a Decl, whereas in many of the others
4652     // it's a Type.
4653     if (isa<TagDecl>(TagD))
4654       Tag = cast<TagDecl>(TagD);
4655     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4656       Tag = CTD->getTemplatedDecl();
4657   }
4658 
4659   if (Tag) {
4660     handleTagNumbering(Tag, S);
4661     Tag->setFreeStanding();
4662     if (Tag->isInvalidDecl())
4663       return Tag;
4664   }
4665 
4666   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4667     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4668     // or incomplete types shall not be restrict-qualified."
4669     if (TypeQuals & DeclSpec::TQ_restrict)
4670       Diag(DS.getRestrictSpecLoc(),
4671            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4672            << DS.getSourceRange();
4673   }
4674 
4675   if (DS.isInlineSpecified())
4676     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4677         << getLangOpts().CPlusPlus17;
4678 
4679   if (DS.hasConstexprSpecifier()) {
4680     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4681     // and definitions of functions and variables.
4682     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4683     // the declaration of a function or function template
4684     if (Tag)
4685       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4686           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4687           << static_cast<int>(DS.getConstexprSpecifier());
4688     else
4689       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4690           << static_cast<int>(DS.getConstexprSpecifier());
4691     // Don't emit warnings after this error.
4692     return TagD;
4693   }
4694 
4695   DiagnoseFunctionSpecifiers(DS);
4696 
4697   if (DS.isFriendSpecified()) {
4698     // If we're dealing with a decl but not a TagDecl, assume that
4699     // whatever routines created it handled the friendship aspect.
4700     if (TagD && !Tag)
4701       return nullptr;
4702     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4703   }
4704 
4705   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4706   bool IsExplicitSpecialization =
4707     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4708   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4709       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4710       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4711     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4712     // nested-name-specifier unless it is an explicit instantiation
4713     // or an explicit specialization.
4714     //
4715     // FIXME: We allow class template partial specializations here too, per the
4716     // obvious intent of DR1819.
4717     //
4718     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4719     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4720         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4721     return nullptr;
4722   }
4723 
4724   // Track whether this decl-specifier declares anything.
4725   bool DeclaresAnything = true;
4726 
4727   // Handle anonymous struct definitions.
4728   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4729     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4730         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4731       if (getLangOpts().CPlusPlus ||
4732           Record->getDeclContext()->isRecord()) {
4733         // If CurContext is a DeclContext that can contain statements,
4734         // RecursiveASTVisitor won't visit the decls that
4735         // BuildAnonymousStructOrUnion() will put into CurContext.
4736         // Also store them here so that they can be part of the
4737         // DeclStmt that gets created in this case.
4738         // FIXME: Also return the IndirectFieldDecls created by
4739         // BuildAnonymousStructOr union, for the same reason?
4740         if (CurContext->isFunctionOrMethod())
4741           AnonRecord = Record;
4742         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4743                                            Context.getPrintingPolicy());
4744       }
4745 
4746       DeclaresAnything = false;
4747     }
4748   }
4749 
4750   // C11 6.7.2.1p2:
4751   //   A struct-declaration that does not declare an anonymous structure or
4752   //   anonymous union shall contain a struct-declarator-list.
4753   //
4754   // This rule also existed in C89 and C99; the grammar for struct-declaration
4755   // did not permit a struct-declaration without a struct-declarator-list.
4756   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4757       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4758     // Check for Microsoft C extension: anonymous struct/union member.
4759     // Handle 2 kinds of anonymous struct/union:
4760     //   struct STRUCT;
4761     //   union UNION;
4762     // and
4763     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4764     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4765     if ((Tag && Tag->getDeclName()) ||
4766         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4767       RecordDecl *Record = nullptr;
4768       if (Tag)
4769         Record = dyn_cast<RecordDecl>(Tag);
4770       else if (const RecordType *RT =
4771                    DS.getRepAsType().get()->getAsStructureType())
4772         Record = RT->getDecl();
4773       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4774         Record = UT->getDecl();
4775 
4776       if (Record && getLangOpts().MicrosoftExt) {
4777         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4778             << Record->isUnion() << DS.getSourceRange();
4779         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4780       }
4781 
4782       DeclaresAnything = false;
4783     }
4784   }
4785 
4786   // Skip all the checks below if we have a type error.
4787   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4788       (TagD && TagD->isInvalidDecl()))
4789     return TagD;
4790 
4791   if (getLangOpts().CPlusPlus &&
4792       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4793     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4794       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4795           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4796         DeclaresAnything = false;
4797 
4798   if (!DS.isMissingDeclaratorOk()) {
4799     // Customize diagnostic for a typedef missing a name.
4800     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4801       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4802           << DS.getSourceRange();
4803     else
4804       DeclaresAnything = false;
4805   }
4806 
4807   if (DS.isModulePrivateSpecified() &&
4808       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4809     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4810       << Tag->getTagKind()
4811       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4812 
4813   ActOnDocumentableDecl(TagD);
4814 
4815   // C 6.7/2:
4816   //   A declaration [...] shall declare at least a declarator [...], a tag,
4817   //   or the members of an enumeration.
4818   // C++ [dcl.dcl]p3:
4819   //   [If there are no declarators], and except for the declaration of an
4820   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4821   //   names into the program, or shall redeclare a name introduced by a
4822   //   previous declaration.
4823   if (!DeclaresAnything) {
4824     // In C, we allow this as a (popular) extension / bug. Don't bother
4825     // producing further diagnostics for redundant qualifiers after this.
4826     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4827                                ? diag::err_no_declarators
4828                                : diag::ext_no_declarators)
4829         << DS.getSourceRange();
4830     return TagD;
4831   }
4832 
4833   // C++ [dcl.stc]p1:
4834   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4835   //   init-declarator-list of the declaration shall not be empty.
4836   // C++ [dcl.fct.spec]p1:
4837   //   If a cv-qualifier appears in a decl-specifier-seq, the
4838   //   init-declarator-list of the declaration shall not be empty.
4839   //
4840   // Spurious qualifiers here appear to be valid in C.
4841   unsigned DiagID = diag::warn_standalone_specifier;
4842   if (getLangOpts().CPlusPlus)
4843     DiagID = diag::ext_standalone_specifier;
4844 
4845   // Note that a linkage-specification sets a storage class, but
4846   // 'extern "C" struct foo;' is actually valid and not theoretically
4847   // useless.
4848   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4849     if (SCS == DeclSpec::SCS_mutable)
4850       // Since mutable is not a viable storage class specifier in C, there is
4851       // no reason to treat it as an extension. Instead, diagnose as an error.
4852       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4853     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4854       Diag(DS.getStorageClassSpecLoc(), DiagID)
4855         << DeclSpec::getSpecifierName(SCS);
4856   }
4857 
4858   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4859     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4860       << DeclSpec::getSpecifierName(TSCS);
4861   if (DS.getTypeQualifiers()) {
4862     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4863       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4864     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4865       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4866     // Restrict is covered above.
4867     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4868       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4869     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4870       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4871   }
4872 
4873   // Warn about ignored type attributes, for example:
4874   // __attribute__((aligned)) struct A;
4875   // Attributes should be placed after tag to apply to type declaration.
4876   if (!DS.getAttributes().empty()) {
4877     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4878     if (TypeSpecType == DeclSpec::TST_class ||
4879         TypeSpecType == DeclSpec::TST_struct ||
4880         TypeSpecType == DeclSpec::TST_interface ||
4881         TypeSpecType == DeclSpec::TST_union ||
4882         TypeSpecType == DeclSpec::TST_enum) {
4883       for (const ParsedAttr &AL : DS.getAttributes())
4884         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4885             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4886     }
4887   }
4888 
4889   return TagD;
4890 }
4891 
4892 /// We are trying to inject an anonymous member into the given scope;
4893 /// check if there's an existing declaration that can't be overloaded.
4894 ///
4895 /// \return true if this is a forbidden redeclaration
4896 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4897                                          Scope *S,
4898                                          DeclContext *Owner,
4899                                          DeclarationName Name,
4900                                          SourceLocation NameLoc,
4901                                          bool IsUnion) {
4902   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4903                  Sema::ForVisibleRedeclaration);
4904   if (!SemaRef.LookupName(R, S)) return false;
4905 
4906   // Pick a representative declaration.
4907   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4908   assert(PrevDecl && "Expected a non-null Decl");
4909 
4910   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4911     return false;
4912 
4913   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4914     << IsUnion << Name;
4915   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4916 
4917   return true;
4918 }
4919 
4920 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4921 /// anonymous struct or union AnonRecord into the owning context Owner
4922 /// and scope S. This routine will be invoked just after we realize
4923 /// that an unnamed union or struct is actually an anonymous union or
4924 /// struct, e.g.,
4925 ///
4926 /// @code
4927 /// union {
4928 ///   int i;
4929 ///   float f;
4930 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4931 ///    // f into the surrounding scope.x
4932 /// @endcode
4933 ///
4934 /// This routine is recursive, injecting the names of nested anonymous
4935 /// structs/unions into the owning context and scope as well.
4936 static bool
4937 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4938                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4939                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4940   bool Invalid = false;
4941 
4942   // Look every FieldDecl and IndirectFieldDecl with a name.
4943   for (auto *D : AnonRecord->decls()) {
4944     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4945         cast<NamedDecl>(D)->getDeclName()) {
4946       ValueDecl *VD = cast<ValueDecl>(D);
4947       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4948                                        VD->getLocation(),
4949                                        AnonRecord->isUnion())) {
4950         // C++ [class.union]p2:
4951         //   The names of the members of an anonymous union shall be
4952         //   distinct from the names of any other entity in the
4953         //   scope in which the anonymous union is declared.
4954         Invalid = true;
4955       } else {
4956         // C++ [class.union]p2:
4957         //   For the purpose of name lookup, after the anonymous union
4958         //   definition, the members of the anonymous union are
4959         //   considered to have been defined in the scope in which the
4960         //   anonymous union is declared.
4961         unsigned OldChainingSize = Chaining.size();
4962         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4963           Chaining.append(IF->chain_begin(), IF->chain_end());
4964         else
4965           Chaining.push_back(VD);
4966 
4967         assert(Chaining.size() >= 2);
4968         NamedDecl **NamedChain =
4969           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4970         for (unsigned i = 0; i < Chaining.size(); i++)
4971           NamedChain[i] = Chaining[i];
4972 
4973         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4974             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4975             VD->getType(), {NamedChain, Chaining.size()});
4976 
4977         for (const auto *Attr : VD->attrs())
4978           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4979 
4980         IndirectField->setAccess(AS);
4981         IndirectField->setImplicit();
4982         SemaRef.PushOnScopeChains(IndirectField, S);
4983 
4984         // That includes picking up the appropriate access specifier.
4985         if (AS != AS_none) IndirectField->setAccess(AS);
4986 
4987         Chaining.resize(OldChainingSize);
4988       }
4989     }
4990   }
4991 
4992   return Invalid;
4993 }
4994 
4995 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4996 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4997 /// illegal input values are mapped to SC_None.
4998 static StorageClass
4999 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5000   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5001   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5002          "Parser allowed 'typedef' as storage class VarDecl.");
5003   switch (StorageClassSpec) {
5004   case DeclSpec::SCS_unspecified:    return SC_None;
5005   case DeclSpec::SCS_extern:
5006     if (DS.isExternInLinkageSpec())
5007       return SC_None;
5008     return SC_Extern;
5009   case DeclSpec::SCS_static:         return SC_Static;
5010   case DeclSpec::SCS_auto:           return SC_Auto;
5011   case DeclSpec::SCS_register:       return SC_Register;
5012   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5013     // Illegal SCSs map to None: error reporting is up to the caller.
5014   case DeclSpec::SCS_mutable:        // Fall through.
5015   case DeclSpec::SCS_typedef:        return SC_None;
5016   }
5017   llvm_unreachable("unknown storage class specifier");
5018 }
5019 
5020 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5021   assert(Record->hasInClassInitializer());
5022 
5023   for (const auto *I : Record->decls()) {
5024     const auto *FD = dyn_cast<FieldDecl>(I);
5025     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5026       FD = IFD->getAnonField();
5027     if (FD && FD->hasInClassInitializer())
5028       return FD->getLocation();
5029   }
5030 
5031   llvm_unreachable("couldn't find in-class initializer");
5032 }
5033 
5034 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5035                                       SourceLocation DefaultInitLoc) {
5036   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5037     return;
5038 
5039   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5040   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5041 }
5042 
5043 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5044                                       CXXRecordDecl *AnonUnion) {
5045   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5046     return;
5047 
5048   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5049 }
5050 
5051 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5052 /// anonymous structure or union. Anonymous unions are a C++ feature
5053 /// (C++ [class.union]) and a C11 feature; anonymous structures
5054 /// are a C11 feature and GNU C++ extension.
5055 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5056                                         AccessSpecifier AS,
5057                                         RecordDecl *Record,
5058                                         const PrintingPolicy &Policy) {
5059   DeclContext *Owner = Record->getDeclContext();
5060 
5061   // Diagnose whether this anonymous struct/union is an extension.
5062   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5063     Diag(Record->getLocation(), diag::ext_anonymous_union);
5064   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5065     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5066   else if (!Record->isUnion() && !getLangOpts().C11)
5067     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5068 
5069   // C and C++ require different kinds of checks for anonymous
5070   // structs/unions.
5071   bool Invalid = false;
5072   if (getLangOpts().CPlusPlus) {
5073     const char *PrevSpec = nullptr;
5074     if (Record->isUnion()) {
5075       // C++ [class.union]p6:
5076       // C++17 [class.union.anon]p2:
5077       //   Anonymous unions declared in a named namespace or in the
5078       //   global namespace shall be declared static.
5079       unsigned DiagID;
5080       DeclContext *OwnerScope = Owner->getRedeclContext();
5081       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5082           (OwnerScope->isTranslationUnit() ||
5083            (OwnerScope->isNamespace() &&
5084             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5085         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5086           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5087 
5088         // Recover by adding 'static'.
5089         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5090                                PrevSpec, DiagID, Policy);
5091       }
5092       // C++ [class.union]p6:
5093       //   A storage class is not allowed in a declaration of an
5094       //   anonymous union in a class scope.
5095       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5096                isa<RecordDecl>(Owner)) {
5097         Diag(DS.getStorageClassSpecLoc(),
5098              diag::err_anonymous_union_with_storage_spec)
5099           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5100 
5101         // Recover by removing the storage specifier.
5102         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5103                                SourceLocation(),
5104                                PrevSpec, DiagID, Context.getPrintingPolicy());
5105       }
5106     }
5107 
5108     // Ignore const/volatile/restrict qualifiers.
5109     if (DS.getTypeQualifiers()) {
5110       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5111         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5112           << Record->isUnion() << "const"
5113           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5114       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5115         Diag(DS.getVolatileSpecLoc(),
5116              diag::ext_anonymous_struct_union_qualified)
5117           << Record->isUnion() << "volatile"
5118           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5119       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5120         Diag(DS.getRestrictSpecLoc(),
5121              diag::ext_anonymous_struct_union_qualified)
5122           << Record->isUnion() << "restrict"
5123           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5124       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5125         Diag(DS.getAtomicSpecLoc(),
5126              diag::ext_anonymous_struct_union_qualified)
5127           << Record->isUnion() << "_Atomic"
5128           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5129       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5130         Diag(DS.getUnalignedSpecLoc(),
5131              diag::ext_anonymous_struct_union_qualified)
5132           << Record->isUnion() << "__unaligned"
5133           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5134 
5135       DS.ClearTypeQualifiers();
5136     }
5137 
5138     // C++ [class.union]p2:
5139     //   The member-specification of an anonymous union shall only
5140     //   define non-static data members. [Note: nested types and
5141     //   functions cannot be declared within an anonymous union. ]
5142     for (auto *Mem : Record->decls()) {
5143       // Ignore invalid declarations; we already diagnosed them.
5144       if (Mem->isInvalidDecl())
5145         continue;
5146 
5147       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5148         // C++ [class.union]p3:
5149         //   An anonymous union shall not have private or protected
5150         //   members (clause 11).
5151         assert(FD->getAccess() != AS_none);
5152         if (FD->getAccess() != AS_public) {
5153           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5154             << Record->isUnion() << (FD->getAccess() == AS_protected);
5155           Invalid = true;
5156         }
5157 
5158         // C++ [class.union]p1
5159         //   An object of a class with a non-trivial constructor, a non-trivial
5160         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5161         //   assignment operator cannot be a member of a union, nor can an
5162         //   array of such objects.
5163         if (CheckNontrivialField(FD))
5164           Invalid = true;
5165       } else if (Mem->isImplicit()) {
5166         // Any implicit members are fine.
5167       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5168         // This is a type that showed up in an
5169         // elaborated-type-specifier inside the anonymous struct or
5170         // union, but which actually declares a type outside of the
5171         // anonymous struct or union. It's okay.
5172       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5173         if (!MemRecord->isAnonymousStructOrUnion() &&
5174             MemRecord->getDeclName()) {
5175           // Visual C++ allows type definition in anonymous struct or union.
5176           if (getLangOpts().MicrosoftExt)
5177             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5178               << Record->isUnion();
5179           else {
5180             // This is a nested type declaration.
5181             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5182               << Record->isUnion();
5183             Invalid = true;
5184           }
5185         } else {
5186           // This is an anonymous type definition within another anonymous type.
5187           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5188           // not part of standard C++.
5189           Diag(MemRecord->getLocation(),
5190                diag::ext_anonymous_record_with_anonymous_type)
5191             << Record->isUnion();
5192         }
5193       } else if (isa<AccessSpecDecl>(Mem)) {
5194         // Any access specifier is fine.
5195       } else if (isa<StaticAssertDecl>(Mem)) {
5196         // In C++1z, static_assert declarations are also fine.
5197       } else {
5198         // We have something that isn't a non-static data
5199         // member. Complain about it.
5200         unsigned DK = diag::err_anonymous_record_bad_member;
5201         if (isa<TypeDecl>(Mem))
5202           DK = diag::err_anonymous_record_with_type;
5203         else if (isa<FunctionDecl>(Mem))
5204           DK = diag::err_anonymous_record_with_function;
5205         else if (isa<VarDecl>(Mem))
5206           DK = diag::err_anonymous_record_with_static;
5207 
5208         // Visual C++ allows type definition in anonymous struct or union.
5209         if (getLangOpts().MicrosoftExt &&
5210             DK == diag::err_anonymous_record_with_type)
5211           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5212             << Record->isUnion();
5213         else {
5214           Diag(Mem->getLocation(), DK) << Record->isUnion();
5215           Invalid = true;
5216         }
5217       }
5218     }
5219 
5220     // C++11 [class.union]p8 (DR1460):
5221     //   At most one variant member of a union may have a
5222     //   brace-or-equal-initializer.
5223     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5224         Owner->isRecord())
5225       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5226                                 cast<CXXRecordDecl>(Record));
5227   }
5228 
5229   if (!Record->isUnion() && !Owner->isRecord()) {
5230     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5231       << getLangOpts().CPlusPlus;
5232     Invalid = true;
5233   }
5234 
5235   // C++ [dcl.dcl]p3:
5236   //   [If there are no declarators], and except for the declaration of an
5237   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5238   //   names into the program
5239   // C++ [class.mem]p2:
5240   //   each such member-declaration shall either declare at least one member
5241   //   name of the class or declare at least one unnamed bit-field
5242   //
5243   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5244   if (getLangOpts().CPlusPlus && Record->field_empty())
5245     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5246 
5247   // Mock up a declarator.
5248   Declarator Dc(DS, DeclaratorContext::Member);
5249   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5250   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5251 
5252   // Create a declaration for this anonymous struct/union.
5253   NamedDecl *Anon = nullptr;
5254   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5255     Anon = FieldDecl::Create(
5256         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5257         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5258         /*BitWidth=*/nullptr, /*Mutable=*/false,
5259         /*InitStyle=*/ICIS_NoInit);
5260     Anon->setAccess(AS);
5261     ProcessDeclAttributes(S, Anon, Dc);
5262 
5263     if (getLangOpts().CPlusPlus)
5264       FieldCollector->Add(cast<FieldDecl>(Anon));
5265   } else {
5266     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5267     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5268     if (SCSpec == DeclSpec::SCS_mutable) {
5269       // mutable can only appear on non-static class members, so it's always
5270       // an error here
5271       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5272       Invalid = true;
5273       SC = SC_None;
5274     }
5275 
5276     assert(DS.getAttributes().empty() && "No attribute expected");
5277     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5278                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5279                            Context.getTypeDeclType(Record), TInfo, SC);
5280 
5281     // Default-initialize the implicit variable. This initialization will be
5282     // trivial in almost all cases, except if a union member has an in-class
5283     // initializer:
5284     //   union { int n = 0; };
5285     if (!Invalid)
5286       ActOnUninitializedDecl(Anon);
5287   }
5288   Anon->setImplicit();
5289 
5290   // Mark this as an anonymous struct/union type.
5291   Record->setAnonymousStructOrUnion(true);
5292 
5293   // Add the anonymous struct/union object to the current
5294   // context. We'll be referencing this object when we refer to one of
5295   // its members.
5296   Owner->addDecl(Anon);
5297 
5298   // Inject the members of the anonymous struct/union into the owning
5299   // context and into the identifier resolver chain for name lookup
5300   // purposes.
5301   SmallVector<NamedDecl*, 2> Chain;
5302   Chain.push_back(Anon);
5303 
5304   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5305     Invalid = true;
5306 
5307   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5308     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5309       MangleNumberingContext *MCtx;
5310       Decl *ManglingContextDecl;
5311       std::tie(MCtx, ManglingContextDecl) =
5312           getCurrentMangleNumberContext(NewVD->getDeclContext());
5313       if (MCtx) {
5314         Context.setManglingNumber(
5315             NewVD, MCtx->getManglingNumber(
5316                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5317         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5318       }
5319     }
5320   }
5321 
5322   if (Invalid)
5323     Anon->setInvalidDecl();
5324 
5325   return Anon;
5326 }
5327 
5328 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5329 /// Microsoft C anonymous structure.
5330 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5331 /// Example:
5332 ///
5333 /// struct A { int a; };
5334 /// struct B { struct A; int b; };
5335 ///
5336 /// void foo() {
5337 ///   B var;
5338 ///   var.a = 3;
5339 /// }
5340 ///
5341 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5342                                            RecordDecl *Record) {
5343   assert(Record && "expected a record!");
5344 
5345   // Mock up a declarator.
5346   Declarator Dc(DS, DeclaratorContext::TypeName);
5347   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5348   assert(TInfo && "couldn't build declarator info for anonymous struct");
5349 
5350   auto *ParentDecl = cast<RecordDecl>(CurContext);
5351   QualType RecTy = Context.getTypeDeclType(Record);
5352 
5353   // Create a declaration for this anonymous struct.
5354   NamedDecl *Anon =
5355       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5356                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5357                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5358                         /*InitStyle=*/ICIS_NoInit);
5359   Anon->setImplicit();
5360 
5361   // Add the anonymous struct object to the current context.
5362   CurContext->addDecl(Anon);
5363 
5364   // Inject the members of the anonymous struct into the current
5365   // context and into the identifier resolver chain for name lookup
5366   // purposes.
5367   SmallVector<NamedDecl*, 2> Chain;
5368   Chain.push_back(Anon);
5369 
5370   RecordDecl *RecordDef = Record->getDefinition();
5371   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5372                                diag::err_field_incomplete_or_sizeless) ||
5373       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5374                                           AS_none, Chain)) {
5375     Anon->setInvalidDecl();
5376     ParentDecl->setInvalidDecl();
5377   }
5378 
5379   return Anon;
5380 }
5381 
5382 /// GetNameForDeclarator - Determine the full declaration name for the
5383 /// given Declarator.
5384 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5385   return GetNameFromUnqualifiedId(D.getName());
5386 }
5387 
5388 /// Retrieves the declaration name from a parsed unqualified-id.
5389 DeclarationNameInfo
5390 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5391   DeclarationNameInfo NameInfo;
5392   NameInfo.setLoc(Name.StartLocation);
5393 
5394   switch (Name.getKind()) {
5395 
5396   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5397   case UnqualifiedIdKind::IK_Identifier:
5398     NameInfo.setName(Name.Identifier);
5399     return NameInfo;
5400 
5401   case UnqualifiedIdKind::IK_DeductionGuideName: {
5402     // C++ [temp.deduct.guide]p3:
5403     //   The simple-template-id shall name a class template specialization.
5404     //   The template-name shall be the same identifier as the template-name
5405     //   of the simple-template-id.
5406     // These together intend to imply that the template-name shall name a
5407     // class template.
5408     // FIXME: template<typename T> struct X {};
5409     //        template<typename T> using Y = X<T>;
5410     //        Y(int) -> Y<int>;
5411     //   satisfies these rules but does not name a class template.
5412     TemplateName TN = Name.TemplateName.get().get();
5413     auto *Template = TN.getAsTemplateDecl();
5414     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5415       Diag(Name.StartLocation,
5416            diag::err_deduction_guide_name_not_class_template)
5417         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5418       if (Template)
5419         Diag(Template->getLocation(), diag::note_template_decl_here);
5420       return DeclarationNameInfo();
5421     }
5422 
5423     NameInfo.setName(
5424         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5425     return NameInfo;
5426   }
5427 
5428   case UnqualifiedIdKind::IK_OperatorFunctionId:
5429     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5430                                            Name.OperatorFunctionId.Operator));
5431     NameInfo.setCXXOperatorNameRange(SourceRange(
5432         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5433     return NameInfo;
5434 
5435   case UnqualifiedIdKind::IK_LiteralOperatorId:
5436     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5437                                                            Name.Identifier));
5438     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5439     return NameInfo;
5440 
5441   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5442     TypeSourceInfo *TInfo;
5443     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5444     if (Ty.isNull())
5445       return DeclarationNameInfo();
5446     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5447                                                Context.getCanonicalType(Ty)));
5448     NameInfo.setNamedTypeInfo(TInfo);
5449     return NameInfo;
5450   }
5451 
5452   case UnqualifiedIdKind::IK_ConstructorName: {
5453     TypeSourceInfo *TInfo;
5454     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5455     if (Ty.isNull())
5456       return DeclarationNameInfo();
5457     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5458                                               Context.getCanonicalType(Ty)));
5459     NameInfo.setNamedTypeInfo(TInfo);
5460     return NameInfo;
5461   }
5462 
5463   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5464     // In well-formed code, we can only have a constructor
5465     // template-id that refers to the current context, so go there
5466     // to find the actual type being constructed.
5467     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5468     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5469       return DeclarationNameInfo();
5470 
5471     // Determine the type of the class being constructed.
5472     QualType CurClassType = Context.getTypeDeclType(CurClass);
5473 
5474     // FIXME: Check two things: that the template-id names the same type as
5475     // CurClassType, and that the template-id does not occur when the name
5476     // was qualified.
5477 
5478     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5479                                     Context.getCanonicalType(CurClassType)));
5480     // FIXME: should we retrieve TypeSourceInfo?
5481     NameInfo.setNamedTypeInfo(nullptr);
5482     return NameInfo;
5483   }
5484 
5485   case UnqualifiedIdKind::IK_DestructorName: {
5486     TypeSourceInfo *TInfo;
5487     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5488     if (Ty.isNull())
5489       return DeclarationNameInfo();
5490     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5491                                               Context.getCanonicalType(Ty)));
5492     NameInfo.setNamedTypeInfo(TInfo);
5493     return NameInfo;
5494   }
5495 
5496   case UnqualifiedIdKind::IK_TemplateId: {
5497     TemplateName TName = Name.TemplateId->Template.get();
5498     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5499     return Context.getNameForTemplate(TName, TNameLoc);
5500   }
5501 
5502   } // switch (Name.getKind())
5503 
5504   llvm_unreachable("Unknown name kind");
5505 }
5506 
5507 static QualType getCoreType(QualType Ty) {
5508   do {
5509     if (Ty->isPointerType() || Ty->isReferenceType())
5510       Ty = Ty->getPointeeType();
5511     else if (Ty->isArrayType())
5512       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5513     else
5514       return Ty.withoutLocalFastQualifiers();
5515   } while (true);
5516 }
5517 
5518 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5519 /// and Definition have "nearly" matching parameters. This heuristic is
5520 /// used to improve diagnostics in the case where an out-of-line function
5521 /// definition doesn't match any declaration within the class or namespace.
5522 /// Also sets Params to the list of indices to the parameters that differ
5523 /// between the declaration and the definition. If hasSimilarParameters
5524 /// returns true and Params is empty, then all of the parameters match.
5525 static bool hasSimilarParameters(ASTContext &Context,
5526                                      FunctionDecl *Declaration,
5527                                      FunctionDecl *Definition,
5528                                      SmallVectorImpl<unsigned> &Params) {
5529   Params.clear();
5530   if (Declaration->param_size() != Definition->param_size())
5531     return false;
5532   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5533     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5534     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5535 
5536     // The parameter types are identical
5537     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5538       continue;
5539 
5540     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5541     QualType DefParamBaseTy = getCoreType(DefParamTy);
5542     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5543     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5544 
5545     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5546         (DeclTyName && DeclTyName == DefTyName))
5547       Params.push_back(Idx);
5548     else  // The two parameters aren't even close
5549       return false;
5550   }
5551 
5552   return true;
5553 }
5554 
5555 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5556 /// declarator needs to be rebuilt in the current instantiation.
5557 /// Any bits of declarator which appear before the name are valid for
5558 /// consideration here.  That's specifically the type in the decl spec
5559 /// and the base type in any member-pointer chunks.
5560 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5561                                                     DeclarationName Name) {
5562   // The types we specifically need to rebuild are:
5563   //   - typenames, typeofs, and decltypes
5564   //   - types which will become injected class names
5565   // Of course, we also need to rebuild any type referencing such a
5566   // type.  It's safest to just say "dependent", but we call out a
5567   // few cases here.
5568 
5569   DeclSpec &DS = D.getMutableDeclSpec();
5570   switch (DS.getTypeSpecType()) {
5571   case DeclSpec::TST_typename:
5572   case DeclSpec::TST_typeofType:
5573   case DeclSpec::TST_underlyingType:
5574   case DeclSpec::TST_atomic: {
5575     // Grab the type from the parser.
5576     TypeSourceInfo *TSI = nullptr;
5577     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5578     if (T.isNull() || !T->isInstantiationDependentType()) break;
5579 
5580     // Make sure there's a type source info.  This isn't really much
5581     // of a waste; most dependent types should have type source info
5582     // attached already.
5583     if (!TSI)
5584       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5585 
5586     // Rebuild the type in the current instantiation.
5587     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5588     if (!TSI) return true;
5589 
5590     // Store the new type back in the decl spec.
5591     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5592     DS.UpdateTypeRep(LocType);
5593     break;
5594   }
5595 
5596   case DeclSpec::TST_decltype:
5597   case DeclSpec::TST_typeofExpr: {
5598     Expr *E = DS.getRepAsExpr();
5599     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5600     if (Result.isInvalid()) return true;
5601     DS.UpdateExprRep(Result.get());
5602     break;
5603   }
5604 
5605   default:
5606     // Nothing to do for these decl specs.
5607     break;
5608   }
5609 
5610   // It doesn't matter what order we do this in.
5611   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5612     DeclaratorChunk &Chunk = D.getTypeObject(I);
5613 
5614     // The only type information in the declarator which can come
5615     // before the declaration name is the base type of a member
5616     // pointer.
5617     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5618       continue;
5619 
5620     // Rebuild the scope specifier in-place.
5621     CXXScopeSpec &SS = Chunk.Mem.Scope();
5622     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5623       return true;
5624   }
5625 
5626   return false;
5627 }
5628 
5629 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5630   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5631   // of system decl.
5632   if (D->getPreviousDecl() || D->isImplicit())
5633     return;
5634   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5635   if (Status != ReservedIdentifierStatus::NotReserved &&
5636       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5637     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5638         << D << static_cast<int>(Status);
5639 }
5640 
5641 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5642   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5643   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5644 
5645   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5646       Dcl && Dcl->getDeclContext()->isFileContext())
5647     Dcl->setTopLevelDeclInObjCContainer();
5648 
5649   return Dcl;
5650 }
5651 
5652 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5653 ///   If T is the name of a class, then each of the following shall have a
5654 ///   name different from T:
5655 ///     - every static data member of class T;
5656 ///     - every member function of class T
5657 ///     - every member of class T that is itself a type;
5658 /// \returns true if the declaration name violates these rules.
5659 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5660                                    DeclarationNameInfo NameInfo) {
5661   DeclarationName Name = NameInfo.getName();
5662 
5663   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5664   while (Record && Record->isAnonymousStructOrUnion())
5665     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5666   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5667     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5668     return true;
5669   }
5670 
5671   return false;
5672 }
5673 
5674 /// Diagnose a declaration whose declarator-id has the given
5675 /// nested-name-specifier.
5676 ///
5677 /// \param SS The nested-name-specifier of the declarator-id.
5678 ///
5679 /// \param DC The declaration context to which the nested-name-specifier
5680 /// resolves.
5681 ///
5682 /// \param Name The name of the entity being declared.
5683 ///
5684 /// \param Loc The location of the name of the entity being declared.
5685 ///
5686 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5687 /// we're declaring an explicit / partial specialization / instantiation.
5688 ///
5689 /// \returns true if we cannot safely recover from this error, false otherwise.
5690 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5691                                         DeclarationName Name,
5692                                         SourceLocation Loc, bool IsTemplateId) {
5693   DeclContext *Cur = CurContext;
5694   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5695     Cur = Cur->getParent();
5696 
5697   // If the user provided a superfluous scope specifier that refers back to the
5698   // class in which the entity is already declared, diagnose and ignore it.
5699   //
5700   // class X {
5701   //   void X::f();
5702   // };
5703   //
5704   // Note, it was once ill-formed to give redundant qualification in all
5705   // contexts, but that rule was removed by DR482.
5706   if (Cur->Equals(DC)) {
5707     if (Cur->isRecord()) {
5708       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5709                                       : diag::err_member_extra_qualification)
5710         << Name << FixItHint::CreateRemoval(SS.getRange());
5711       SS.clear();
5712     } else {
5713       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5714     }
5715     return false;
5716   }
5717 
5718   // Check whether the qualifying scope encloses the scope of the original
5719   // declaration. For a template-id, we perform the checks in
5720   // CheckTemplateSpecializationScope.
5721   if (!Cur->Encloses(DC) && !IsTemplateId) {
5722     if (Cur->isRecord())
5723       Diag(Loc, diag::err_member_qualification)
5724         << Name << SS.getRange();
5725     else if (isa<TranslationUnitDecl>(DC))
5726       Diag(Loc, diag::err_invalid_declarator_global_scope)
5727         << Name << SS.getRange();
5728     else if (isa<FunctionDecl>(Cur))
5729       Diag(Loc, diag::err_invalid_declarator_in_function)
5730         << Name << SS.getRange();
5731     else if (isa<BlockDecl>(Cur))
5732       Diag(Loc, diag::err_invalid_declarator_in_block)
5733         << Name << SS.getRange();
5734     else
5735       Diag(Loc, diag::err_invalid_declarator_scope)
5736       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5737 
5738     return true;
5739   }
5740 
5741   if (Cur->isRecord()) {
5742     // Cannot qualify members within a class.
5743     Diag(Loc, diag::err_member_qualification)
5744       << Name << SS.getRange();
5745     SS.clear();
5746 
5747     // C++ constructors and destructors with incorrect scopes can break
5748     // our AST invariants by having the wrong underlying types. If
5749     // that's the case, then drop this declaration entirely.
5750     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5751          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5752         !Context.hasSameType(Name.getCXXNameType(),
5753                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5754       return true;
5755 
5756     return false;
5757   }
5758 
5759   // C++11 [dcl.meaning]p1:
5760   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5761   //   not begin with a decltype-specifer"
5762   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5763   while (SpecLoc.getPrefix())
5764     SpecLoc = SpecLoc.getPrefix();
5765   if (dyn_cast_or_null<DecltypeType>(
5766         SpecLoc.getNestedNameSpecifier()->getAsType()))
5767     Diag(Loc, diag::err_decltype_in_declarator)
5768       << SpecLoc.getTypeLoc().getSourceRange();
5769 
5770   return false;
5771 }
5772 
5773 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5774                                   MultiTemplateParamsArg TemplateParamLists) {
5775   // TODO: consider using NameInfo for diagnostic.
5776   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5777   DeclarationName Name = NameInfo.getName();
5778 
5779   // All of these full declarators require an identifier.  If it doesn't have
5780   // one, the ParsedFreeStandingDeclSpec action should be used.
5781   if (D.isDecompositionDeclarator()) {
5782     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5783   } else if (!Name) {
5784     if (!D.isInvalidType())  // Reject this if we think it is valid.
5785       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5786           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5787     return nullptr;
5788   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5789     return nullptr;
5790 
5791   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5792   // we find one that is.
5793   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5794          (S->getFlags() & Scope::TemplateParamScope) != 0)
5795     S = S->getParent();
5796 
5797   DeclContext *DC = CurContext;
5798   if (D.getCXXScopeSpec().isInvalid())
5799     D.setInvalidType();
5800   else if (D.getCXXScopeSpec().isSet()) {
5801     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5802                                         UPPC_DeclarationQualifier))
5803       return nullptr;
5804 
5805     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5806     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5807     if (!DC || isa<EnumDecl>(DC)) {
5808       // If we could not compute the declaration context, it's because the
5809       // declaration context is dependent but does not refer to a class,
5810       // class template, or class template partial specialization. Complain
5811       // and return early, to avoid the coming semantic disaster.
5812       Diag(D.getIdentifierLoc(),
5813            diag::err_template_qualified_declarator_no_match)
5814         << D.getCXXScopeSpec().getScopeRep()
5815         << D.getCXXScopeSpec().getRange();
5816       return nullptr;
5817     }
5818     bool IsDependentContext = DC->isDependentContext();
5819 
5820     if (!IsDependentContext &&
5821         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5822       return nullptr;
5823 
5824     // If a class is incomplete, do not parse entities inside it.
5825     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5826       Diag(D.getIdentifierLoc(),
5827            diag::err_member_def_undefined_record)
5828         << Name << DC << D.getCXXScopeSpec().getRange();
5829       return nullptr;
5830     }
5831     if (!D.getDeclSpec().isFriendSpecified()) {
5832       if (diagnoseQualifiedDeclaration(
5833               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5834               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5835         if (DC->isRecord())
5836           return nullptr;
5837 
5838         D.setInvalidType();
5839       }
5840     }
5841 
5842     // Check whether we need to rebuild the type of the given
5843     // declaration in the current instantiation.
5844     if (EnteringContext && IsDependentContext &&
5845         TemplateParamLists.size() != 0) {
5846       ContextRAII SavedContext(*this, DC);
5847       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5848         D.setInvalidType();
5849     }
5850   }
5851 
5852   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5853   QualType R = TInfo->getType();
5854 
5855   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5856                                       UPPC_DeclarationType))
5857     D.setInvalidType();
5858 
5859   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5860                         forRedeclarationInCurContext());
5861 
5862   // See if this is a redefinition of a variable in the same scope.
5863   if (!D.getCXXScopeSpec().isSet()) {
5864     bool IsLinkageLookup = false;
5865     bool CreateBuiltins = false;
5866 
5867     // If the declaration we're planning to build will be a function
5868     // or object with linkage, then look for another declaration with
5869     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5870     //
5871     // If the declaration we're planning to build will be declared with
5872     // external linkage in the translation unit, create any builtin with
5873     // the same name.
5874     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5875       /* Do nothing*/;
5876     else if (CurContext->isFunctionOrMethod() &&
5877              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5878               R->isFunctionType())) {
5879       IsLinkageLookup = true;
5880       CreateBuiltins =
5881           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5882     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5883                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5884       CreateBuiltins = true;
5885 
5886     if (IsLinkageLookup) {
5887       Previous.clear(LookupRedeclarationWithLinkage);
5888       Previous.setRedeclarationKind(ForExternalRedeclaration);
5889     }
5890 
5891     LookupName(Previous, S, CreateBuiltins);
5892   } else { // Something like "int foo::x;"
5893     LookupQualifiedName(Previous, DC);
5894 
5895     // C++ [dcl.meaning]p1:
5896     //   When the declarator-id is qualified, the declaration shall refer to a
5897     //  previously declared member of the class or namespace to which the
5898     //  qualifier refers (or, in the case of a namespace, of an element of the
5899     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5900     //  thereof; [...]
5901     //
5902     // Note that we already checked the context above, and that we do not have
5903     // enough information to make sure that Previous contains the declaration
5904     // we want to match. For example, given:
5905     //
5906     //   class X {
5907     //     void f();
5908     //     void f(float);
5909     //   };
5910     //
5911     //   void X::f(int) { } // ill-formed
5912     //
5913     // In this case, Previous will point to the overload set
5914     // containing the two f's declared in X, but neither of them
5915     // matches.
5916 
5917     // C++ [dcl.meaning]p1:
5918     //   [...] the member shall not merely have been introduced by a
5919     //   using-declaration in the scope of the class or namespace nominated by
5920     //   the nested-name-specifier of the declarator-id.
5921     RemoveUsingDecls(Previous);
5922   }
5923 
5924   if (Previous.isSingleResult() &&
5925       Previous.getFoundDecl()->isTemplateParameter()) {
5926     // Maybe we will complain about the shadowed template parameter.
5927     if (!D.isInvalidType())
5928       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5929                                       Previous.getFoundDecl());
5930 
5931     // Just pretend that we didn't see the previous declaration.
5932     Previous.clear();
5933   }
5934 
5935   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5936     // Forget that the previous declaration is the injected-class-name.
5937     Previous.clear();
5938 
5939   // In C++, the previous declaration we find might be a tag type
5940   // (class or enum). In this case, the new declaration will hide the
5941   // tag type. Note that this applies to functions, function templates, and
5942   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5943   if (Previous.isSingleTagDecl() &&
5944       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5945       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5946     Previous.clear();
5947 
5948   // Check that there are no default arguments other than in the parameters
5949   // of a function declaration (C++ only).
5950   if (getLangOpts().CPlusPlus)
5951     CheckExtraCXXDefaultArguments(D);
5952 
5953   NamedDecl *New;
5954 
5955   bool AddToScope = true;
5956   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5957     if (TemplateParamLists.size()) {
5958       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5959       return nullptr;
5960     }
5961 
5962     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5963   } else if (R->isFunctionType()) {
5964     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5965                                   TemplateParamLists,
5966                                   AddToScope);
5967   } else {
5968     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5969                                   AddToScope);
5970   }
5971 
5972   if (!New)
5973     return nullptr;
5974 
5975   // If this has an identifier and is not a function template specialization,
5976   // add it to the scope stack.
5977   if (New->getDeclName() && AddToScope)
5978     PushOnScopeChains(New, S);
5979 
5980   if (isInOpenMPDeclareTargetContext())
5981     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5982 
5983   return New;
5984 }
5985 
5986 /// Helper method to turn variable array types into constant array
5987 /// types in certain situations which would otherwise be errors (for
5988 /// GCC compatibility).
5989 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5990                                                     ASTContext &Context,
5991                                                     bool &SizeIsNegative,
5992                                                     llvm::APSInt &Oversized) {
5993   // This method tries to turn a variable array into a constant
5994   // array even when the size isn't an ICE.  This is necessary
5995   // for compatibility with code that depends on gcc's buggy
5996   // constant expression folding, like struct {char x[(int)(char*)2];}
5997   SizeIsNegative = false;
5998   Oversized = 0;
5999 
6000   if (T->isDependentType())
6001     return QualType();
6002 
6003   QualifierCollector Qs;
6004   const Type *Ty = Qs.strip(T);
6005 
6006   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6007     QualType Pointee = PTy->getPointeeType();
6008     QualType FixedType =
6009         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6010                                             Oversized);
6011     if (FixedType.isNull()) return FixedType;
6012     FixedType = Context.getPointerType(FixedType);
6013     return Qs.apply(Context, FixedType);
6014   }
6015   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6016     QualType Inner = PTy->getInnerType();
6017     QualType FixedType =
6018         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6019                                             Oversized);
6020     if (FixedType.isNull()) return FixedType;
6021     FixedType = Context.getParenType(FixedType);
6022     return Qs.apply(Context, FixedType);
6023   }
6024 
6025   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6026   if (!VLATy)
6027     return QualType();
6028 
6029   QualType ElemTy = VLATy->getElementType();
6030   if (ElemTy->isVariablyModifiedType()) {
6031     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6032                                                  SizeIsNegative, Oversized);
6033     if (ElemTy.isNull())
6034       return QualType();
6035   }
6036 
6037   Expr::EvalResult Result;
6038   if (!VLATy->getSizeExpr() ||
6039       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6040     return QualType();
6041 
6042   llvm::APSInt Res = Result.Val.getInt();
6043 
6044   // Check whether the array size is negative.
6045   if (Res.isSigned() && Res.isNegative()) {
6046     SizeIsNegative = true;
6047     return QualType();
6048   }
6049 
6050   // Check whether the array is too large to be addressed.
6051   unsigned ActiveSizeBits =
6052       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6053        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6054           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6055           : Res.getActiveBits();
6056   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6057     Oversized = Res;
6058     return QualType();
6059   }
6060 
6061   QualType FoldedArrayType = Context.getConstantArrayType(
6062       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6063   return Qs.apply(Context, FoldedArrayType);
6064 }
6065 
6066 static void
6067 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6068   SrcTL = SrcTL.getUnqualifiedLoc();
6069   DstTL = DstTL.getUnqualifiedLoc();
6070   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6071     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6072     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6073                                       DstPTL.getPointeeLoc());
6074     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6075     return;
6076   }
6077   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6078     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6079     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6080                                       DstPTL.getInnerLoc());
6081     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6082     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6083     return;
6084   }
6085   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6086   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6087   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6088   TypeLoc DstElemTL = DstATL.getElementLoc();
6089   if (VariableArrayTypeLoc SrcElemATL =
6090           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6091     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6092     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6093   } else {
6094     DstElemTL.initializeFullCopy(SrcElemTL);
6095   }
6096   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6097   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6098   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6099 }
6100 
6101 /// Helper method to turn variable array types into constant array
6102 /// types in certain situations which would otherwise be errors (for
6103 /// GCC compatibility).
6104 static TypeSourceInfo*
6105 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6106                                               ASTContext &Context,
6107                                               bool &SizeIsNegative,
6108                                               llvm::APSInt &Oversized) {
6109   QualType FixedTy
6110     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6111                                           SizeIsNegative, Oversized);
6112   if (FixedTy.isNull())
6113     return nullptr;
6114   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6115   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6116                                     FixedTInfo->getTypeLoc());
6117   return FixedTInfo;
6118 }
6119 
6120 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6121 /// true if we were successful.
6122 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6123                                            QualType &T, SourceLocation Loc,
6124                                            unsigned FailedFoldDiagID) {
6125   bool SizeIsNegative;
6126   llvm::APSInt Oversized;
6127   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6128       TInfo, Context, SizeIsNegative, Oversized);
6129   if (FixedTInfo) {
6130     Diag(Loc, diag::ext_vla_folded_to_constant);
6131     TInfo = FixedTInfo;
6132     T = FixedTInfo->getType();
6133     return true;
6134   }
6135 
6136   if (SizeIsNegative)
6137     Diag(Loc, diag::err_typecheck_negative_array_size);
6138   else if (Oversized.getBoolValue())
6139     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6140   else if (FailedFoldDiagID)
6141     Diag(Loc, FailedFoldDiagID);
6142   return false;
6143 }
6144 
6145 /// Register the given locally-scoped extern "C" declaration so
6146 /// that it can be found later for redeclarations. We include any extern "C"
6147 /// declaration that is not visible in the translation unit here, not just
6148 /// function-scope declarations.
6149 void
6150 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6151   if (!getLangOpts().CPlusPlus &&
6152       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6153     // Don't need to track declarations in the TU in C.
6154     return;
6155 
6156   // Note that we have a locally-scoped external with this name.
6157   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6158 }
6159 
6160 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6161   // FIXME: We can have multiple results via __attribute__((overloadable)).
6162   auto Result = Context.getExternCContextDecl()->lookup(Name);
6163   return Result.empty() ? nullptr : *Result.begin();
6164 }
6165 
6166 /// Diagnose function specifiers on a declaration of an identifier that
6167 /// does not identify a function.
6168 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6169   // FIXME: We should probably indicate the identifier in question to avoid
6170   // confusion for constructs like "virtual int a(), b;"
6171   if (DS.isVirtualSpecified())
6172     Diag(DS.getVirtualSpecLoc(),
6173          diag::err_virtual_non_function);
6174 
6175   if (DS.hasExplicitSpecifier())
6176     Diag(DS.getExplicitSpecLoc(),
6177          diag::err_explicit_non_function);
6178 
6179   if (DS.isNoreturnSpecified())
6180     Diag(DS.getNoreturnSpecLoc(),
6181          diag::err_noreturn_non_function);
6182 }
6183 
6184 NamedDecl*
6185 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6186                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6187   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6188   if (D.getCXXScopeSpec().isSet()) {
6189     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6190       << D.getCXXScopeSpec().getRange();
6191     D.setInvalidType();
6192     // Pretend we didn't see the scope specifier.
6193     DC = CurContext;
6194     Previous.clear();
6195   }
6196 
6197   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6198 
6199   if (D.getDeclSpec().isInlineSpecified())
6200     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6201         << getLangOpts().CPlusPlus17;
6202   if (D.getDeclSpec().hasConstexprSpecifier())
6203     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6204         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6205 
6206   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6207     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6208       Diag(D.getName().StartLocation,
6209            diag::err_deduction_guide_invalid_specifier)
6210           << "typedef";
6211     else
6212       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6213           << D.getName().getSourceRange();
6214     return nullptr;
6215   }
6216 
6217   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6218   if (!NewTD) return nullptr;
6219 
6220   // Handle attributes prior to checking for duplicates in MergeVarDecl
6221   ProcessDeclAttributes(S, NewTD, D);
6222 
6223   CheckTypedefForVariablyModifiedType(S, NewTD);
6224 
6225   bool Redeclaration = D.isRedeclaration();
6226   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6227   D.setRedeclaration(Redeclaration);
6228   return ND;
6229 }
6230 
6231 void
6232 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6233   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6234   // then it shall have block scope.
6235   // Note that variably modified types must be fixed before merging the decl so
6236   // that redeclarations will match.
6237   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6238   QualType T = TInfo->getType();
6239   if (T->isVariablyModifiedType()) {
6240     setFunctionHasBranchProtectedScope();
6241 
6242     if (S->getFnParent() == nullptr) {
6243       bool SizeIsNegative;
6244       llvm::APSInt Oversized;
6245       TypeSourceInfo *FixedTInfo =
6246         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6247                                                       SizeIsNegative,
6248                                                       Oversized);
6249       if (FixedTInfo) {
6250         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6251         NewTD->setTypeSourceInfo(FixedTInfo);
6252       } else {
6253         if (SizeIsNegative)
6254           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6255         else if (T->isVariableArrayType())
6256           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6257         else if (Oversized.getBoolValue())
6258           Diag(NewTD->getLocation(), diag::err_array_too_large)
6259             << toString(Oversized, 10);
6260         else
6261           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6262         NewTD->setInvalidDecl();
6263       }
6264     }
6265   }
6266 }
6267 
6268 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6269 /// declares a typedef-name, either using the 'typedef' type specifier or via
6270 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6271 NamedDecl*
6272 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6273                            LookupResult &Previous, bool &Redeclaration) {
6274 
6275   // Find the shadowed declaration before filtering for scope.
6276   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6277 
6278   // Merge the decl with the existing one if appropriate. If the decl is
6279   // in an outer scope, it isn't the same thing.
6280   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6281                        /*AllowInlineNamespace*/false);
6282   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6283   if (!Previous.empty()) {
6284     Redeclaration = true;
6285     MergeTypedefNameDecl(S, NewTD, Previous);
6286   } else {
6287     inferGslPointerAttribute(NewTD);
6288   }
6289 
6290   if (ShadowedDecl && !Redeclaration)
6291     CheckShadow(NewTD, ShadowedDecl, Previous);
6292 
6293   // If this is the C FILE type, notify the AST context.
6294   if (IdentifierInfo *II = NewTD->getIdentifier())
6295     if (!NewTD->isInvalidDecl() &&
6296         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6297       if (II->isStr("FILE"))
6298         Context.setFILEDecl(NewTD);
6299       else if (II->isStr("jmp_buf"))
6300         Context.setjmp_bufDecl(NewTD);
6301       else if (II->isStr("sigjmp_buf"))
6302         Context.setsigjmp_bufDecl(NewTD);
6303       else if (II->isStr("ucontext_t"))
6304         Context.setucontext_tDecl(NewTD);
6305     }
6306 
6307   return NewTD;
6308 }
6309 
6310 /// Determines whether the given declaration is an out-of-scope
6311 /// previous declaration.
6312 ///
6313 /// This routine should be invoked when name lookup has found a
6314 /// previous declaration (PrevDecl) that is not in the scope where a
6315 /// new declaration by the same name is being introduced. If the new
6316 /// declaration occurs in a local scope, previous declarations with
6317 /// linkage may still be considered previous declarations (C99
6318 /// 6.2.2p4-5, C++ [basic.link]p6).
6319 ///
6320 /// \param PrevDecl the previous declaration found by name
6321 /// lookup
6322 ///
6323 /// \param DC the context in which the new declaration is being
6324 /// declared.
6325 ///
6326 /// \returns true if PrevDecl is an out-of-scope previous declaration
6327 /// for a new delcaration with the same name.
6328 static bool
6329 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6330                                 ASTContext &Context) {
6331   if (!PrevDecl)
6332     return false;
6333 
6334   if (!PrevDecl->hasLinkage())
6335     return false;
6336 
6337   if (Context.getLangOpts().CPlusPlus) {
6338     // C++ [basic.link]p6:
6339     //   If there is a visible declaration of an entity with linkage
6340     //   having the same name and type, ignoring entities declared
6341     //   outside the innermost enclosing namespace scope, the block
6342     //   scope declaration declares that same entity and receives the
6343     //   linkage of the previous declaration.
6344     DeclContext *OuterContext = DC->getRedeclContext();
6345     if (!OuterContext->isFunctionOrMethod())
6346       // This rule only applies to block-scope declarations.
6347       return false;
6348 
6349     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6350     if (PrevOuterContext->isRecord())
6351       // We found a member function: ignore it.
6352       return false;
6353 
6354     // Find the innermost enclosing namespace for the new and
6355     // previous declarations.
6356     OuterContext = OuterContext->getEnclosingNamespaceContext();
6357     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6358 
6359     // The previous declaration is in a different namespace, so it
6360     // isn't the same function.
6361     if (!OuterContext->Equals(PrevOuterContext))
6362       return false;
6363   }
6364 
6365   return true;
6366 }
6367 
6368 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6369   CXXScopeSpec &SS = D.getCXXScopeSpec();
6370   if (!SS.isSet()) return;
6371   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6372 }
6373 
6374 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6375   QualType type = decl->getType();
6376   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6377   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6378     // Various kinds of declaration aren't allowed to be __autoreleasing.
6379     unsigned kind = -1U;
6380     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6381       if (var->hasAttr<BlocksAttr>())
6382         kind = 0; // __block
6383       else if (!var->hasLocalStorage())
6384         kind = 1; // global
6385     } else if (isa<ObjCIvarDecl>(decl)) {
6386       kind = 3; // ivar
6387     } else if (isa<FieldDecl>(decl)) {
6388       kind = 2; // field
6389     }
6390 
6391     if (kind != -1U) {
6392       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6393         << kind;
6394     }
6395   } else if (lifetime == Qualifiers::OCL_None) {
6396     // Try to infer lifetime.
6397     if (!type->isObjCLifetimeType())
6398       return false;
6399 
6400     lifetime = type->getObjCARCImplicitLifetime();
6401     type = Context.getLifetimeQualifiedType(type, lifetime);
6402     decl->setType(type);
6403   }
6404 
6405   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6406     // Thread-local variables cannot have lifetime.
6407     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6408         var->getTLSKind()) {
6409       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6410         << var->getType();
6411       return true;
6412     }
6413   }
6414 
6415   return false;
6416 }
6417 
6418 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6419   if (Decl->getType().hasAddressSpace())
6420     return;
6421   if (Decl->getType()->isDependentType())
6422     return;
6423   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6424     QualType Type = Var->getType();
6425     if (Type->isSamplerT() || Type->isVoidType())
6426       return;
6427     LangAS ImplAS = LangAS::opencl_private;
6428     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6429     // __opencl_c_program_scope_global_variables feature, the address space
6430     // for a variable at program scope or a static or extern variable inside
6431     // a function are inferred to be __global.
6432     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6433         Var->hasGlobalStorage())
6434       ImplAS = LangAS::opencl_global;
6435     // If the original type from a decayed type is an array type and that array
6436     // type has no address space yet, deduce it now.
6437     if (auto DT = dyn_cast<DecayedType>(Type)) {
6438       auto OrigTy = DT->getOriginalType();
6439       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6440         // Add the address space to the original array type and then propagate
6441         // that to the element type through `getAsArrayType`.
6442         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6443         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6444         // Re-generate the decayed type.
6445         Type = Context.getDecayedType(OrigTy);
6446       }
6447     }
6448     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6449     // Apply any qualifiers (including address space) from the array type to
6450     // the element type. This implements C99 6.7.3p8: "If the specification of
6451     // an array type includes any type qualifiers, the element type is so
6452     // qualified, not the array type."
6453     if (Type->isArrayType())
6454       Type = QualType(Context.getAsArrayType(Type), 0);
6455     Decl->setType(Type);
6456   }
6457 }
6458 
6459 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6460   // Ensure that an auto decl is deduced otherwise the checks below might cache
6461   // the wrong linkage.
6462   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6463 
6464   // 'weak' only applies to declarations with external linkage.
6465   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6466     if (!ND.isExternallyVisible()) {
6467       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6468       ND.dropAttr<WeakAttr>();
6469     }
6470   }
6471   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6472     if (ND.isExternallyVisible()) {
6473       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6474       ND.dropAttr<WeakRefAttr>();
6475       ND.dropAttr<AliasAttr>();
6476     }
6477   }
6478 
6479   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6480     if (VD->hasInit()) {
6481       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6482         assert(VD->isThisDeclarationADefinition() &&
6483                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6484         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6485         VD->dropAttr<AliasAttr>();
6486       }
6487     }
6488   }
6489 
6490   // 'selectany' only applies to externally visible variable declarations.
6491   // It does not apply to functions.
6492   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6493     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6494       S.Diag(Attr->getLocation(),
6495              diag::err_attribute_selectany_non_extern_data);
6496       ND.dropAttr<SelectAnyAttr>();
6497     }
6498   }
6499 
6500   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6501     auto *VD = dyn_cast<VarDecl>(&ND);
6502     bool IsAnonymousNS = false;
6503     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6504     if (VD) {
6505       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6506       while (NS && !IsAnonymousNS) {
6507         IsAnonymousNS = NS->isAnonymousNamespace();
6508         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6509       }
6510     }
6511     // dll attributes require external linkage. Static locals may have external
6512     // linkage but still cannot be explicitly imported or exported.
6513     // In Microsoft mode, a variable defined in anonymous namespace must have
6514     // external linkage in order to be exported.
6515     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6516     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6517         (!AnonNSInMicrosoftMode &&
6518          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6519       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6520         << &ND << Attr;
6521       ND.setInvalidDecl();
6522     }
6523   }
6524 
6525   // Check the attributes on the function type, if any.
6526   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6527     // Don't declare this variable in the second operand of the for-statement;
6528     // GCC miscompiles that by ending its lifetime before evaluating the
6529     // third operand. See gcc.gnu.org/PR86769.
6530     AttributedTypeLoc ATL;
6531     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6532          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6533          TL = ATL.getModifiedLoc()) {
6534       // The [[lifetimebound]] attribute can be applied to the implicit object
6535       // parameter of a non-static member function (other than a ctor or dtor)
6536       // by applying it to the function type.
6537       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6538         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6539         if (!MD || MD->isStatic()) {
6540           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6541               << !MD << A->getRange();
6542         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6543           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6544               << isa<CXXDestructorDecl>(MD) << A->getRange();
6545         }
6546       }
6547     }
6548   }
6549 }
6550 
6551 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6552                                            NamedDecl *NewDecl,
6553                                            bool IsSpecialization,
6554                                            bool IsDefinition) {
6555   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6556     return;
6557 
6558   bool IsTemplate = false;
6559   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6560     OldDecl = OldTD->getTemplatedDecl();
6561     IsTemplate = true;
6562     if (!IsSpecialization)
6563       IsDefinition = false;
6564   }
6565   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6566     NewDecl = NewTD->getTemplatedDecl();
6567     IsTemplate = true;
6568   }
6569 
6570   if (!OldDecl || !NewDecl)
6571     return;
6572 
6573   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6574   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6575   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6576   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6577 
6578   // dllimport and dllexport are inheritable attributes so we have to exclude
6579   // inherited attribute instances.
6580   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6581                     (NewExportAttr && !NewExportAttr->isInherited());
6582 
6583   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6584   // the only exception being explicit specializations.
6585   // Implicitly generated declarations are also excluded for now because there
6586   // is no other way to switch these to use dllimport or dllexport.
6587   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6588 
6589   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6590     // Allow with a warning for free functions and global variables.
6591     bool JustWarn = false;
6592     if (!OldDecl->isCXXClassMember()) {
6593       auto *VD = dyn_cast<VarDecl>(OldDecl);
6594       if (VD && !VD->getDescribedVarTemplate())
6595         JustWarn = true;
6596       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6597       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6598         JustWarn = true;
6599     }
6600 
6601     // We cannot change a declaration that's been used because IR has already
6602     // been emitted. Dllimported functions will still work though (modulo
6603     // address equality) as they can use the thunk.
6604     if (OldDecl->isUsed())
6605       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6606         JustWarn = false;
6607 
6608     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6609                                : diag::err_attribute_dll_redeclaration;
6610     S.Diag(NewDecl->getLocation(), DiagID)
6611         << NewDecl
6612         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6613     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6614     if (!JustWarn) {
6615       NewDecl->setInvalidDecl();
6616       return;
6617     }
6618   }
6619 
6620   // A redeclaration is not allowed to drop a dllimport attribute, the only
6621   // exceptions being inline function definitions (except for function
6622   // templates), local extern declarations, qualified friend declarations or
6623   // special MSVC extension: in the last case, the declaration is treated as if
6624   // it were marked dllexport.
6625   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6626   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6627   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6628     // Ignore static data because out-of-line definitions are diagnosed
6629     // separately.
6630     IsStaticDataMember = VD->isStaticDataMember();
6631     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6632                    VarDecl::DeclarationOnly;
6633   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6634     IsInline = FD->isInlined();
6635     IsQualifiedFriend = FD->getQualifier() &&
6636                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6637   }
6638 
6639   if (OldImportAttr && !HasNewAttr &&
6640       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6641       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6642     if (IsMicrosoftABI && IsDefinition) {
6643       S.Diag(NewDecl->getLocation(),
6644              diag::warn_redeclaration_without_import_attribute)
6645           << NewDecl;
6646       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6647       NewDecl->dropAttr<DLLImportAttr>();
6648       NewDecl->addAttr(
6649           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6650     } else {
6651       S.Diag(NewDecl->getLocation(),
6652              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6653           << NewDecl << OldImportAttr;
6654       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6655       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6656       OldDecl->dropAttr<DLLImportAttr>();
6657       NewDecl->dropAttr<DLLImportAttr>();
6658     }
6659   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6660     // In MinGW, seeing a function declared inline drops the dllimport
6661     // attribute.
6662     OldDecl->dropAttr<DLLImportAttr>();
6663     NewDecl->dropAttr<DLLImportAttr>();
6664     S.Diag(NewDecl->getLocation(),
6665            diag::warn_dllimport_dropped_from_inline_function)
6666         << NewDecl << OldImportAttr;
6667   }
6668 
6669   // A specialization of a class template member function is processed here
6670   // since it's a redeclaration. If the parent class is dllexport, the
6671   // specialization inherits that attribute. This doesn't happen automatically
6672   // since the parent class isn't instantiated until later.
6673   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6674     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6675         !NewImportAttr && !NewExportAttr) {
6676       if (const DLLExportAttr *ParentExportAttr =
6677               MD->getParent()->getAttr<DLLExportAttr>()) {
6678         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6679         NewAttr->setInherited(true);
6680         NewDecl->addAttr(NewAttr);
6681       }
6682     }
6683   }
6684 }
6685 
6686 /// Given that we are within the definition of the given function,
6687 /// will that definition behave like C99's 'inline', where the
6688 /// definition is discarded except for optimization purposes?
6689 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6690   // Try to avoid calling GetGVALinkageForFunction.
6691 
6692   // All cases of this require the 'inline' keyword.
6693   if (!FD->isInlined()) return false;
6694 
6695   // This is only possible in C++ with the gnu_inline attribute.
6696   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6697     return false;
6698 
6699   // Okay, go ahead and call the relatively-more-expensive function.
6700   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6701 }
6702 
6703 /// Determine whether a variable is extern "C" prior to attaching
6704 /// an initializer. We can't just call isExternC() here, because that
6705 /// will also compute and cache whether the declaration is externally
6706 /// visible, which might change when we attach the initializer.
6707 ///
6708 /// This can only be used if the declaration is known to not be a
6709 /// redeclaration of an internal linkage declaration.
6710 ///
6711 /// For instance:
6712 ///
6713 ///   auto x = []{};
6714 ///
6715 /// Attaching the initializer here makes this declaration not externally
6716 /// visible, because its type has internal linkage.
6717 ///
6718 /// FIXME: This is a hack.
6719 template<typename T>
6720 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6721   if (S.getLangOpts().CPlusPlus) {
6722     // In C++, the overloadable attribute negates the effects of extern "C".
6723     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6724       return false;
6725 
6726     // So do CUDA's host/device attributes.
6727     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6728                                  D->template hasAttr<CUDAHostAttr>()))
6729       return false;
6730   }
6731   return D->isExternC();
6732 }
6733 
6734 static bool shouldConsiderLinkage(const VarDecl *VD) {
6735   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6736   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6737       isa<OMPDeclareMapperDecl>(DC))
6738     return VD->hasExternalStorage();
6739   if (DC->isFileContext())
6740     return true;
6741   if (DC->isRecord())
6742     return false;
6743   if (isa<RequiresExprBodyDecl>(DC))
6744     return false;
6745   llvm_unreachable("Unexpected context");
6746 }
6747 
6748 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6749   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6750   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6751       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6752     return true;
6753   if (DC->isRecord())
6754     return false;
6755   llvm_unreachable("Unexpected context");
6756 }
6757 
6758 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6759                           ParsedAttr::Kind Kind) {
6760   // Check decl attributes on the DeclSpec.
6761   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6762     return true;
6763 
6764   // Walk the declarator structure, checking decl attributes that were in a type
6765   // position to the decl itself.
6766   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6767     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6768       return true;
6769   }
6770 
6771   // Finally, check attributes on the decl itself.
6772   return PD.getAttributes().hasAttribute(Kind);
6773 }
6774 
6775 /// Adjust the \c DeclContext for a function or variable that might be a
6776 /// function-local external declaration.
6777 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6778   if (!DC->isFunctionOrMethod())
6779     return false;
6780 
6781   // If this is a local extern function or variable declared within a function
6782   // template, don't add it into the enclosing namespace scope until it is
6783   // instantiated; it might have a dependent type right now.
6784   if (DC->isDependentContext())
6785     return true;
6786 
6787   // C++11 [basic.link]p7:
6788   //   When a block scope declaration of an entity with linkage is not found to
6789   //   refer to some other declaration, then that entity is a member of the
6790   //   innermost enclosing namespace.
6791   //
6792   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6793   // semantically-enclosing namespace, not a lexically-enclosing one.
6794   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6795     DC = DC->getParent();
6796   return true;
6797 }
6798 
6799 /// Returns true if given declaration has external C language linkage.
6800 static bool isDeclExternC(const Decl *D) {
6801   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6802     return FD->isExternC();
6803   if (const auto *VD = dyn_cast<VarDecl>(D))
6804     return VD->isExternC();
6805 
6806   llvm_unreachable("Unknown type of decl!");
6807 }
6808 
6809 /// Returns true if there hasn't been any invalid type diagnosed.
6810 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6811   DeclContext *DC = NewVD->getDeclContext();
6812   QualType R = NewVD->getType();
6813 
6814   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6815   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6816   // argument.
6817   if (R->isImageType() || R->isPipeType()) {
6818     Se.Diag(NewVD->getLocation(),
6819             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6820         << R;
6821     NewVD->setInvalidDecl();
6822     return false;
6823   }
6824 
6825   // OpenCL v1.2 s6.9.r:
6826   // The event type cannot be used to declare a program scope variable.
6827   // OpenCL v2.0 s6.9.q:
6828   // The clk_event_t and reserve_id_t types cannot be declared in program
6829   // scope.
6830   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6831     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6832       Se.Diag(NewVD->getLocation(),
6833               diag::err_invalid_type_for_program_scope_var)
6834           << R;
6835       NewVD->setInvalidDecl();
6836       return false;
6837     }
6838   }
6839 
6840   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6841   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6842                                                Se.getLangOpts())) {
6843     QualType NR = R.getCanonicalType();
6844     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6845            NR->isReferenceType()) {
6846       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6847           NR->isFunctionReferenceType()) {
6848         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6849             << NR->isReferenceType();
6850         NewVD->setInvalidDecl();
6851         return false;
6852       }
6853       NR = NR->getPointeeType();
6854     }
6855   }
6856 
6857   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6858                                                Se.getLangOpts())) {
6859     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6860     // half array type (unless the cl_khr_fp16 extension is enabled).
6861     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6862       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6863       NewVD->setInvalidDecl();
6864       return false;
6865     }
6866   }
6867 
6868   // OpenCL v1.2 s6.9.r:
6869   // The event type cannot be used with the __local, __constant and __global
6870   // address space qualifiers.
6871   if (R->isEventT()) {
6872     if (R.getAddressSpace() != LangAS::opencl_private) {
6873       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6874       NewVD->setInvalidDecl();
6875       return false;
6876     }
6877   }
6878 
6879   if (R->isSamplerT()) {
6880     // OpenCL v1.2 s6.9.b p4:
6881     // The sampler type cannot be used with the __local and __global address
6882     // space qualifiers.
6883     if (R.getAddressSpace() == LangAS::opencl_local ||
6884         R.getAddressSpace() == LangAS::opencl_global) {
6885       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6886       NewVD->setInvalidDecl();
6887     }
6888 
6889     // OpenCL v1.2 s6.12.14.1:
6890     // A global sampler must be declared with either the constant address
6891     // space qualifier or with the const qualifier.
6892     if (DC->isTranslationUnit() &&
6893         !(R.getAddressSpace() == LangAS::opencl_constant ||
6894           R.isConstQualified())) {
6895       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6896       NewVD->setInvalidDecl();
6897     }
6898     if (NewVD->isInvalidDecl())
6899       return false;
6900   }
6901 
6902   return true;
6903 }
6904 
6905 template <typename AttrTy>
6906 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6907   const TypedefNameDecl *TND = TT->getDecl();
6908   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6909     AttrTy *Clone = Attribute->clone(S.Context);
6910     Clone->setInherited(true);
6911     D->addAttr(Clone);
6912   }
6913 }
6914 
6915 NamedDecl *Sema::ActOnVariableDeclarator(
6916     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6917     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6918     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6919   QualType R = TInfo->getType();
6920   DeclarationName Name = GetNameForDeclarator(D).getName();
6921 
6922   IdentifierInfo *II = Name.getAsIdentifierInfo();
6923 
6924   if (D.isDecompositionDeclarator()) {
6925     // Take the name of the first declarator as our name for diagnostic
6926     // purposes.
6927     auto &Decomp = D.getDecompositionDeclarator();
6928     if (!Decomp.bindings().empty()) {
6929       II = Decomp.bindings()[0].Name;
6930       Name = II;
6931     }
6932   } else if (!II) {
6933     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6934     return nullptr;
6935   }
6936 
6937 
6938   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6939   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6940 
6941   // dllimport globals without explicit storage class are treated as extern. We
6942   // have to change the storage class this early to get the right DeclContext.
6943   if (SC == SC_None && !DC->isRecord() &&
6944       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6945       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6946     SC = SC_Extern;
6947 
6948   DeclContext *OriginalDC = DC;
6949   bool IsLocalExternDecl = SC == SC_Extern &&
6950                            adjustContextForLocalExternDecl(DC);
6951 
6952   if (SCSpec == DeclSpec::SCS_mutable) {
6953     // mutable can only appear on non-static class members, so it's always
6954     // an error here
6955     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6956     D.setInvalidType();
6957     SC = SC_None;
6958   }
6959 
6960   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6961       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6962                               D.getDeclSpec().getStorageClassSpecLoc())) {
6963     // In C++11, the 'register' storage class specifier is deprecated.
6964     // Suppress the warning in system macros, it's used in macros in some
6965     // popular C system headers, such as in glibc's htonl() macro.
6966     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6967          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6968                                    : diag::warn_deprecated_register)
6969       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6970   }
6971 
6972   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6973 
6974   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6975     // C99 6.9p2: The storage-class specifiers auto and register shall not
6976     // appear in the declaration specifiers in an external declaration.
6977     // Global Register+Asm is a GNU extension we support.
6978     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6979       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6980       D.setInvalidType();
6981     }
6982   }
6983 
6984   // If this variable has a VLA type and an initializer, try to
6985   // fold to a constant-sized type. This is otherwise invalid.
6986   if (D.hasInitializer() && R->isVariableArrayType())
6987     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6988                                     /*DiagID=*/0);
6989 
6990   bool IsMemberSpecialization = false;
6991   bool IsVariableTemplateSpecialization = false;
6992   bool IsPartialSpecialization = false;
6993   bool IsVariableTemplate = false;
6994   VarDecl *NewVD = nullptr;
6995   VarTemplateDecl *NewTemplate = nullptr;
6996   TemplateParameterList *TemplateParams = nullptr;
6997   if (!getLangOpts().CPlusPlus) {
6998     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6999                             II, R, TInfo, SC);
7000 
7001     if (R->getContainedDeducedType())
7002       ParsingInitForAutoVars.insert(NewVD);
7003 
7004     if (D.isInvalidType())
7005       NewVD->setInvalidDecl();
7006 
7007     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7008         NewVD->hasLocalStorage())
7009       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7010                             NTCUC_AutoVar, NTCUK_Destruct);
7011   } else {
7012     bool Invalid = false;
7013 
7014     if (DC->isRecord() && !CurContext->isRecord()) {
7015       // This is an out-of-line definition of a static data member.
7016       switch (SC) {
7017       case SC_None:
7018         break;
7019       case SC_Static:
7020         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7021              diag::err_static_out_of_line)
7022           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7023         break;
7024       case SC_Auto:
7025       case SC_Register:
7026       case SC_Extern:
7027         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7028         // to names of variables declared in a block or to function parameters.
7029         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7030         // of class members
7031 
7032         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7033              diag::err_storage_class_for_static_member)
7034           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7035         break;
7036       case SC_PrivateExtern:
7037         llvm_unreachable("C storage class in c++!");
7038       }
7039     }
7040 
7041     if (SC == SC_Static && CurContext->isRecord()) {
7042       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7043         // Walk up the enclosing DeclContexts to check for any that are
7044         // incompatible with static data members.
7045         const DeclContext *FunctionOrMethod = nullptr;
7046         const CXXRecordDecl *AnonStruct = nullptr;
7047         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7048           if (Ctxt->isFunctionOrMethod()) {
7049             FunctionOrMethod = Ctxt;
7050             break;
7051           }
7052           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7053           if (ParentDecl && !ParentDecl->getDeclName()) {
7054             AnonStruct = ParentDecl;
7055             break;
7056           }
7057         }
7058         if (FunctionOrMethod) {
7059           // C++ [class.static.data]p5: A local class shall not have static data
7060           // members.
7061           Diag(D.getIdentifierLoc(),
7062                diag::err_static_data_member_not_allowed_in_local_class)
7063             << Name << RD->getDeclName() << RD->getTagKind();
7064         } else if (AnonStruct) {
7065           // C++ [class.static.data]p4: Unnamed classes and classes contained
7066           // directly or indirectly within unnamed classes shall not contain
7067           // static data members.
7068           Diag(D.getIdentifierLoc(),
7069                diag::err_static_data_member_not_allowed_in_anon_struct)
7070             << Name << AnonStruct->getTagKind();
7071           Invalid = true;
7072         } else if (RD->isUnion()) {
7073           // C++98 [class.union]p1: If a union contains a static data member,
7074           // the program is ill-formed. C++11 drops this restriction.
7075           Diag(D.getIdentifierLoc(),
7076                getLangOpts().CPlusPlus11
7077                  ? diag::warn_cxx98_compat_static_data_member_in_union
7078                  : diag::ext_static_data_member_in_union) << Name;
7079         }
7080       }
7081     }
7082 
7083     // Match up the template parameter lists with the scope specifier, then
7084     // determine whether we have a template or a template specialization.
7085     bool InvalidScope = false;
7086     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7087         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7088         D.getCXXScopeSpec(),
7089         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7090             ? D.getName().TemplateId
7091             : nullptr,
7092         TemplateParamLists,
7093         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7094     Invalid |= InvalidScope;
7095 
7096     if (TemplateParams) {
7097       if (!TemplateParams->size() &&
7098           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7099         // There is an extraneous 'template<>' for this variable. Complain
7100         // about it, but allow the declaration of the variable.
7101         Diag(TemplateParams->getTemplateLoc(),
7102              diag::err_template_variable_noparams)
7103           << II
7104           << SourceRange(TemplateParams->getTemplateLoc(),
7105                          TemplateParams->getRAngleLoc());
7106         TemplateParams = nullptr;
7107       } else {
7108         // Check that we can declare a template here.
7109         if (CheckTemplateDeclScope(S, TemplateParams))
7110           return nullptr;
7111 
7112         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7113           // This is an explicit specialization or a partial specialization.
7114           IsVariableTemplateSpecialization = true;
7115           IsPartialSpecialization = TemplateParams->size() > 0;
7116         } else { // if (TemplateParams->size() > 0)
7117           // This is a template declaration.
7118           IsVariableTemplate = true;
7119 
7120           // Only C++1y supports variable templates (N3651).
7121           Diag(D.getIdentifierLoc(),
7122                getLangOpts().CPlusPlus14
7123                    ? diag::warn_cxx11_compat_variable_template
7124                    : diag::ext_variable_template);
7125         }
7126       }
7127     } else {
7128       // Check that we can declare a member specialization here.
7129       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7130           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7131         return nullptr;
7132       assert((Invalid ||
7133               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7134              "should have a 'template<>' for this decl");
7135     }
7136 
7137     if (IsVariableTemplateSpecialization) {
7138       SourceLocation TemplateKWLoc =
7139           TemplateParamLists.size() > 0
7140               ? TemplateParamLists[0]->getTemplateLoc()
7141               : SourceLocation();
7142       DeclResult Res = ActOnVarTemplateSpecialization(
7143           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7144           IsPartialSpecialization);
7145       if (Res.isInvalid())
7146         return nullptr;
7147       NewVD = cast<VarDecl>(Res.get());
7148       AddToScope = false;
7149     } else if (D.isDecompositionDeclarator()) {
7150       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7151                                         D.getIdentifierLoc(), R, TInfo, SC,
7152                                         Bindings);
7153     } else
7154       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7155                               D.getIdentifierLoc(), II, R, TInfo, SC);
7156 
7157     // If this is supposed to be a variable template, create it as such.
7158     if (IsVariableTemplate) {
7159       NewTemplate =
7160           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7161                                   TemplateParams, NewVD);
7162       NewVD->setDescribedVarTemplate(NewTemplate);
7163     }
7164 
7165     // If this decl has an auto type in need of deduction, make a note of the
7166     // Decl so we can diagnose uses of it in its own initializer.
7167     if (R->getContainedDeducedType())
7168       ParsingInitForAutoVars.insert(NewVD);
7169 
7170     if (D.isInvalidType() || Invalid) {
7171       NewVD->setInvalidDecl();
7172       if (NewTemplate)
7173         NewTemplate->setInvalidDecl();
7174     }
7175 
7176     SetNestedNameSpecifier(*this, NewVD, D);
7177 
7178     // If we have any template parameter lists that don't directly belong to
7179     // the variable (matching the scope specifier), store them.
7180     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7181     if (TemplateParamLists.size() > VDTemplateParamLists)
7182       NewVD->setTemplateParameterListsInfo(
7183           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7184   }
7185 
7186   if (D.getDeclSpec().isInlineSpecified()) {
7187     if (!getLangOpts().CPlusPlus) {
7188       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7189           << 0;
7190     } else if (CurContext->isFunctionOrMethod()) {
7191       // 'inline' is not allowed on block scope variable declaration.
7192       Diag(D.getDeclSpec().getInlineSpecLoc(),
7193            diag::err_inline_declaration_block_scope) << Name
7194         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7195     } else {
7196       Diag(D.getDeclSpec().getInlineSpecLoc(),
7197            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7198                                      : diag::ext_inline_variable);
7199       NewVD->setInlineSpecified();
7200     }
7201   }
7202 
7203   // Set the lexical context. If the declarator has a C++ scope specifier, the
7204   // lexical context will be different from the semantic context.
7205   NewVD->setLexicalDeclContext(CurContext);
7206   if (NewTemplate)
7207     NewTemplate->setLexicalDeclContext(CurContext);
7208 
7209   if (IsLocalExternDecl) {
7210     if (D.isDecompositionDeclarator())
7211       for (auto *B : Bindings)
7212         B->setLocalExternDecl();
7213     else
7214       NewVD->setLocalExternDecl();
7215   }
7216 
7217   bool EmitTLSUnsupportedError = false;
7218   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7219     // C++11 [dcl.stc]p4:
7220     //   When thread_local is applied to a variable of block scope the
7221     //   storage-class-specifier static is implied if it does not appear
7222     //   explicitly.
7223     // Core issue: 'static' is not implied if the variable is declared
7224     //   'extern'.
7225     if (NewVD->hasLocalStorage() &&
7226         (SCSpec != DeclSpec::SCS_unspecified ||
7227          TSCS != DeclSpec::TSCS_thread_local ||
7228          !DC->isFunctionOrMethod()))
7229       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7230            diag::err_thread_non_global)
7231         << DeclSpec::getSpecifierName(TSCS);
7232     else if (!Context.getTargetInfo().isTLSSupported()) {
7233       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7234           getLangOpts().SYCLIsDevice) {
7235         // Postpone error emission until we've collected attributes required to
7236         // figure out whether it's a host or device variable and whether the
7237         // error should be ignored.
7238         EmitTLSUnsupportedError = true;
7239         // We still need to mark the variable as TLS so it shows up in AST with
7240         // proper storage class for other tools to use even if we're not going
7241         // to emit any code for it.
7242         NewVD->setTSCSpec(TSCS);
7243       } else
7244         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7245              diag::err_thread_unsupported);
7246     } else
7247       NewVD->setTSCSpec(TSCS);
7248   }
7249 
7250   switch (D.getDeclSpec().getConstexprSpecifier()) {
7251   case ConstexprSpecKind::Unspecified:
7252     break;
7253 
7254   case ConstexprSpecKind::Consteval:
7255     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7256          diag::err_constexpr_wrong_decl_kind)
7257         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7258     LLVM_FALLTHROUGH;
7259 
7260   case ConstexprSpecKind::Constexpr:
7261     NewVD->setConstexpr(true);
7262     // C++1z [dcl.spec.constexpr]p1:
7263     //   A static data member declared with the constexpr specifier is
7264     //   implicitly an inline variable.
7265     if (NewVD->isStaticDataMember() &&
7266         (getLangOpts().CPlusPlus17 ||
7267          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7268       NewVD->setImplicitlyInline();
7269     break;
7270 
7271   case ConstexprSpecKind::Constinit:
7272     if (!NewVD->hasGlobalStorage())
7273       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7274            diag::err_constinit_local_variable);
7275     else
7276       NewVD->addAttr(ConstInitAttr::Create(
7277           Context, D.getDeclSpec().getConstexprSpecLoc(),
7278           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7279     break;
7280   }
7281 
7282   // C99 6.7.4p3
7283   //   An inline definition of a function with external linkage shall
7284   //   not contain a definition of a modifiable object with static or
7285   //   thread storage duration...
7286   // We only apply this when the function is required to be defined
7287   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7288   // that a local variable with thread storage duration still has to
7289   // be marked 'static'.  Also note that it's possible to get these
7290   // semantics in C++ using __attribute__((gnu_inline)).
7291   if (SC == SC_Static && S->getFnParent() != nullptr &&
7292       !NewVD->getType().isConstQualified()) {
7293     FunctionDecl *CurFD = getCurFunctionDecl();
7294     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7295       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7296            diag::warn_static_local_in_extern_inline);
7297       MaybeSuggestAddingStaticToDecl(CurFD);
7298     }
7299   }
7300 
7301   if (D.getDeclSpec().isModulePrivateSpecified()) {
7302     if (IsVariableTemplateSpecialization)
7303       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7304           << (IsPartialSpecialization ? 1 : 0)
7305           << FixItHint::CreateRemoval(
7306                  D.getDeclSpec().getModulePrivateSpecLoc());
7307     else if (IsMemberSpecialization)
7308       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7309         << 2
7310         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7311     else if (NewVD->hasLocalStorage())
7312       Diag(NewVD->getLocation(), diag::err_module_private_local)
7313           << 0 << NewVD
7314           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7315           << FixItHint::CreateRemoval(
7316                  D.getDeclSpec().getModulePrivateSpecLoc());
7317     else {
7318       NewVD->setModulePrivate();
7319       if (NewTemplate)
7320         NewTemplate->setModulePrivate();
7321       for (auto *B : Bindings)
7322         B->setModulePrivate();
7323     }
7324   }
7325 
7326   if (getLangOpts().OpenCL) {
7327     deduceOpenCLAddressSpace(NewVD);
7328 
7329     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7330     if (TSC != TSCS_unspecified) {
7331       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7332       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7333            diag::err_opencl_unknown_type_specifier)
7334           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7335           << DeclSpec::getSpecifierName(TSC) << 1;
7336       NewVD->setInvalidDecl();
7337     }
7338   }
7339 
7340   // Handle attributes prior to checking for duplicates in MergeVarDecl
7341   ProcessDeclAttributes(S, NewVD, D);
7342 
7343   // FIXME: This is probably the wrong location to be doing this and we should
7344   // probably be doing this for more attributes (especially for function
7345   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7346   // the code to copy attributes would be generated by TableGen.
7347   if (R->isFunctionPointerType())
7348     if (const auto *TT = R->getAs<TypedefType>())
7349       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7350 
7351   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7352       getLangOpts().SYCLIsDevice) {
7353     if (EmitTLSUnsupportedError &&
7354         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7355          (getLangOpts().OpenMPIsDevice &&
7356           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7357       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7358            diag::err_thread_unsupported);
7359 
7360     if (EmitTLSUnsupportedError &&
7361         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7362       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7363     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7364     // storage [duration]."
7365     if (SC == SC_None && S->getFnParent() != nullptr &&
7366         (NewVD->hasAttr<CUDASharedAttr>() ||
7367          NewVD->hasAttr<CUDAConstantAttr>())) {
7368       NewVD->setStorageClass(SC_Static);
7369     }
7370   }
7371 
7372   // Ensure that dllimport globals without explicit storage class are treated as
7373   // extern. The storage class is set above using parsed attributes. Now we can
7374   // check the VarDecl itself.
7375   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7376          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7377          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7378 
7379   // In auto-retain/release, infer strong retension for variables of
7380   // retainable type.
7381   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7382     NewVD->setInvalidDecl();
7383 
7384   // Handle GNU asm-label extension (encoded as an attribute).
7385   if (Expr *E = (Expr*)D.getAsmLabel()) {
7386     // The parser guarantees this is a string.
7387     StringLiteral *SE = cast<StringLiteral>(E);
7388     StringRef Label = SE->getString();
7389     if (S->getFnParent() != nullptr) {
7390       switch (SC) {
7391       case SC_None:
7392       case SC_Auto:
7393         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7394         break;
7395       case SC_Register:
7396         // Local Named register
7397         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7398             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7399           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7400         break;
7401       case SC_Static:
7402       case SC_Extern:
7403       case SC_PrivateExtern:
7404         break;
7405       }
7406     } else if (SC == SC_Register) {
7407       // Global Named register
7408       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7409         const auto &TI = Context.getTargetInfo();
7410         bool HasSizeMismatch;
7411 
7412         if (!TI.isValidGCCRegisterName(Label))
7413           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7414         else if (!TI.validateGlobalRegisterVariable(Label,
7415                                                     Context.getTypeSize(R),
7416                                                     HasSizeMismatch))
7417           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7418         else if (HasSizeMismatch)
7419           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7420       }
7421 
7422       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7423         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7424         NewVD->setInvalidDecl(true);
7425       }
7426     }
7427 
7428     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7429                                         /*IsLiteralLabel=*/true,
7430                                         SE->getStrTokenLoc(0)));
7431   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7432     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7433       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7434     if (I != ExtnameUndeclaredIdentifiers.end()) {
7435       if (isDeclExternC(NewVD)) {
7436         NewVD->addAttr(I->second);
7437         ExtnameUndeclaredIdentifiers.erase(I);
7438       } else
7439         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7440             << /*Variable*/1 << NewVD;
7441     }
7442   }
7443 
7444   // Find the shadowed declaration before filtering for scope.
7445   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7446                                 ? getShadowedDeclaration(NewVD, Previous)
7447                                 : nullptr;
7448 
7449   // Don't consider existing declarations that are in a different
7450   // scope and are out-of-semantic-context declarations (if the new
7451   // declaration has linkage).
7452   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7453                        D.getCXXScopeSpec().isNotEmpty() ||
7454                        IsMemberSpecialization ||
7455                        IsVariableTemplateSpecialization);
7456 
7457   // Check whether the previous declaration is in the same block scope. This
7458   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7459   if (getLangOpts().CPlusPlus &&
7460       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7461     NewVD->setPreviousDeclInSameBlockScope(
7462         Previous.isSingleResult() && !Previous.isShadowed() &&
7463         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7464 
7465   if (!getLangOpts().CPlusPlus) {
7466     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7467   } else {
7468     // If this is an explicit specialization of a static data member, check it.
7469     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7470         CheckMemberSpecialization(NewVD, Previous))
7471       NewVD->setInvalidDecl();
7472 
7473     // Merge the decl with the existing one if appropriate.
7474     if (!Previous.empty()) {
7475       if (Previous.isSingleResult() &&
7476           isa<FieldDecl>(Previous.getFoundDecl()) &&
7477           D.getCXXScopeSpec().isSet()) {
7478         // The user tried to define a non-static data member
7479         // out-of-line (C++ [dcl.meaning]p1).
7480         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7481           << D.getCXXScopeSpec().getRange();
7482         Previous.clear();
7483         NewVD->setInvalidDecl();
7484       }
7485     } else if (D.getCXXScopeSpec().isSet()) {
7486       // No previous declaration in the qualifying scope.
7487       Diag(D.getIdentifierLoc(), diag::err_no_member)
7488         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7489         << D.getCXXScopeSpec().getRange();
7490       NewVD->setInvalidDecl();
7491     }
7492 
7493     if (!IsVariableTemplateSpecialization)
7494       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7495 
7496     if (NewTemplate) {
7497       VarTemplateDecl *PrevVarTemplate =
7498           NewVD->getPreviousDecl()
7499               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7500               : nullptr;
7501 
7502       // Check the template parameter list of this declaration, possibly
7503       // merging in the template parameter list from the previous variable
7504       // template declaration.
7505       if (CheckTemplateParameterList(
7506               TemplateParams,
7507               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7508                               : nullptr,
7509               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7510                DC->isDependentContext())
7511                   ? TPC_ClassTemplateMember
7512                   : TPC_VarTemplate))
7513         NewVD->setInvalidDecl();
7514 
7515       // If we are providing an explicit specialization of a static variable
7516       // template, make a note of that.
7517       if (PrevVarTemplate &&
7518           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7519         PrevVarTemplate->setMemberSpecialization();
7520     }
7521   }
7522 
7523   // Diagnose shadowed variables iff this isn't a redeclaration.
7524   if (ShadowedDecl && !D.isRedeclaration())
7525     CheckShadow(NewVD, ShadowedDecl, Previous);
7526 
7527   ProcessPragmaWeak(S, NewVD);
7528 
7529   // If this is the first declaration of an extern C variable, update
7530   // the map of such variables.
7531   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7532       isIncompleteDeclExternC(*this, NewVD))
7533     RegisterLocallyScopedExternCDecl(NewVD, S);
7534 
7535   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7536     MangleNumberingContext *MCtx;
7537     Decl *ManglingContextDecl;
7538     std::tie(MCtx, ManglingContextDecl) =
7539         getCurrentMangleNumberContext(NewVD->getDeclContext());
7540     if (MCtx) {
7541       Context.setManglingNumber(
7542           NewVD, MCtx->getManglingNumber(
7543                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7544       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7545     }
7546   }
7547 
7548   // Special handling of variable named 'main'.
7549   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7550       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7551       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7552 
7553     // C++ [basic.start.main]p3
7554     // A program that declares a variable main at global scope is ill-formed.
7555     if (getLangOpts().CPlusPlus)
7556       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7557 
7558     // In C, and external-linkage variable named main results in undefined
7559     // behavior.
7560     else if (NewVD->hasExternalFormalLinkage())
7561       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7562   }
7563 
7564   if (D.isRedeclaration() && !Previous.empty()) {
7565     NamedDecl *Prev = Previous.getRepresentativeDecl();
7566     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7567                                    D.isFunctionDefinition());
7568   }
7569 
7570   if (NewTemplate) {
7571     if (NewVD->isInvalidDecl())
7572       NewTemplate->setInvalidDecl();
7573     ActOnDocumentableDecl(NewTemplate);
7574     return NewTemplate;
7575   }
7576 
7577   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7578     CompleteMemberSpecialization(NewVD, Previous);
7579 
7580   return NewVD;
7581 }
7582 
7583 /// Enum describing the %select options in diag::warn_decl_shadow.
7584 enum ShadowedDeclKind {
7585   SDK_Local,
7586   SDK_Global,
7587   SDK_StaticMember,
7588   SDK_Field,
7589   SDK_Typedef,
7590   SDK_Using,
7591   SDK_StructuredBinding
7592 };
7593 
7594 /// Determine what kind of declaration we're shadowing.
7595 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7596                                                 const DeclContext *OldDC) {
7597   if (isa<TypeAliasDecl>(ShadowedDecl))
7598     return SDK_Using;
7599   else if (isa<TypedefDecl>(ShadowedDecl))
7600     return SDK_Typedef;
7601   else if (isa<BindingDecl>(ShadowedDecl))
7602     return SDK_StructuredBinding;
7603   else if (isa<RecordDecl>(OldDC))
7604     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7605 
7606   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7607 }
7608 
7609 /// Return the location of the capture if the given lambda captures the given
7610 /// variable \p VD, or an invalid source location otherwise.
7611 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7612                                          const VarDecl *VD) {
7613   for (const Capture &Capture : LSI->Captures) {
7614     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7615       return Capture.getLocation();
7616   }
7617   return SourceLocation();
7618 }
7619 
7620 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7621                                      const LookupResult &R) {
7622   // Only diagnose if we're shadowing an unambiguous field or variable.
7623   if (R.getResultKind() != LookupResult::Found)
7624     return false;
7625 
7626   // Return false if warning is ignored.
7627   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7628 }
7629 
7630 /// Return the declaration shadowed by the given variable \p D, or null
7631 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7632 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7633                                         const LookupResult &R) {
7634   if (!shouldWarnIfShadowedDecl(Diags, R))
7635     return nullptr;
7636 
7637   // Don't diagnose declarations at file scope.
7638   if (D->hasGlobalStorage())
7639     return nullptr;
7640 
7641   NamedDecl *ShadowedDecl = R.getFoundDecl();
7642   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7643                                                             : nullptr;
7644 }
7645 
7646 /// Return the declaration shadowed by the given typedef \p D, or null
7647 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7648 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7649                                         const LookupResult &R) {
7650   // Don't warn if typedef declaration is part of a class
7651   if (D->getDeclContext()->isRecord())
7652     return nullptr;
7653 
7654   if (!shouldWarnIfShadowedDecl(Diags, R))
7655     return nullptr;
7656 
7657   NamedDecl *ShadowedDecl = R.getFoundDecl();
7658   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7659 }
7660 
7661 /// Return the declaration shadowed by the given variable \p D, or null
7662 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7663 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7664                                         const LookupResult &R) {
7665   if (!shouldWarnIfShadowedDecl(Diags, R))
7666     return nullptr;
7667 
7668   NamedDecl *ShadowedDecl = R.getFoundDecl();
7669   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7670                                                             : nullptr;
7671 }
7672 
7673 /// Diagnose variable or built-in function shadowing.  Implements
7674 /// -Wshadow.
7675 ///
7676 /// This method is called whenever a VarDecl is added to a "useful"
7677 /// scope.
7678 ///
7679 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7680 /// \param R the lookup of the name
7681 ///
7682 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7683                        const LookupResult &R) {
7684   DeclContext *NewDC = D->getDeclContext();
7685 
7686   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7687     // Fields are not shadowed by variables in C++ static methods.
7688     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7689       if (MD->isStatic())
7690         return;
7691 
7692     // Fields shadowed by constructor parameters are a special case. Usually
7693     // the constructor initializes the field with the parameter.
7694     if (isa<CXXConstructorDecl>(NewDC))
7695       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7696         // Remember that this was shadowed so we can either warn about its
7697         // modification or its existence depending on warning settings.
7698         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7699         return;
7700       }
7701   }
7702 
7703   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7704     if (shadowedVar->isExternC()) {
7705       // For shadowing external vars, make sure that we point to the global
7706       // declaration, not a locally scoped extern declaration.
7707       for (auto I : shadowedVar->redecls())
7708         if (I->isFileVarDecl()) {
7709           ShadowedDecl = I;
7710           break;
7711         }
7712     }
7713 
7714   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7715 
7716   unsigned WarningDiag = diag::warn_decl_shadow;
7717   SourceLocation CaptureLoc;
7718   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7719       isa<CXXMethodDecl>(NewDC)) {
7720     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7721       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7722         if (RD->getLambdaCaptureDefault() == LCD_None) {
7723           // Try to avoid warnings for lambdas with an explicit capture list.
7724           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7725           // Warn only when the lambda captures the shadowed decl explicitly.
7726           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7727           if (CaptureLoc.isInvalid())
7728             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7729         } else {
7730           // Remember that this was shadowed so we can avoid the warning if the
7731           // shadowed decl isn't captured and the warning settings allow it.
7732           cast<LambdaScopeInfo>(getCurFunction())
7733               ->ShadowingDecls.push_back(
7734                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7735           return;
7736         }
7737       }
7738 
7739       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7740         // A variable can't shadow a local variable in an enclosing scope, if
7741         // they are separated by a non-capturing declaration context.
7742         for (DeclContext *ParentDC = NewDC;
7743              ParentDC && !ParentDC->Equals(OldDC);
7744              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7745           // Only block literals, captured statements, and lambda expressions
7746           // can capture; other scopes don't.
7747           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7748               !isLambdaCallOperator(ParentDC)) {
7749             return;
7750           }
7751         }
7752       }
7753     }
7754   }
7755 
7756   // Only warn about certain kinds of shadowing for class members.
7757   if (NewDC && NewDC->isRecord()) {
7758     // In particular, don't warn about shadowing non-class members.
7759     if (!OldDC->isRecord())
7760       return;
7761 
7762     // TODO: should we warn about static data members shadowing
7763     // static data members from base classes?
7764 
7765     // TODO: don't diagnose for inaccessible shadowed members.
7766     // This is hard to do perfectly because we might friend the
7767     // shadowing context, but that's just a false negative.
7768   }
7769 
7770 
7771   DeclarationName Name = R.getLookupName();
7772 
7773   // Emit warning and note.
7774   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7775     return;
7776   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7777   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7778   if (!CaptureLoc.isInvalid())
7779     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7780         << Name << /*explicitly*/ 1;
7781   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7782 }
7783 
7784 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7785 /// when these variables are captured by the lambda.
7786 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7787   for (const auto &Shadow : LSI->ShadowingDecls) {
7788     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7789     // Try to avoid the warning when the shadowed decl isn't captured.
7790     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7791     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7792     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7793                                        ? diag::warn_decl_shadow_uncaptured_local
7794                                        : diag::warn_decl_shadow)
7795         << Shadow.VD->getDeclName()
7796         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7797     if (!CaptureLoc.isInvalid())
7798       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7799           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7800     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7801   }
7802 }
7803 
7804 /// Check -Wshadow without the advantage of a previous lookup.
7805 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7806   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7807     return;
7808 
7809   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7810                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7811   LookupName(R, S);
7812   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7813     CheckShadow(D, ShadowedDecl, R);
7814 }
7815 
7816 /// Check if 'E', which is an expression that is about to be modified, refers
7817 /// to a constructor parameter that shadows a field.
7818 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7819   // Quickly ignore expressions that can't be shadowing ctor parameters.
7820   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7821     return;
7822   E = E->IgnoreParenImpCasts();
7823   auto *DRE = dyn_cast<DeclRefExpr>(E);
7824   if (!DRE)
7825     return;
7826   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7827   auto I = ShadowingDecls.find(D);
7828   if (I == ShadowingDecls.end())
7829     return;
7830   const NamedDecl *ShadowedDecl = I->second;
7831   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7832   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7833   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7834   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7835 
7836   // Avoid issuing multiple warnings about the same decl.
7837   ShadowingDecls.erase(I);
7838 }
7839 
7840 /// Check for conflict between this global or extern "C" declaration and
7841 /// previous global or extern "C" declarations. This is only used in C++.
7842 template<typename T>
7843 static bool checkGlobalOrExternCConflict(
7844     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7845   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7846   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7847 
7848   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7849     // The common case: this global doesn't conflict with any extern "C"
7850     // declaration.
7851     return false;
7852   }
7853 
7854   if (Prev) {
7855     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7856       // Both the old and new declarations have C language linkage. This is a
7857       // redeclaration.
7858       Previous.clear();
7859       Previous.addDecl(Prev);
7860       return true;
7861     }
7862 
7863     // This is a global, non-extern "C" declaration, and there is a previous
7864     // non-global extern "C" declaration. Diagnose if this is a variable
7865     // declaration.
7866     if (!isa<VarDecl>(ND))
7867       return false;
7868   } else {
7869     // The declaration is extern "C". Check for any declaration in the
7870     // translation unit which might conflict.
7871     if (IsGlobal) {
7872       // We have already performed the lookup into the translation unit.
7873       IsGlobal = false;
7874       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7875            I != E; ++I) {
7876         if (isa<VarDecl>(*I)) {
7877           Prev = *I;
7878           break;
7879         }
7880       }
7881     } else {
7882       DeclContext::lookup_result R =
7883           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7884       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7885            I != E; ++I) {
7886         if (isa<VarDecl>(*I)) {
7887           Prev = *I;
7888           break;
7889         }
7890         // FIXME: If we have any other entity with this name in global scope,
7891         // the declaration is ill-formed, but that is a defect: it breaks the
7892         // 'stat' hack, for instance. Only variables can have mangled name
7893         // clashes with extern "C" declarations, so only they deserve a
7894         // diagnostic.
7895       }
7896     }
7897 
7898     if (!Prev)
7899       return false;
7900   }
7901 
7902   // Use the first declaration's location to ensure we point at something which
7903   // is lexically inside an extern "C" linkage-spec.
7904   assert(Prev && "should have found a previous declaration to diagnose");
7905   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7906     Prev = FD->getFirstDecl();
7907   else
7908     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7909 
7910   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7911     << IsGlobal << ND;
7912   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7913     << IsGlobal;
7914   return false;
7915 }
7916 
7917 /// Apply special rules for handling extern "C" declarations. Returns \c true
7918 /// if we have found that this is a redeclaration of some prior entity.
7919 ///
7920 /// Per C++ [dcl.link]p6:
7921 ///   Two declarations [for a function or variable] with C language linkage
7922 ///   with the same name that appear in different scopes refer to the same
7923 ///   [entity]. An entity with C language linkage shall not be declared with
7924 ///   the same name as an entity in global scope.
7925 template<typename T>
7926 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7927                                                   LookupResult &Previous) {
7928   if (!S.getLangOpts().CPlusPlus) {
7929     // In C, when declaring a global variable, look for a corresponding 'extern'
7930     // variable declared in function scope. We don't need this in C++, because
7931     // we find local extern decls in the surrounding file-scope DeclContext.
7932     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7933       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7934         Previous.clear();
7935         Previous.addDecl(Prev);
7936         return true;
7937       }
7938     }
7939     return false;
7940   }
7941 
7942   // A declaration in the translation unit can conflict with an extern "C"
7943   // declaration.
7944   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7945     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7946 
7947   // An extern "C" declaration can conflict with a declaration in the
7948   // translation unit or can be a redeclaration of an extern "C" declaration
7949   // in another scope.
7950   if (isIncompleteDeclExternC(S,ND))
7951     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7952 
7953   // Neither global nor extern "C": nothing to do.
7954   return false;
7955 }
7956 
7957 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7958   // If the decl is already known invalid, don't check it.
7959   if (NewVD->isInvalidDecl())
7960     return;
7961 
7962   QualType T = NewVD->getType();
7963 
7964   // Defer checking an 'auto' type until its initializer is attached.
7965   if (T->isUndeducedType())
7966     return;
7967 
7968   if (NewVD->hasAttrs())
7969     CheckAlignasUnderalignment(NewVD);
7970 
7971   if (T->isObjCObjectType()) {
7972     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7973       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7974     T = Context.getObjCObjectPointerType(T);
7975     NewVD->setType(T);
7976   }
7977 
7978   // Emit an error if an address space was applied to decl with local storage.
7979   // This includes arrays of objects with address space qualifiers, but not
7980   // automatic variables that point to other address spaces.
7981   // ISO/IEC TR 18037 S5.1.2
7982   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7983       T.getAddressSpace() != LangAS::Default) {
7984     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7985     NewVD->setInvalidDecl();
7986     return;
7987   }
7988 
7989   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7990   // scope.
7991   if (getLangOpts().OpenCLVersion == 120 &&
7992       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7993                                             getLangOpts()) &&
7994       NewVD->isStaticLocal()) {
7995     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7996     NewVD->setInvalidDecl();
7997     return;
7998   }
7999 
8000   if (getLangOpts().OpenCL) {
8001     if (!diagnoseOpenCLTypes(*this, NewVD))
8002       return;
8003 
8004     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8005     if (NewVD->hasAttr<BlocksAttr>()) {
8006       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8007       return;
8008     }
8009 
8010     if (T->isBlockPointerType()) {
8011       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8012       // can't use 'extern' storage class.
8013       if (!T.isConstQualified()) {
8014         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8015             << 0 /*const*/;
8016         NewVD->setInvalidDecl();
8017         return;
8018       }
8019       if (NewVD->hasExternalStorage()) {
8020         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8021         NewVD->setInvalidDecl();
8022         return;
8023       }
8024     }
8025 
8026     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8027     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8028         NewVD->hasExternalStorage()) {
8029       if (!T->isSamplerT() && !T->isDependentType() &&
8030           !(T.getAddressSpace() == LangAS::opencl_constant ||
8031             (T.getAddressSpace() == LangAS::opencl_global &&
8032              getOpenCLOptions().areProgramScopeVariablesSupported(
8033                  getLangOpts())))) {
8034         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8035         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8036           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8037               << Scope << "global or constant";
8038         else
8039           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8040               << Scope << "constant";
8041         NewVD->setInvalidDecl();
8042         return;
8043       }
8044     } else {
8045       if (T.getAddressSpace() == LangAS::opencl_global) {
8046         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8047             << 1 /*is any function*/ << "global";
8048         NewVD->setInvalidDecl();
8049         return;
8050       }
8051       if (T.getAddressSpace() == LangAS::opencl_constant ||
8052           T.getAddressSpace() == LangAS::opencl_local) {
8053         FunctionDecl *FD = getCurFunctionDecl();
8054         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8055         // in functions.
8056         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8057           if (T.getAddressSpace() == LangAS::opencl_constant)
8058             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8059                 << 0 /*non-kernel only*/ << "constant";
8060           else
8061             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8062                 << 0 /*non-kernel only*/ << "local";
8063           NewVD->setInvalidDecl();
8064           return;
8065         }
8066         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8067         // in the outermost scope of a kernel function.
8068         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8069           if (!getCurScope()->isFunctionScope()) {
8070             if (T.getAddressSpace() == LangAS::opencl_constant)
8071               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8072                   << "constant";
8073             else
8074               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8075                   << "local";
8076             NewVD->setInvalidDecl();
8077             return;
8078           }
8079         }
8080       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8081                  // If we are parsing a template we didn't deduce an addr
8082                  // space yet.
8083                  T.getAddressSpace() != LangAS::Default) {
8084         // Do not allow other address spaces on automatic variable.
8085         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8086         NewVD->setInvalidDecl();
8087         return;
8088       }
8089     }
8090   }
8091 
8092   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8093       && !NewVD->hasAttr<BlocksAttr>()) {
8094     if (getLangOpts().getGC() != LangOptions::NonGC)
8095       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8096     else {
8097       assert(!getLangOpts().ObjCAutoRefCount);
8098       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8099     }
8100   }
8101 
8102   bool isVM = T->isVariablyModifiedType();
8103   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8104       NewVD->hasAttr<BlocksAttr>())
8105     setFunctionHasBranchProtectedScope();
8106 
8107   if ((isVM && NewVD->hasLinkage()) ||
8108       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8109     bool SizeIsNegative;
8110     llvm::APSInt Oversized;
8111     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8112         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8113     QualType FixedT;
8114     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8115       FixedT = FixedTInfo->getType();
8116     else if (FixedTInfo) {
8117       // Type and type-as-written are canonically different. We need to fix up
8118       // both types separately.
8119       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8120                                                    Oversized);
8121     }
8122     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8123       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8124       // FIXME: This won't give the correct result for
8125       // int a[10][n];
8126       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8127 
8128       if (NewVD->isFileVarDecl())
8129         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8130         << SizeRange;
8131       else if (NewVD->isStaticLocal())
8132         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8133         << SizeRange;
8134       else
8135         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8136         << SizeRange;
8137       NewVD->setInvalidDecl();
8138       return;
8139     }
8140 
8141     if (!FixedTInfo) {
8142       if (NewVD->isFileVarDecl())
8143         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8144       else
8145         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8146       NewVD->setInvalidDecl();
8147       return;
8148     }
8149 
8150     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8151     NewVD->setType(FixedT);
8152     NewVD->setTypeSourceInfo(FixedTInfo);
8153   }
8154 
8155   if (T->isVoidType()) {
8156     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8157     //                    of objects and functions.
8158     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8159       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8160         << T;
8161       NewVD->setInvalidDecl();
8162       return;
8163     }
8164   }
8165 
8166   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8167     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8168     NewVD->setInvalidDecl();
8169     return;
8170   }
8171 
8172   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8173     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8174     NewVD->setInvalidDecl();
8175     return;
8176   }
8177 
8178   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8179     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8180     NewVD->setInvalidDecl();
8181     return;
8182   }
8183 
8184   if (NewVD->isConstexpr() && !T->isDependentType() &&
8185       RequireLiteralType(NewVD->getLocation(), T,
8186                          diag::err_constexpr_var_non_literal)) {
8187     NewVD->setInvalidDecl();
8188     return;
8189   }
8190 
8191   // PPC MMA non-pointer types are not allowed as non-local variable types.
8192   if (Context.getTargetInfo().getTriple().isPPC64() &&
8193       !NewVD->isLocalVarDecl() &&
8194       CheckPPCMMAType(T, NewVD->getLocation())) {
8195     NewVD->setInvalidDecl();
8196     return;
8197   }
8198 }
8199 
8200 /// Perform semantic checking on a newly-created variable
8201 /// declaration.
8202 ///
8203 /// This routine performs all of the type-checking required for a
8204 /// variable declaration once it has been built. It is used both to
8205 /// check variables after they have been parsed and their declarators
8206 /// have been translated into a declaration, and to check variables
8207 /// that have been instantiated from a template.
8208 ///
8209 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8210 ///
8211 /// Returns true if the variable declaration is a redeclaration.
8212 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8213   CheckVariableDeclarationType(NewVD);
8214 
8215   // If the decl is already known invalid, don't check it.
8216   if (NewVD->isInvalidDecl())
8217     return false;
8218 
8219   // If we did not find anything by this name, look for a non-visible
8220   // extern "C" declaration with the same name.
8221   if (Previous.empty() &&
8222       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8223     Previous.setShadowed();
8224 
8225   if (!Previous.empty()) {
8226     MergeVarDecl(NewVD, Previous);
8227     return true;
8228   }
8229   return false;
8230 }
8231 
8232 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8233 /// and if so, check that it's a valid override and remember it.
8234 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8235   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8236 
8237   // Look for methods in base classes that this method might override.
8238   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8239                      /*DetectVirtual=*/false);
8240   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8241     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8242     DeclarationName Name = MD->getDeclName();
8243 
8244     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8245       // We really want to find the base class destructor here.
8246       QualType T = Context.getTypeDeclType(BaseRecord);
8247       CanQualType CT = Context.getCanonicalType(T);
8248       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8249     }
8250 
8251     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8252       CXXMethodDecl *BaseMD =
8253           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8254       if (!BaseMD || !BaseMD->isVirtual() ||
8255           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8256                      /*ConsiderCudaAttrs=*/true,
8257                      // C++2a [class.virtual]p2 does not consider requires
8258                      // clauses when overriding.
8259                      /*ConsiderRequiresClauses=*/false))
8260         continue;
8261 
8262       if (Overridden.insert(BaseMD).second) {
8263         MD->addOverriddenMethod(BaseMD);
8264         CheckOverridingFunctionReturnType(MD, BaseMD);
8265         CheckOverridingFunctionAttributes(MD, BaseMD);
8266         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8267         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8268       }
8269 
8270       // A method can only override one function from each base class. We
8271       // don't track indirectly overridden methods from bases of bases.
8272       return true;
8273     }
8274 
8275     return false;
8276   };
8277 
8278   DC->lookupInBases(VisitBase, Paths);
8279   return !Overridden.empty();
8280 }
8281 
8282 namespace {
8283   // Struct for holding all of the extra arguments needed by
8284   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8285   struct ActOnFDArgs {
8286     Scope *S;
8287     Declarator &D;
8288     MultiTemplateParamsArg TemplateParamLists;
8289     bool AddToScope;
8290   };
8291 } // end anonymous namespace
8292 
8293 namespace {
8294 
8295 // Callback to only accept typo corrections that have a non-zero edit distance.
8296 // Also only accept corrections that have the same parent decl.
8297 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8298  public:
8299   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8300                             CXXRecordDecl *Parent)
8301       : Context(Context), OriginalFD(TypoFD),
8302         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8303 
8304   bool ValidateCandidate(const TypoCorrection &candidate) override {
8305     if (candidate.getEditDistance() == 0)
8306       return false;
8307 
8308     SmallVector<unsigned, 1> MismatchedParams;
8309     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8310                                           CDeclEnd = candidate.end();
8311          CDecl != CDeclEnd; ++CDecl) {
8312       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8313 
8314       if (FD && !FD->hasBody() &&
8315           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8316         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8317           CXXRecordDecl *Parent = MD->getParent();
8318           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8319             return true;
8320         } else if (!ExpectedParent) {
8321           return true;
8322         }
8323       }
8324     }
8325 
8326     return false;
8327   }
8328 
8329   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8330     return std::make_unique<DifferentNameValidatorCCC>(*this);
8331   }
8332 
8333  private:
8334   ASTContext &Context;
8335   FunctionDecl *OriginalFD;
8336   CXXRecordDecl *ExpectedParent;
8337 };
8338 
8339 } // end anonymous namespace
8340 
8341 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8342   TypoCorrectedFunctionDefinitions.insert(F);
8343 }
8344 
8345 /// Generate diagnostics for an invalid function redeclaration.
8346 ///
8347 /// This routine handles generating the diagnostic messages for an invalid
8348 /// function redeclaration, including finding possible similar declarations
8349 /// or performing typo correction if there are no previous declarations with
8350 /// the same name.
8351 ///
8352 /// Returns a NamedDecl iff typo correction was performed and substituting in
8353 /// the new declaration name does not cause new errors.
8354 static NamedDecl *DiagnoseInvalidRedeclaration(
8355     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8356     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8357   DeclarationName Name = NewFD->getDeclName();
8358   DeclContext *NewDC = NewFD->getDeclContext();
8359   SmallVector<unsigned, 1> MismatchedParams;
8360   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8361   TypoCorrection Correction;
8362   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8363   unsigned DiagMsg =
8364     IsLocalFriend ? diag::err_no_matching_local_friend :
8365     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8366     diag::err_member_decl_does_not_match;
8367   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8368                     IsLocalFriend ? Sema::LookupLocalFriendName
8369                                   : Sema::LookupOrdinaryName,
8370                     Sema::ForVisibleRedeclaration);
8371 
8372   NewFD->setInvalidDecl();
8373   if (IsLocalFriend)
8374     SemaRef.LookupName(Prev, S);
8375   else
8376     SemaRef.LookupQualifiedName(Prev, NewDC);
8377   assert(!Prev.isAmbiguous() &&
8378          "Cannot have an ambiguity in previous-declaration lookup");
8379   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8380   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8381                                 MD ? MD->getParent() : nullptr);
8382   if (!Prev.empty()) {
8383     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8384          Func != FuncEnd; ++Func) {
8385       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8386       if (FD &&
8387           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8388         // Add 1 to the index so that 0 can mean the mismatch didn't
8389         // involve a parameter
8390         unsigned ParamNum =
8391             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8392         NearMatches.push_back(std::make_pair(FD, ParamNum));
8393       }
8394     }
8395   // If the qualified name lookup yielded nothing, try typo correction
8396   } else if ((Correction = SemaRef.CorrectTypo(
8397                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8398                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8399                   IsLocalFriend ? nullptr : NewDC))) {
8400     // Set up everything for the call to ActOnFunctionDeclarator
8401     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8402                               ExtraArgs.D.getIdentifierLoc());
8403     Previous.clear();
8404     Previous.setLookupName(Correction.getCorrection());
8405     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8406                                     CDeclEnd = Correction.end();
8407          CDecl != CDeclEnd; ++CDecl) {
8408       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8409       if (FD && !FD->hasBody() &&
8410           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8411         Previous.addDecl(FD);
8412       }
8413     }
8414     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8415 
8416     NamedDecl *Result;
8417     // Retry building the function declaration with the new previous
8418     // declarations, and with errors suppressed.
8419     {
8420       // Trap errors.
8421       Sema::SFINAETrap Trap(SemaRef);
8422 
8423       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8424       // pieces need to verify the typo-corrected C++ declaration and hopefully
8425       // eliminate the need for the parameter pack ExtraArgs.
8426       Result = SemaRef.ActOnFunctionDeclarator(
8427           ExtraArgs.S, ExtraArgs.D,
8428           Correction.getCorrectionDecl()->getDeclContext(),
8429           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8430           ExtraArgs.AddToScope);
8431 
8432       if (Trap.hasErrorOccurred())
8433         Result = nullptr;
8434     }
8435 
8436     if (Result) {
8437       // Determine which correction we picked.
8438       Decl *Canonical = Result->getCanonicalDecl();
8439       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8440            I != E; ++I)
8441         if ((*I)->getCanonicalDecl() == Canonical)
8442           Correction.setCorrectionDecl(*I);
8443 
8444       // Let Sema know about the correction.
8445       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8446       SemaRef.diagnoseTypo(
8447           Correction,
8448           SemaRef.PDiag(IsLocalFriend
8449                           ? diag::err_no_matching_local_friend_suggest
8450                           : diag::err_member_decl_does_not_match_suggest)
8451             << Name << NewDC << IsDefinition);
8452       return Result;
8453     }
8454 
8455     // Pretend the typo correction never occurred
8456     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8457                               ExtraArgs.D.getIdentifierLoc());
8458     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8459     Previous.clear();
8460     Previous.setLookupName(Name);
8461   }
8462 
8463   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8464       << Name << NewDC << IsDefinition << NewFD->getLocation();
8465 
8466   bool NewFDisConst = false;
8467   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8468     NewFDisConst = NewMD->isConst();
8469 
8470   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8471        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8472        NearMatch != NearMatchEnd; ++NearMatch) {
8473     FunctionDecl *FD = NearMatch->first;
8474     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8475     bool FDisConst = MD && MD->isConst();
8476     bool IsMember = MD || !IsLocalFriend;
8477 
8478     // FIXME: These notes are poorly worded for the local friend case.
8479     if (unsigned Idx = NearMatch->second) {
8480       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8481       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8482       if (Loc.isInvalid()) Loc = FD->getLocation();
8483       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8484                                  : diag::note_local_decl_close_param_match)
8485         << Idx << FDParam->getType()
8486         << NewFD->getParamDecl(Idx - 1)->getType();
8487     } else if (FDisConst != NewFDisConst) {
8488       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8489           << NewFDisConst << FD->getSourceRange().getEnd();
8490     } else
8491       SemaRef.Diag(FD->getLocation(),
8492                    IsMember ? diag::note_member_def_close_match
8493                             : diag::note_local_decl_close_match);
8494   }
8495   return nullptr;
8496 }
8497 
8498 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8499   switch (D.getDeclSpec().getStorageClassSpec()) {
8500   default: llvm_unreachable("Unknown storage class!");
8501   case DeclSpec::SCS_auto:
8502   case DeclSpec::SCS_register:
8503   case DeclSpec::SCS_mutable:
8504     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8505                  diag::err_typecheck_sclass_func);
8506     D.getMutableDeclSpec().ClearStorageClassSpecs();
8507     D.setInvalidType();
8508     break;
8509   case DeclSpec::SCS_unspecified: break;
8510   case DeclSpec::SCS_extern:
8511     if (D.getDeclSpec().isExternInLinkageSpec())
8512       return SC_None;
8513     return SC_Extern;
8514   case DeclSpec::SCS_static: {
8515     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8516       // C99 6.7.1p5:
8517       //   The declaration of an identifier for a function that has
8518       //   block scope shall have no explicit storage-class specifier
8519       //   other than extern
8520       // See also (C++ [dcl.stc]p4).
8521       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8522                    diag::err_static_block_func);
8523       break;
8524     } else
8525       return SC_Static;
8526   }
8527   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8528   }
8529 
8530   // No explicit storage class has already been returned
8531   return SC_None;
8532 }
8533 
8534 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8535                                            DeclContext *DC, QualType &R,
8536                                            TypeSourceInfo *TInfo,
8537                                            StorageClass SC,
8538                                            bool &IsVirtualOkay) {
8539   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8540   DeclarationName Name = NameInfo.getName();
8541 
8542   FunctionDecl *NewFD = nullptr;
8543   bool isInline = D.getDeclSpec().isInlineSpecified();
8544 
8545   if (!SemaRef.getLangOpts().CPlusPlus) {
8546     // Determine whether the function was written with a
8547     // prototype. This true when:
8548     //   - there is a prototype in the declarator, or
8549     //   - the type R of the function is some kind of typedef or other non-
8550     //     attributed reference to a type name (which eventually refers to a
8551     //     function type).
8552     bool HasPrototype =
8553       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8554       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8555 
8556     NewFD = FunctionDecl::Create(
8557         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8558         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8559         ConstexprSpecKind::Unspecified,
8560         /*TrailingRequiresClause=*/nullptr);
8561     if (D.isInvalidType())
8562       NewFD->setInvalidDecl();
8563 
8564     return NewFD;
8565   }
8566 
8567   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8568 
8569   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8570   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8571     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8572                  diag::err_constexpr_wrong_decl_kind)
8573         << static_cast<int>(ConstexprKind);
8574     ConstexprKind = ConstexprSpecKind::Unspecified;
8575     D.getMutableDeclSpec().ClearConstexprSpec();
8576   }
8577   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8578 
8579   // Check that the return type is not an abstract class type.
8580   // For record types, this is done by the AbstractClassUsageDiagnoser once
8581   // the class has been completely parsed.
8582   if (!DC->isRecord() &&
8583       SemaRef.RequireNonAbstractType(
8584           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8585           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8586     D.setInvalidType();
8587 
8588   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8589     // This is a C++ constructor declaration.
8590     assert(DC->isRecord() &&
8591            "Constructors can only be declared in a member context");
8592 
8593     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8594     return CXXConstructorDecl::Create(
8595         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8596         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8597         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8598         InheritedConstructor(), TrailingRequiresClause);
8599 
8600   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8601     // This is a C++ destructor declaration.
8602     if (DC->isRecord()) {
8603       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8604       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8605       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8606           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8607           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8608           /*isImplicitlyDeclared=*/false, ConstexprKind,
8609           TrailingRequiresClause);
8610 
8611       // If the destructor needs an implicit exception specification, set it
8612       // now. FIXME: It'd be nice to be able to create the right type to start
8613       // with, but the type needs to reference the destructor declaration.
8614       if (SemaRef.getLangOpts().CPlusPlus11)
8615         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8616 
8617       IsVirtualOkay = true;
8618       return NewDD;
8619 
8620     } else {
8621       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8622       D.setInvalidType();
8623 
8624       // Create a FunctionDecl to satisfy the function definition parsing
8625       // code path.
8626       return FunctionDecl::Create(
8627           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8628           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8629           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8630     }
8631 
8632   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8633     if (!DC->isRecord()) {
8634       SemaRef.Diag(D.getIdentifierLoc(),
8635            diag::err_conv_function_not_member);
8636       return nullptr;
8637     }
8638 
8639     SemaRef.CheckConversionDeclarator(D, R, SC);
8640     if (D.isInvalidType())
8641       return nullptr;
8642 
8643     IsVirtualOkay = true;
8644     return CXXConversionDecl::Create(
8645         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8646         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8647         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8648         TrailingRequiresClause);
8649 
8650   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8651     if (TrailingRequiresClause)
8652       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8653                    diag::err_trailing_requires_clause_on_deduction_guide)
8654           << TrailingRequiresClause->getSourceRange();
8655     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8656 
8657     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8658                                          ExplicitSpecifier, NameInfo, R, TInfo,
8659                                          D.getEndLoc());
8660   } else if (DC->isRecord()) {
8661     // If the name of the function is the same as the name of the record,
8662     // then this must be an invalid constructor that has a return type.
8663     // (The parser checks for a return type and makes the declarator a
8664     // constructor if it has no return type).
8665     if (Name.getAsIdentifierInfo() &&
8666         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8667       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8668         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8669         << SourceRange(D.getIdentifierLoc());
8670       return nullptr;
8671     }
8672 
8673     // This is a C++ method declaration.
8674     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8675         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8676         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8677         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8678     IsVirtualOkay = !Ret->isStatic();
8679     return Ret;
8680   } else {
8681     bool isFriend =
8682         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8683     if (!isFriend && SemaRef.CurContext->isRecord())
8684       return nullptr;
8685 
8686     // Determine whether the function was written with a
8687     // prototype. This true when:
8688     //   - we're in C++ (where every function has a prototype),
8689     return FunctionDecl::Create(
8690         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8691         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8692         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8693   }
8694 }
8695 
8696 enum OpenCLParamType {
8697   ValidKernelParam,
8698   PtrPtrKernelParam,
8699   PtrKernelParam,
8700   InvalidAddrSpacePtrKernelParam,
8701   InvalidKernelParam,
8702   RecordKernelParam
8703 };
8704 
8705 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8706   // Size dependent types are just typedefs to normal integer types
8707   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8708   // integers other than by their names.
8709   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8710 
8711   // Remove typedefs one by one until we reach a typedef
8712   // for a size dependent type.
8713   QualType DesugaredTy = Ty;
8714   do {
8715     ArrayRef<StringRef> Names(SizeTypeNames);
8716     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8717     if (Names.end() != Match)
8718       return true;
8719 
8720     Ty = DesugaredTy;
8721     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8722   } while (DesugaredTy != Ty);
8723 
8724   return false;
8725 }
8726 
8727 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8728   if (PT->isDependentType())
8729     return InvalidKernelParam;
8730 
8731   if (PT->isPointerType() || PT->isReferenceType()) {
8732     QualType PointeeType = PT->getPointeeType();
8733     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8734         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8735         PointeeType.getAddressSpace() == LangAS::Default)
8736       return InvalidAddrSpacePtrKernelParam;
8737 
8738     if (PointeeType->isPointerType()) {
8739       // This is a pointer to pointer parameter.
8740       // Recursively check inner type.
8741       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8742       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8743           ParamKind == InvalidKernelParam)
8744         return ParamKind;
8745 
8746       return PtrPtrKernelParam;
8747     }
8748 
8749     // C++ for OpenCL v1.0 s2.4:
8750     // Moreover the types used in parameters of the kernel functions must be:
8751     // Standard layout types for pointer parameters. The same applies to
8752     // reference if an implementation supports them in kernel parameters.
8753     if (S.getLangOpts().OpenCLCPlusPlus &&
8754         !S.getOpenCLOptions().isAvailableOption(
8755             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8756         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8757         !PointeeType->isStandardLayoutType())
8758       return InvalidKernelParam;
8759 
8760     return PtrKernelParam;
8761   }
8762 
8763   // OpenCL v1.2 s6.9.k:
8764   // Arguments to kernel functions in a program cannot be declared with the
8765   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8766   // uintptr_t or a struct and/or union that contain fields declared to be one
8767   // of these built-in scalar types.
8768   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8769     return InvalidKernelParam;
8770 
8771   if (PT->isImageType())
8772     return PtrKernelParam;
8773 
8774   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8775     return InvalidKernelParam;
8776 
8777   // OpenCL extension spec v1.2 s9.5:
8778   // This extension adds support for half scalar and vector types as built-in
8779   // types that can be used for arithmetic operations, conversions etc.
8780   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8781       PT->isHalfType())
8782     return InvalidKernelParam;
8783 
8784   // Look into an array argument to check if it has a forbidden type.
8785   if (PT->isArrayType()) {
8786     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8787     // Call ourself to check an underlying type of an array. Since the
8788     // getPointeeOrArrayElementType returns an innermost type which is not an
8789     // array, this recursive call only happens once.
8790     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8791   }
8792 
8793   // C++ for OpenCL v1.0 s2.4:
8794   // Moreover the types used in parameters of the kernel functions must be:
8795   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8796   // types) for parameters passed by value;
8797   if (S.getLangOpts().OpenCLCPlusPlus &&
8798       !S.getOpenCLOptions().isAvailableOption(
8799           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8800       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8801     return InvalidKernelParam;
8802 
8803   if (PT->isRecordType())
8804     return RecordKernelParam;
8805 
8806   return ValidKernelParam;
8807 }
8808 
8809 static void checkIsValidOpenCLKernelParameter(
8810   Sema &S,
8811   Declarator &D,
8812   ParmVarDecl *Param,
8813   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8814   QualType PT = Param->getType();
8815 
8816   // Cache the valid types we encounter to avoid rechecking structs that are
8817   // used again
8818   if (ValidTypes.count(PT.getTypePtr()))
8819     return;
8820 
8821   switch (getOpenCLKernelParameterType(S, PT)) {
8822   case PtrPtrKernelParam:
8823     // OpenCL v3.0 s6.11.a:
8824     // A kernel function argument cannot be declared as a pointer to a pointer
8825     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8826     if (S.getLangOpts().OpenCLVersion <= 120 &&
8827         !S.getLangOpts().OpenCLCPlusPlus) {
8828       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8829       D.setInvalidType();
8830       return;
8831     }
8832 
8833     ValidTypes.insert(PT.getTypePtr());
8834     return;
8835 
8836   case InvalidAddrSpacePtrKernelParam:
8837     // OpenCL v1.0 s6.5:
8838     // __kernel function arguments declared to be a pointer of a type can point
8839     // to one of the following address spaces only : __global, __local or
8840     // __constant.
8841     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8842     D.setInvalidType();
8843     return;
8844 
8845     // OpenCL v1.2 s6.9.k:
8846     // Arguments to kernel functions in a program cannot be declared with the
8847     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8848     // uintptr_t or a struct and/or union that contain fields declared to be
8849     // one of these built-in scalar types.
8850 
8851   case InvalidKernelParam:
8852     // OpenCL v1.2 s6.8 n:
8853     // A kernel function argument cannot be declared
8854     // of event_t type.
8855     // Do not diagnose half type since it is diagnosed as invalid argument
8856     // type for any function elsewhere.
8857     if (!PT->isHalfType()) {
8858       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8859 
8860       // Explain what typedefs are involved.
8861       const TypedefType *Typedef = nullptr;
8862       while ((Typedef = PT->getAs<TypedefType>())) {
8863         SourceLocation Loc = Typedef->getDecl()->getLocation();
8864         // SourceLocation may be invalid for a built-in type.
8865         if (Loc.isValid())
8866           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8867         PT = Typedef->desugar();
8868       }
8869     }
8870 
8871     D.setInvalidType();
8872     return;
8873 
8874   case PtrKernelParam:
8875   case ValidKernelParam:
8876     ValidTypes.insert(PT.getTypePtr());
8877     return;
8878 
8879   case RecordKernelParam:
8880     break;
8881   }
8882 
8883   // Track nested structs we will inspect
8884   SmallVector<const Decl *, 4> VisitStack;
8885 
8886   // Track where we are in the nested structs. Items will migrate from
8887   // VisitStack to HistoryStack as we do the DFS for bad field.
8888   SmallVector<const FieldDecl *, 4> HistoryStack;
8889   HistoryStack.push_back(nullptr);
8890 
8891   // At this point we already handled everything except of a RecordType or
8892   // an ArrayType of a RecordType.
8893   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8894   const RecordType *RecTy =
8895       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8896   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8897 
8898   VisitStack.push_back(RecTy->getDecl());
8899   assert(VisitStack.back() && "First decl null?");
8900 
8901   do {
8902     const Decl *Next = VisitStack.pop_back_val();
8903     if (!Next) {
8904       assert(!HistoryStack.empty());
8905       // Found a marker, we have gone up a level
8906       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8907         ValidTypes.insert(Hist->getType().getTypePtr());
8908 
8909       continue;
8910     }
8911 
8912     // Adds everything except the original parameter declaration (which is not a
8913     // field itself) to the history stack.
8914     const RecordDecl *RD;
8915     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8916       HistoryStack.push_back(Field);
8917 
8918       QualType FieldTy = Field->getType();
8919       // Other field types (known to be valid or invalid) are handled while we
8920       // walk around RecordDecl::fields().
8921       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8922              "Unexpected type.");
8923       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8924 
8925       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8926     } else {
8927       RD = cast<RecordDecl>(Next);
8928     }
8929 
8930     // Add a null marker so we know when we've gone back up a level
8931     VisitStack.push_back(nullptr);
8932 
8933     for (const auto *FD : RD->fields()) {
8934       QualType QT = FD->getType();
8935 
8936       if (ValidTypes.count(QT.getTypePtr()))
8937         continue;
8938 
8939       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8940       if (ParamType == ValidKernelParam)
8941         continue;
8942 
8943       if (ParamType == RecordKernelParam) {
8944         VisitStack.push_back(FD);
8945         continue;
8946       }
8947 
8948       // OpenCL v1.2 s6.9.p:
8949       // Arguments to kernel functions that are declared to be a struct or union
8950       // do not allow OpenCL objects to be passed as elements of the struct or
8951       // union.
8952       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8953           ParamType == InvalidAddrSpacePtrKernelParam) {
8954         S.Diag(Param->getLocation(),
8955                diag::err_record_with_pointers_kernel_param)
8956           << PT->isUnionType()
8957           << PT;
8958       } else {
8959         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8960       }
8961 
8962       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8963           << OrigRecDecl->getDeclName();
8964 
8965       // We have an error, now let's go back up through history and show where
8966       // the offending field came from
8967       for (ArrayRef<const FieldDecl *>::const_iterator
8968                I = HistoryStack.begin() + 1,
8969                E = HistoryStack.end();
8970            I != E; ++I) {
8971         const FieldDecl *OuterField = *I;
8972         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8973           << OuterField->getType();
8974       }
8975 
8976       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8977         << QT->isPointerType()
8978         << QT;
8979       D.setInvalidType();
8980       return;
8981     }
8982   } while (!VisitStack.empty());
8983 }
8984 
8985 /// Find the DeclContext in which a tag is implicitly declared if we see an
8986 /// elaborated type specifier in the specified context, and lookup finds
8987 /// nothing.
8988 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8989   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8990     DC = DC->getParent();
8991   return DC;
8992 }
8993 
8994 /// Find the Scope in which a tag is implicitly declared if we see an
8995 /// elaborated type specifier in the specified context, and lookup finds
8996 /// nothing.
8997 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8998   while (S->isClassScope() ||
8999          (LangOpts.CPlusPlus &&
9000           S->isFunctionPrototypeScope()) ||
9001          ((S->getFlags() & Scope::DeclScope) == 0) ||
9002          (S->getEntity() && S->getEntity()->isTransparentContext()))
9003     S = S->getParent();
9004   return S;
9005 }
9006 
9007 NamedDecl*
9008 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9009                               TypeSourceInfo *TInfo, LookupResult &Previous,
9010                               MultiTemplateParamsArg TemplateParamListsRef,
9011                               bool &AddToScope) {
9012   QualType R = TInfo->getType();
9013 
9014   assert(R->isFunctionType());
9015   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9016     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9017 
9018   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9019   for (TemplateParameterList *TPL : TemplateParamListsRef)
9020     TemplateParamLists.push_back(TPL);
9021   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9022     if (!TemplateParamLists.empty() &&
9023         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9024       TemplateParamLists.back() = Invented;
9025     else
9026       TemplateParamLists.push_back(Invented);
9027   }
9028 
9029   // TODO: consider using NameInfo for diagnostic.
9030   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9031   DeclarationName Name = NameInfo.getName();
9032   StorageClass SC = getFunctionStorageClass(*this, D);
9033 
9034   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9035     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9036          diag::err_invalid_thread)
9037       << DeclSpec::getSpecifierName(TSCS);
9038 
9039   if (D.isFirstDeclarationOfMember())
9040     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9041                            D.getIdentifierLoc());
9042 
9043   bool isFriend = false;
9044   FunctionTemplateDecl *FunctionTemplate = nullptr;
9045   bool isMemberSpecialization = false;
9046   bool isFunctionTemplateSpecialization = false;
9047 
9048   bool isDependentClassScopeExplicitSpecialization = false;
9049   bool HasExplicitTemplateArgs = false;
9050   TemplateArgumentListInfo TemplateArgs;
9051 
9052   bool isVirtualOkay = false;
9053 
9054   DeclContext *OriginalDC = DC;
9055   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9056 
9057   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9058                                               isVirtualOkay);
9059   if (!NewFD) return nullptr;
9060 
9061   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9062     NewFD->setTopLevelDeclInObjCContainer();
9063 
9064   // Set the lexical context. If this is a function-scope declaration, or has a
9065   // C++ scope specifier, or is the object of a friend declaration, the lexical
9066   // context will be different from the semantic context.
9067   NewFD->setLexicalDeclContext(CurContext);
9068 
9069   if (IsLocalExternDecl)
9070     NewFD->setLocalExternDecl();
9071 
9072   if (getLangOpts().CPlusPlus) {
9073     bool isInline = D.getDeclSpec().isInlineSpecified();
9074     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9075     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9076     isFriend = D.getDeclSpec().isFriendSpecified();
9077     if (isFriend && !isInline && D.isFunctionDefinition()) {
9078       // C++ [class.friend]p5
9079       //   A function can be defined in a friend declaration of a
9080       //   class . . . . Such a function is implicitly inline.
9081       NewFD->setImplicitlyInline();
9082     }
9083 
9084     // If this is a method defined in an __interface, and is not a constructor
9085     // or an overloaded operator, then set the pure flag (isVirtual will already
9086     // return true).
9087     if (const CXXRecordDecl *Parent =
9088           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9089       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9090         NewFD->setPure(true);
9091 
9092       // C++ [class.union]p2
9093       //   A union can have member functions, but not virtual functions.
9094       if (isVirtual && Parent->isUnion())
9095         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9096     }
9097 
9098     SetNestedNameSpecifier(*this, NewFD, D);
9099     isMemberSpecialization = false;
9100     isFunctionTemplateSpecialization = false;
9101     if (D.isInvalidType())
9102       NewFD->setInvalidDecl();
9103 
9104     // Match up the template parameter lists with the scope specifier, then
9105     // determine whether we have a template or a template specialization.
9106     bool Invalid = false;
9107     TemplateParameterList *TemplateParams =
9108         MatchTemplateParametersToScopeSpecifier(
9109             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9110             D.getCXXScopeSpec(),
9111             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9112                 ? D.getName().TemplateId
9113                 : nullptr,
9114             TemplateParamLists, isFriend, isMemberSpecialization,
9115             Invalid);
9116     if (TemplateParams) {
9117       // Check that we can declare a template here.
9118       if (CheckTemplateDeclScope(S, TemplateParams))
9119         NewFD->setInvalidDecl();
9120 
9121       if (TemplateParams->size() > 0) {
9122         // This is a function template
9123 
9124         // A destructor cannot be a template.
9125         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9126           Diag(NewFD->getLocation(), diag::err_destructor_template);
9127           NewFD->setInvalidDecl();
9128         }
9129 
9130         // If we're adding a template to a dependent context, we may need to
9131         // rebuilding some of the types used within the template parameter list,
9132         // now that we know what the current instantiation is.
9133         if (DC->isDependentContext()) {
9134           ContextRAII SavedContext(*this, DC);
9135           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9136             Invalid = true;
9137         }
9138 
9139         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9140                                                         NewFD->getLocation(),
9141                                                         Name, TemplateParams,
9142                                                         NewFD);
9143         FunctionTemplate->setLexicalDeclContext(CurContext);
9144         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9145 
9146         // For source fidelity, store the other template param lists.
9147         if (TemplateParamLists.size() > 1) {
9148           NewFD->setTemplateParameterListsInfo(Context,
9149               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9150                   .drop_back(1));
9151         }
9152       } else {
9153         // This is a function template specialization.
9154         isFunctionTemplateSpecialization = true;
9155         // For source fidelity, store all the template param lists.
9156         if (TemplateParamLists.size() > 0)
9157           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9158 
9159         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9160         if (isFriend) {
9161           // We want to remove the "template<>", found here.
9162           SourceRange RemoveRange = TemplateParams->getSourceRange();
9163 
9164           // If we remove the template<> and the name is not a
9165           // template-id, we're actually silently creating a problem:
9166           // the friend declaration will refer to an untemplated decl,
9167           // and clearly the user wants a template specialization.  So
9168           // we need to insert '<>' after the name.
9169           SourceLocation InsertLoc;
9170           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9171             InsertLoc = D.getName().getSourceRange().getEnd();
9172             InsertLoc = getLocForEndOfToken(InsertLoc);
9173           }
9174 
9175           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9176             << Name << RemoveRange
9177             << FixItHint::CreateRemoval(RemoveRange)
9178             << FixItHint::CreateInsertion(InsertLoc, "<>");
9179         }
9180       }
9181     } else {
9182       // Check that we can declare a template here.
9183       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9184           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9185         NewFD->setInvalidDecl();
9186 
9187       // All template param lists were matched against the scope specifier:
9188       // this is NOT (an explicit specialization of) a template.
9189       if (TemplateParamLists.size() > 0)
9190         // For source fidelity, store all the template param lists.
9191         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9192     }
9193 
9194     if (Invalid) {
9195       NewFD->setInvalidDecl();
9196       if (FunctionTemplate)
9197         FunctionTemplate->setInvalidDecl();
9198     }
9199 
9200     // C++ [dcl.fct.spec]p5:
9201     //   The virtual specifier shall only be used in declarations of
9202     //   nonstatic class member functions that appear within a
9203     //   member-specification of a class declaration; see 10.3.
9204     //
9205     if (isVirtual && !NewFD->isInvalidDecl()) {
9206       if (!isVirtualOkay) {
9207         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9208              diag::err_virtual_non_function);
9209       } else if (!CurContext->isRecord()) {
9210         // 'virtual' was specified outside of the class.
9211         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9212              diag::err_virtual_out_of_class)
9213           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9214       } else if (NewFD->getDescribedFunctionTemplate()) {
9215         // C++ [temp.mem]p3:
9216         //  A member function template shall not be virtual.
9217         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9218              diag::err_virtual_member_function_template)
9219           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9220       } else {
9221         // Okay: Add virtual to the method.
9222         NewFD->setVirtualAsWritten(true);
9223       }
9224 
9225       if (getLangOpts().CPlusPlus14 &&
9226           NewFD->getReturnType()->isUndeducedType())
9227         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9228     }
9229 
9230     if (getLangOpts().CPlusPlus14 &&
9231         (NewFD->isDependentContext() ||
9232          (isFriend && CurContext->isDependentContext())) &&
9233         NewFD->getReturnType()->isUndeducedType()) {
9234       // If the function template is referenced directly (for instance, as a
9235       // member of the current instantiation), pretend it has a dependent type.
9236       // This is not really justified by the standard, but is the only sane
9237       // thing to do.
9238       // FIXME: For a friend function, we have not marked the function as being
9239       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9240       const FunctionProtoType *FPT =
9241           NewFD->getType()->castAs<FunctionProtoType>();
9242       QualType Result =
9243           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9244       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9245                                              FPT->getExtProtoInfo()));
9246     }
9247 
9248     // C++ [dcl.fct.spec]p3:
9249     //  The inline specifier shall not appear on a block scope function
9250     //  declaration.
9251     if (isInline && !NewFD->isInvalidDecl()) {
9252       if (CurContext->isFunctionOrMethod()) {
9253         // 'inline' is not allowed on block scope function declaration.
9254         Diag(D.getDeclSpec().getInlineSpecLoc(),
9255              diag::err_inline_declaration_block_scope) << Name
9256           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9257       }
9258     }
9259 
9260     // C++ [dcl.fct.spec]p6:
9261     //  The explicit specifier shall be used only in the declaration of a
9262     //  constructor or conversion function within its class definition;
9263     //  see 12.3.1 and 12.3.2.
9264     if (hasExplicit && !NewFD->isInvalidDecl() &&
9265         !isa<CXXDeductionGuideDecl>(NewFD)) {
9266       if (!CurContext->isRecord()) {
9267         // 'explicit' was specified outside of the class.
9268         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9269              diag::err_explicit_out_of_class)
9270             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9271       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9272                  !isa<CXXConversionDecl>(NewFD)) {
9273         // 'explicit' was specified on a function that wasn't a constructor
9274         // or conversion function.
9275         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9276              diag::err_explicit_non_ctor_or_conv_function)
9277             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9278       }
9279     }
9280 
9281     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9282     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9283       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9284       // are implicitly inline.
9285       NewFD->setImplicitlyInline();
9286 
9287       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9288       // be either constructors or to return a literal type. Therefore,
9289       // destructors cannot be declared constexpr.
9290       if (isa<CXXDestructorDecl>(NewFD) &&
9291           (!getLangOpts().CPlusPlus20 ||
9292            ConstexprKind == ConstexprSpecKind::Consteval)) {
9293         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9294             << static_cast<int>(ConstexprKind);
9295         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9296                                     ? ConstexprSpecKind::Unspecified
9297                                     : ConstexprSpecKind::Constexpr);
9298       }
9299       // C++20 [dcl.constexpr]p2: An allocation function, or a
9300       // deallocation function shall not be declared with the consteval
9301       // specifier.
9302       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9303           (NewFD->getOverloadedOperator() == OO_New ||
9304            NewFD->getOverloadedOperator() == OO_Array_New ||
9305            NewFD->getOverloadedOperator() == OO_Delete ||
9306            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9307         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9308              diag::err_invalid_consteval_decl_kind)
9309             << NewFD;
9310         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9311       }
9312     }
9313 
9314     // If __module_private__ was specified, mark the function accordingly.
9315     if (D.getDeclSpec().isModulePrivateSpecified()) {
9316       if (isFunctionTemplateSpecialization) {
9317         SourceLocation ModulePrivateLoc
9318           = D.getDeclSpec().getModulePrivateSpecLoc();
9319         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9320           << 0
9321           << FixItHint::CreateRemoval(ModulePrivateLoc);
9322       } else {
9323         NewFD->setModulePrivate();
9324         if (FunctionTemplate)
9325           FunctionTemplate->setModulePrivate();
9326       }
9327     }
9328 
9329     if (isFriend) {
9330       if (FunctionTemplate) {
9331         FunctionTemplate->setObjectOfFriendDecl();
9332         FunctionTemplate->setAccess(AS_public);
9333       }
9334       NewFD->setObjectOfFriendDecl();
9335       NewFD->setAccess(AS_public);
9336     }
9337 
9338     // If a function is defined as defaulted or deleted, mark it as such now.
9339     // We'll do the relevant checks on defaulted / deleted functions later.
9340     switch (D.getFunctionDefinitionKind()) {
9341     case FunctionDefinitionKind::Declaration:
9342     case FunctionDefinitionKind::Definition:
9343       break;
9344 
9345     case FunctionDefinitionKind::Defaulted:
9346       NewFD->setDefaulted();
9347       break;
9348 
9349     case FunctionDefinitionKind::Deleted:
9350       NewFD->setDeletedAsWritten();
9351       break;
9352     }
9353 
9354     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9355         D.isFunctionDefinition()) {
9356       // C++ [class.mfct]p2:
9357       //   A member function may be defined (8.4) in its class definition, in
9358       //   which case it is an inline member function (7.1.2)
9359       NewFD->setImplicitlyInline();
9360     }
9361 
9362     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9363         !CurContext->isRecord()) {
9364       // C++ [class.static]p1:
9365       //   A data or function member of a class may be declared static
9366       //   in a class definition, in which case it is a static member of
9367       //   the class.
9368 
9369       // Complain about the 'static' specifier if it's on an out-of-line
9370       // member function definition.
9371 
9372       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9373       // member function template declaration and class member template
9374       // declaration (MSVC versions before 2015), warn about this.
9375       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9376            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9377              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9378            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9379            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9380         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9381     }
9382 
9383     // C++11 [except.spec]p15:
9384     //   A deallocation function with no exception-specification is treated
9385     //   as if it were specified with noexcept(true).
9386     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9387     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9388          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9389         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9390       NewFD->setType(Context.getFunctionType(
9391           FPT->getReturnType(), FPT->getParamTypes(),
9392           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9393   }
9394 
9395   // Filter out previous declarations that don't match the scope.
9396   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9397                        D.getCXXScopeSpec().isNotEmpty() ||
9398                        isMemberSpecialization ||
9399                        isFunctionTemplateSpecialization);
9400 
9401   // Handle GNU asm-label extension (encoded as an attribute).
9402   if (Expr *E = (Expr*) D.getAsmLabel()) {
9403     // The parser guarantees this is a string.
9404     StringLiteral *SE = cast<StringLiteral>(E);
9405     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9406                                         /*IsLiteralLabel=*/true,
9407                                         SE->getStrTokenLoc(0)));
9408   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9409     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9410       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9411     if (I != ExtnameUndeclaredIdentifiers.end()) {
9412       if (isDeclExternC(NewFD)) {
9413         NewFD->addAttr(I->second);
9414         ExtnameUndeclaredIdentifiers.erase(I);
9415       } else
9416         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9417             << /*Variable*/0 << NewFD;
9418     }
9419   }
9420 
9421   // Copy the parameter declarations from the declarator D to the function
9422   // declaration NewFD, if they are available.  First scavenge them into Params.
9423   SmallVector<ParmVarDecl*, 16> Params;
9424   unsigned FTIIdx;
9425   if (D.isFunctionDeclarator(FTIIdx)) {
9426     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9427 
9428     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9429     // function that takes no arguments, not a function that takes a
9430     // single void argument.
9431     // We let through "const void" here because Sema::GetTypeForDeclarator
9432     // already checks for that case.
9433     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9434       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9435         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9436         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9437         Param->setDeclContext(NewFD);
9438         Params.push_back(Param);
9439 
9440         if (Param->isInvalidDecl())
9441           NewFD->setInvalidDecl();
9442       }
9443     }
9444 
9445     if (!getLangOpts().CPlusPlus) {
9446       // In C, find all the tag declarations from the prototype and move them
9447       // into the function DeclContext. Remove them from the surrounding tag
9448       // injection context of the function, which is typically but not always
9449       // the TU.
9450       DeclContext *PrototypeTagContext =
9451           getTagInjectionContext(NewFD->getLexicalDeclContext());
9452       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9453         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9454 
9455         // We don't want to reparent enumerators. Look at their parent enum
9456         // instead.
9457         if (!TD) {
9458           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9459             TD = cast<EnumDecl>(ECD->getDeclContext());
9460         }
9461         if (!TD)
9462           continue;
9463         DeclContext *TagDC = TD->getLexicalDeclContext();
9464         if (!TagDC->containsDecl(TD))
9465           continue;
9466         TagDC->removeDecl(TD);
9467         TD->setDeclContext(NewFD);
9468         NewFD->addDecl(TD);
9469 
9470         // Preserve the lexical DeclContext if it is not the surrounding tag
9471         // injection context of the FD. In this example, the semantic context of
9472         // E will be f and the lexical context will be S, while both the
9473         // semantic and lexical contexts of S will be f:
9474         //   void f(struct S { enum E { a } f; } s);
9475         if (TagDC != PrototypeTagContext)
9476           TD->setLexicalDeclContext(TagDC);
9477       }
9478     }
9479   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9480     // When we're declaring a function with a typedef, typeof, etc as in the
9481     // following example, we'll need to synthesize (unnamed)
9482     // parameters for use in the declaration.
9483     //
9484     // @code
9485     // typedef void fn(int);
9486     // fn f;
9487     // @endcode
9488 
9489     // Synthesize a parameter for each argument type.
9490     for (const auto &AI : FT->param_types()) {
9491       ParmVarDecl *Param =
9492           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9493       Param->setScopeInfo(0, Params.size());
9494       Params.push_back(Param);
9495     }
9496   } else {
9497     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9498            "Should not need args for typedef of non-prototype fn");
9499   }
9500 
9501   // Finally, we know we have the right number of parameters, install them.
9502   NewFD->setParams(Params);
9503 
9504   if (D.getDeclSpec().isNoreturnSpecified())
9505     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9506                                            D.getDeclSpec().getNoreturnSpecLoc(),
9507                                            AttributeCommonInfo::AS_Keyword));
9508 
9509   // Functions returning a variably modified type violate C99 6.7.5.2p2
9510   // because all functions have linkage.
9511   if (!NewFD->isInvalidDecl() &&
9512       NewFD->getReturnType()->isVariablyModifiedType()) {
9513     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9514     NewFD->setInvalidDecl();
9515   }
9516 
9517   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9518   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9519       !NewFD->hasAttr<SectionAttr>())
9520     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9521         Context, PragmaClangTextSection.SectionName,
9522         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9523 
9524   // Apply an implicit SectionAttr if #pragma code_seg is active.
9525   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9526       !NewFD->hasAttr<SectionAttr>()) {
9527     NewFD->addAttr(SectionAttr::CreateImplicit(
9528         Context, CodeSegStack.CurrentValue->getString(),
9529         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9530         SectionAttr::Declspec_allocate));
9531     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9532                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9533                          ASTContext::PSF_Read,
9534                      NewFD))
9535       NewFD->dropAttr<SectionAttr>();
9536   }
9537 
9538   // Apply an implicit CodeSegAttr from class declspec or
9539   // apply an implicit SectionAttr from #pragma code_seg if active.
9540   if (!NewFD->hasAttr<CodeSegAttr>()) {
9541     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9542                                                                  D.isFunctionDefinition())) {
9543       NewFD->addAttr(SAttr);
9544     }
9545   }
9546 
9547   // Handle attributes.
9548   ProcessDeclAttributes(S, NewFD, D);
9549 
9550   if (getLangOpts().OpenCL) {
9551     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9552     // type declaration will generate a compilation error.
9553     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9554     if (AddressSpace != LangAS::Default) {
9555       Diag(NewFD->getLocation(),
9556            diag::err_opencl_return_value_with_address_space);
9557       NewFD->setInvalidDecl();
9558     }
9559   }
9560 
9561   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9562     checkDeviceDecl(NewFD, D.getBeginLoc());
9563 
9564   if (!getLangOpts().CPlusPlus) {
9565     // Perform semantic checking on the function declaration.
9566     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9567       CheckMain(NewFD, D.getDeclSpec());
9568 
9569     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9570       CheckMSVCRTEntryPoint(NewFD);
9571 
9572     if (!NewFD->isInvalidDecl())
9573       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9574                                                   isMemberSpecialization));
9575     else if (!Previous.empty())
9576       // Recover gracefully from an invalid redeclaration.
9577       D.setRedeclaration(true);
9578     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9579             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9580            "previous declaration set still overloaded");
9581 
9582     // Diagnose no-prototype function declarations with calling conventions that
9583     // don't support variadic calls. Only do this in C and do it after merging
9584     // possibly prototyped redeclarations.
9585     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9586     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9587       CallingConv CC = FT->getExtInfo().getCC();
9588       if (!supportsVariadicCall(CC)) {
9589         // Windows system headers sometimes accidentally use stdcall without
9590         // (void) parameters, so we relax this to a warning.
9591         int DiagID =
9592             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9593         Diag(NewFD->getLocation(), DiagID)
9594             << FunctionType::getNameForCallConv(CC);
9595       }
9596     }
9597 
9598    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9599        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9600      checkNonTrivialCUnion(NewFD->getReturnType(),
9601                            NewFD->getReturnTypeSourceRange().getBegin(),
9602                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9603   } else {
9604     // C++11 [replacement.functions]p3:
9605     //  The program's definitions shall not be specified as inline.
9606     //
9607     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9608     //
9609     // Suppress the diagnostic if the function is __attribute__((used)), since
9610     // that forces an external definition to be emitted.
9611     if (D.getDeclSpec().isInlineSpecified() &&
9612         NewFD->isReplaceableGlobalAllocationFunction() &&
9613         !NewFD->hasAttr<UsedAttr>())
9614       Diag(D.getDeclSpec().getInlineSpecLoc(),
9615            diag::ext_operator_new_delete_declared_inline)
9616         << NewFD->getDeclName();
9617 
9618     // If the declarator is a template-id, translate the parser's template
9619     // argument list into our AST format.
9620     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9621       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9622       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9623       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9624       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9625                                          TemplateId->NumArgs);
9626       translateTemplateArguments(TemplateArgsPtr,
9627                                  TemplateArgs);
9628 
9629       HasExplicitTemplateArgs = true;
9630 
9631       if (NewFD->isInvalidDecl()) {
9632         HasExplicitTemplateArgs = false;
9633       } else if (FunctionTemplate) {
9634         // Function template with explicit template arguments.
9635         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9636           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9637 
9638         HasExplicitTemplateArgs = false;
9639       } else {
9640         assert((isFunctionTemplateSpecialization ||
9641                 D.getDeclSpec().isFriendSpecified()) &&
9642                "should have a 'template<>' for this decl");
9643         // "friend void foo<>(int);" is an implicit specialization decl.
9644         isFunctionTemplateSpecialization = true;
9645       }
9646     } else if (isFriend && isFunctionTemplateSpecialization) {
9647       // This combination is only possible in a recovery case;  the user
9648       // wrote something like:
9649       //   template <> friend void foo(int);
9650       // which we're recovering from as if the user had written:
9651       //   friend void foo<>(int);
9652       // Go ahead and fake up a template id.
9653       HasExplicitTemplateArgs = true;
9654       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9655       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9656     }
9657 
9658     // We do not add HD attributes to specializations here because
9659     // they may have different constexpr-ness compared to their
9660     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9661     // may end up with different effective targets. Instead, a
9662     // specialization inherits its target attributes from its template
9663     // in the CheckFunctionTemplateSpecialization() call below.
9664     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9665       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9666 
9667     // If it's a friend (and only if it's a friend), it's possible
9668     // that either the specialized function type or the specialized
9669     // template is dependent, and therefore matching will fail.  In
9670     // this case, don't check the specialization yet.
9671     if (isFunctionTemplateSpecialization && isFriend &&
9672         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9673          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9674              TemplateArgs.arguments()))) {
9675       assert(HasExplicitTemplateArgs &&
9676              "friend function specialization without template args");
9677       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9678                                                        Previous))
9679         NewFD->setInvalidDecl();
9680     } else if (isFunctionTemplateSpecialization) {
9681       if (CurContext->isDependentContext() && CurContext->isRecord()
9682           && !isFriend) {
9683         isDependentClassScopeExplicitSpecialization = true;
9684       } else if (!NewFD->isInvalidDecl() &&
9685                  CheckFunctionTemplateSpecialization(
9686                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9687                      Previous))
9688         NewFD->setInvalidDecl();
9689 
9690       // C++ [dcl.stc]p1:
9691       //   A storage-class-specifier shall not be specified in an explicit
9692       //   specialization (14.7.3)
9693       FunctionTemplateSpecializationInfo *Info =
9694           NewFD->getTemplateSpecializationInfo();
9695       if (Info && SC != SC_None) {
9696         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9697           Diag(NewFD->getLocation(),
9698                diag::err_explicit_specialization_inconsistent_storage_class)
9699             << SC
9700             << FixItHint::CreateRemoval(
9701                                       D.getDeclSpec().getStorageClassSpecLoc());
9702 
9703         else
9704           Diag(NewFD->getLocation(),
9705                diag::ext_explicit_specialization_storage_class)
9706             << FixItHint::CreateRemoval(
9707                                       D.getDeclSpec().getStorageClassSpecLoc());
9708       }
9709     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9710       if (CheckMemberSpecialization(NewFD, Previous))
9711           NewFD->setInvalidDecl();
9712     }
9713 
9714     // Perform semantic checking on the function declaration.
9715     if (!isDependentClassScopeExplicitSpecialization) {
9716       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9717         CheckMain(NewFD, D.getDeclSpec());
9718 
9719       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9720         CheckMSVCRTEntryPoint(NewFD);
9721 
9722       if (!NewFD->isInvalidDecl())
9723         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9724                                                     isMemberSpecialization));
9725       else if (!Previous.empty())
9726         // Recover gracefully from an invalid redeclaration.
9727         D.setRedeclaration(true);
9728     }
9729 
9730     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9731             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9732            "previous declaration set still overloaded");
9733 
9734     NamedDecl *PrincipalDecl = (FunctionTemplate
9735                                 ? cast<NamedDecl>(FunctionTemplate)
9736                                 : NewFD);
9737 
9738     if (isFriend && NewFD->getPreviousDecl()) {
9739       AccessSpecifier Access = AS_public;
9740       if (!NewFD->isInvalidDecl())
9741         Access = NewFD->getPreviousDecl()->getAccess();
9742 
9743       NewFD->setAccess(Access);
9744       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9745     }
9746 
9747     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9748         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9749       PrincipalDecl->setNonMemberOperator();
9750 
9751     // If we have a function template, check the template parameter
9752     // list. This will check and merge default template arguments.
9753     if (FunctionTemplate) {
9754       FunctionTemplateDecl *PrevTemplate =
9755                                      FunctionTemplate->getPreviousDecl();
9756       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9757                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9758                                     : nullptr,
9759                             D.getDeclSpec().isFriendSpecified()
9760                               ? (D.isFunctionDefinition()
9761                                    ? TPC_FriendFunctionTemplateDefinition
9762                                    : TPC_FriendFunctionTemplate)
9763                               : (D.getCXXScopeSpec().isSet() &&
9764                                  DC && DC->isRecord() &&
9765                                  DC->isDependentContext())
9766                                   ? TPC_ClassTemplateMember
9767                                   : TPC_FunctionTemplate);
9768     }
9769 
9770     if (NewFD->isInvalidDecl()) {
9771       // Ignore all the rest of this.
9772     } else if (!D.isRedeclaration()) {
9773       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9774                                        AddToScope };
9775       // Fake up an access specifier if it's supposed to be a class member.
9776       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9777         NewFD->setAccess(AS_public);
9778 
9779       // Qualified decls generally require a previous declaration.
9780       if (D.getCXXScopeSpec().isSet()) {
9781         // ...with the major exception of templated-scope or
9782         // dependent-scope friend declarations.
9783 
9784         // TODO: we currently also suppress this check in dependent
9785         // contexts because (1) the parameter depth will be off when
9786         // matching friend templates and (2) we might actually be
9787         // selecting a friend based on a dependent factor.  But there
9788         // are situations where these conditions don't apply and we
9789         // can actually do this check immediately.
9790         //
9791         // Unless the scope is dependent, it's always an error if qualified
9792         // redeclaration lookup found nothing at all. Diagnose that now;
9793         // nothing will diagnose that error later.
9794         if (isFriend &&
9795             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9796              (!Previous.empty() && CurContext->isDependentContext()))) {
9797           // ignore these
9798         } else if (NewFD->isCPUDispatchMultiVersion() ||
9799                    NewFD->isCPUSpecificMultiVersion()) {
9800           // ignore this, we allow the redeclaration behavior here to create new
9801           // versions of the function.
9802         } else {
9803           // The user tried to provide an out-of-line definition for a
9804           // function that is a member of a class or namespace, but there
9805           // was no such member function declared (C++ [class.mfct]p2,
9806           // C++ [namespace.memdef]p2). For example:
9807           //
9808           // class X {
9809           //   void f() const;
9810           // };
9811           //
9812           // void X::f() { } // ill-formed
9813           //
9814           // Complain about this problem, and attempt to suggest close
9815           // matches (e.g., those that differ only in cv-qualifiers and
9816           // whether the parameter types are references).
9817 
9818           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9819                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9820             AddToScope = ExtraArgs.AddToScope;
9821             return Result;
9822           }
9823         }
9824 
9825         // Unqualified local friend declarations are required to resolve
9826         // to something.
9827       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9828         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9829                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9830           AddToScope = ExtraArgs.AddToScope;
9831           return Result;
9832         }
9833       }
9834     } else if (!D.isFunctionDefinition() &&
9835                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9836                !isFriend && !isFunctionTemplateSpecialization &&
9837                !isMemberSpecialization) {
9838       // An out-of-line member function declaration must also be a
9839       // definition (C++ [class.mfct]p2).
9840       // Note that this is not the case for explicit specializations of
9841       // function templates or member functions of class templates, per
9842       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9843       // extension for compatibility with old SWIG code which likes to
9844       // generate them.
9845       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9846         << D.getCXXScopeSpec().getRange();
9847     }
9848   }
9849 
9850   // If this is the first declaration of a library builtin function, add
9851   // attributes as appropriate.
9852   if (!D.isRedeclaration() &&
9853       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9854     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9855       if (unsigned BuiltinID = II->getBuiltinID()) {
9856         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9857           // Validate the type matches unless this builtin is specified as
9858           // matching regardless of its declared type.
9859           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9860             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9861           } else {
9862             ASTContext::GetBuiltinTypeError Error;
9863             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9864             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9865 
9866             if (!Error && !BuiltinType.isNull() &&
9867                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9868                     NewFD->getType(), BuiltinType))
9869               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9870           }
9871         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9872                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9873           // FIXME: We should consider this a builtin only in the std namespace.
9874           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9875         }
9876       }
9877     }
9878   }
9879 
9880   ProcessPragmaWeak(S, NewFD);
9881   checkAttributesAfterMerging(*this, *NewFD);
9882 
9883   AddKnownFunctionAttributes(NewFD);
9884 
9885   if (NewFD->hasAttr<OverloadableAttr>() &&
9886       !NewFD->getType()->getAs<FunctionProtoType>()) {
9887     Diag(NewFD->getLocation(),
9888          diag::err_attribute_overloadable_no_prototype)
9889       << NewFD;
9890 
9891     // Turn this into a variadic function with no parameters.
9892     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9893     FunctionProtoType::ExtProtoInfo EPI(
9894         Context.getDefaultCallingConvention(true, false));
9895     EPI.Variadic = true;
9896     EPI.ExtInfo = FT->getExtInfo();
9897 
9898     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9899     NewFD->setType(R);
9900   }
9901 
9902   // If there's a #pragma GCC visibility in scope, and this isn't a class
9903   // member, set the visibility of this function.
9904   if (!DC->isRecord() && NewFD->isExternallyVisible())
9905     AddPushedVisibilityAttribute(NewFD);
9906 
9907   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9908   // marking the function.
9909   AddCFAuditedAttribute(NewFD);
9910 
9911   // If this is a function definition, check if we have to apply optnone due to
9912   // a pragma.
9913   if(D.isFunctionDefinition())
9914     AddRangeBasedOptnone(NewFD);
9915 
9916   // If this is the first declaration of an extern C variable, update
9917   // the map of such variables.
9918   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9919       isIncompleteDeclExternC(*this, NewFD))
9920     RegisterLocallyScopedExternCDecl(NewFD, S);
9921 
9922   // Set this FunctionDecl's range up to the right paren.
9923   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9924 
9925   if (D.isRedeclaration() && !Previous.empty()) {
9926     NamedDecl *Prev = Previous.getRepresentativeDecl();
9927     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9928                                    isMemberSpecialization ||
9929                                        isFunctionTemplateSpecialization,
9930                                    D.isFunctionDefinition());
9931   }
9932 
9933   if (getLangOpts().CUDA) {
9934     IdentifierInfo *II = NewFD->getIdentifier();
9935     if (II && II->isStr(getCudaConfigureFuncName()) &&
9936         !NewFD->isInvalidDecl() &&
9937         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9938       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9939         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9940             << getCudaConfigureFuncName();
9941       Context.setcudaConfigureCallDecl(NewFD);
9942     }
9943 
9944     // Variadic functions, other than a *declaration* of printf, are not allowed
9945     // in device-side CUDA code, unless someone passed
9946     // -fcuda-allow-variadic-functions.
9947     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9948         (NewFD->hasAttr<CUDADeviceAttr>() ||
9949          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9950         !(II && II->isStr("printf") && NewFD->isExternC() &&
9951           !D.isFunctionDefinition())) {
9952       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9953     }
9954   }
9955 
9956   MarkUnusedFileScopedDecl(NewFD);
9957 
9958 
9959 
9960   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9961     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9962     if ((getLangOpts().OpenCLVersion >= 120)
9963         && (SC == SC_Static)) {
9964       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9965       D.setInvalidType();
9966     }
9967 
9968     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9969     if (!NewFD->getReturnType()->isVoidType()) {
9970       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9971       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9972           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9973                                 : FixItHint());
9974       D.setInvalidType();
9975     }
9976 
9977     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9978     for (auto Param : NewFD->parameters())
9979       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9980 
9981     if (getLangOpts().OpenCLCPlusPlus) {
9982       if (DC->isRecord()) {
9983         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9984         D.setInvalidType();
9985       }
9986       if (FunctionTemplate) {
9987         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9988         D.setInvalidType();
9989       }
9990     }
9991   }
9992 
9993   if (getLangOpts().CPlusPlus) {
9994     if (FunctionTemplate) {
9995       if (NewFD->isInvalidDecl())
9996         FunctionTemplate->setInvalidDecl();
9997       return FunctionTemplate;
9998     }
9999 
10000     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10001       CompleteMemberSpecialization(NewFD, Previous);
10002   }
10003 
10004   for (const ParmVarDecl *Param : NewFD->parameters()) {
10005     QualType PT = Param->getType();
10006 
10007     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10008     // types.
10009     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10010       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10011         QualType ElemTy = PipeTy->getElementType();
10012           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10013             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10014             D.setInvalidType();
10015           }
10016       }
10017     }
10018   }
10019 
10020   // Here we have an function template explicit specialization at class scope.
10021   // The actual specialization will be postponed to template instatiation
10022   // time via the ClassScopeFunctionSpecializationDecl node.
10023   if (isDependentClassScopeExplicitSpecialization) {
10024     ClassScopeFunctionSpecializationDecl *NewSpec =
10025                          ClassScopeFunctionSpecializationDecl::Create(
10026                                 Context, CurContext, NewFD->getLocation(),
10027                                 cast<CXXMethodDecl>(NewFD),
10028                                 HasExplicitTemplateArgs, TemplateArgs);
10029     CurContext->addDecl(NewSpec);
10030     AddToScope = false;
10031   }
10032 
10033   // Diagnose availability attributes. Availability cannot be used on functions
10034   // that are run during load/unload.
10035   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10036     if (NewFD->hasAttr<ConstructorAttr>()) {
10037       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10038           << 1;
10039       NewFD->dropAttr<AvailabilityAttr>();
10040     }
10041     if (NewFD->hasAttr<DestructorAttr>()) {
10042       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10043           << 2;
10044       NewFD->dropAttr<AvailabilityAttr>();
10045     }
10046   }
10047 
10048   // Diagnose no_builtin attribute on function declaration that are not a
10049   // definition.
10050   // FIXME: We should really be doing this in
10051   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10052   // the FunctionDecl and at this point of the code
10053   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10054   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10055   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10056     switch (D.getFunctionDefinitionKind()) {
10057     case FunctionDefinitionKind::Defaulted:
10058     case FunctionDefinitionKind::Deleted:
10059       Diag(NBA->getLocation(),
10060            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10061           << NBA->getSpelling();
10062       break;
10063     case FunctionDefinitionKind::Declaration:
10064       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10065           << NBA->getSpelling();
10066       break;
10067     case FunctionDefinitionKind::Definition:
10068       break;
10069     }
10070 
10071   return NewFD;
10072 }
10073 
10074 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10075 /// when __declspec(code_seg) "is applied to a class, all member functions of
10076 /// the class and nested classes -- this includes compiler-generated special
10077 /// member functions -- are put in the specified segment."
10078 /// The actual behavior is a little more complicated. The Microsoft compiler
10079 /// won't check outer classes if there is an active value from #pragma code_seg.
10080 /// The CodeSeg is always applied from the direct parent but only from outer
10081 /// classes when the #pragma code_seg stack is empty. See:
10082 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10083 /// available since MS has removed the page.
10084 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10085   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10086   if (!Method)
10087     return nullptr;
10088   const CXXRecordDecl *Parent = Method->getParent();
10089   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10090     Attr *NewAttr = SAttr->clone(S.getASTContext());
10091     NewAttr->setImplicit(true);
10092     return NewAttr;
10093   }
10094 
10095   // The Microsoft compiler won't check outer classes for the CodeSeg
10096   // when the #pragma code_seg stack is active.
10097   if (S.CodeSegStack.CurrentValue)
10098    return nullptr;
10099 
10100   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10101     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10102       Attr *NewAttr = SAttr->clone(S.getASTContext());
10103       NewAttr->setImplicit(true);
10104       return NewAttr;
10105     }
10106   }
10107   return nullptr;
10108 }
10109 
10110 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10111 /// containing class. Otherwise it will return implicit SectionAttr if the
10112 /// function is a definition and there is an active value on CodeSegStack
10113 /// (from the current #pragma code-seg value).
10114 ///
10115 /// \param FD Function being declared.
10116 /// \param IsDefinition Whether it is a definition or just a declarartion.
10117 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10118 ///          nullptr if no attribute should be added.
10119 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10120                                                        bool IsDefinition) {
10121   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10122     return A;
10123   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10124       CodeSegStack.CurrentValue)
10125     return SectionAttr::CreateImplicit(
10126         getASTContext(), CodeSegStack.CurrentValue->getString(),
10127         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10128         SectionAttr::Declspec_allocate);
10129   return nullptr;
10130 }
10131 
10132 /// Determines if we can perform a correct type check for \p D as a
10133 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10134 /// best-effort check.
10135 ///
10136 /// \param NewD The new declaration.
10137 /// \param OldD The old declaration.
10138 /// \param NewT The portion of the type of the new declaration to check.
10139 /// \param OldT The portion of the type of the old declaration to check.
10140 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10141                                           QualType NewT, QualType OldT) {
10142   if (!NewD->getLexicalDeclContext()->isDependentContext())
10143     return true;
10144 
10145   // For dependently-typed local extern declarations and friends, we can't
10146   // perform a correct type check in general until instantiation:
10147   //
10148   //   int f();
10149   //   template<typename T> void g() { T f(); }
10150   //
10151   // (valid if g() is only instantiated with T = int).
10152   if (NewT->isDependentType() &&
10153       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10154     return false;
10155 
10156   // Similarly, if the previous declaration was a dependent local extern
10157   // declaration, we don't really know its type yet.
10158   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10159     return false;
10160 
10161   return true;
10162 }
10163 
10164 /// Checks if the new declaration declared in dependent context must be
10165 /// put in the same redeclaration chain as the specified declaration.
10166 ///
10167 /// \param D Declaration that is checked.
10168 /// \param PrevDecl Previous declaration found with proper lookup method for the
10169 ///                 same declaration name.
10170 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10171 ///          belongs to.
10172 ///
10173 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10174   if (!D->getLexicalDeclContext()->isDependentContext())
10175     return true;
10176 
10177   // Don't chain dependent friend function definitions until instantiation, to
10178   // permit cases like
10179   //
10180   //   void func();
10181   //   template<typename T> class C1 { friend void func() {} };
10182   //   template<typename T> class C2 { friend void func() {} };
10183   //
10184   // ... which is valid if only one of C1 and C2 is ever instantiated.
10185   //
10186   // FIXME: This need only apply to function definitions. For now, we proxy
10187   // this by checking for a file-scope function. We do not want this to apply
10188   // to friend declarations nominating member functions, because that gets in
10189   // the way of access checks.
10190   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10191     return false;
10192 
10193   auto *VD = dyn_cast<ValueDecl>(D);
10194   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10195   return !VD || !PrevVD ||
10196          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10197                                         PrevVD->getType());
10198 }
10199 
10200 /// Check the target attribute of the function for MultiVersion
10201 /// validity.
10202 ///
10203 /// Returns true if there was an error, false otherwise.
10204 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10205   const auto *TA = FD->getAttr<TargetAttr>();
10206   assert(TA && "MultiVersion Candidate requires a target attribute");
10207   ParsedTargetAttr ParseInfo = TA->parse();
10208   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10209   enum ErrType { Feature = 0, Architecture = 1 };
10210 
10211   if (!ParseInfo.Architecture.empty() &&
10212       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10213     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10214         << Architecture << ParseInfo.Architecture;
10215     return true;
10216   }
10217 
10218   for (const auto &Feat : ParseInfo.Features) {
10219     auto BareFeat = StringRef{Feat}.substr(1);
10220     if (Feat[0] == '-') {
10221       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10222           << Feature << ("no-" + BareFeat).str();
10223       return true;
10224     }
10225 
10226     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10227         !TargetInfo.isValidFeatureName(BareFeat)) {
10228       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10229           << Feature << BareFeat;
10230       return true;
10231     }
10232   }
10233   return false;
10234 }
10235 
10236 // Provide a white-list of attributes that are allowed to be combined with
10237 // multiversion functions.
10238 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10239                                            MultiVersionKind MVType) {
10240   // Note: this list/diagnosis must match the list in
10241   // checkMultiversionAttributesAllSame.
10242   switch (Kind) {
10243   default:
10244     return false;
10245   case attr::Used:
10246     return MVType == MultiVersionKind::Target;
10247   case attr::NonNull:
10248   case attr::NoThrow:
10249     return true;
10250   }
10251 }
10252 
10253 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10254                                                  const FunctionDecl *FD,
10255                                                  const FunctionDecl *CausedFD,
10256                                                  MultiVersionKind MVType) {
10257   bool IsCPUSpecificCPUDispatchMVType =
10258       MVType == MultiVersionKind::CPUDispatch ||
10259       MVType == MultiVersionKind::CPUSpecific;
10260   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10261                             Sema &S, const Attr *A) {
10262     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10263         << IsCPUSpecificCPUDispatchMVType << A;
10264     if (CausedFD)
10265       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10266     return true;
10267   };
10268 
10269   for (const Attr *A : FD->attrs()) {
10270     switch (A->getKind()) {
10271     case attr::CPUDispatch:
10272     case attr::CPUSpecific:
10273       if (MVType != MultiVersionKind::CPUDispatch &&
10274           MVType != MultiVersionKind::CPUSpecific)
10275         return Diagnose(S, A);
10276       break;
10277     case attr::Target:
10278       if (MVType != MultiVersionKind::Target)
10279         return Diagnose(S, A);
10280       break;
10281     default:
10282       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10283         return Diagnose(S, A);
10284       break;
10285     }
10286   }
10287   return false;
10288 }
10289 
10290 bool Sema::areMultiversionVariantFunctionsCompatible(
10291     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10292     const PartialDiagnostic &NoProtoDiagID,
10293     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10294     const PartialDiagnosticAt &NoSupportDiagIDAt,
10295     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10296     bool ConstexprSupported, bool CLinkageMayDiffer) {
10297   enum DoesntSupport {
10298     FuncTemplates = 0,
10299     VirtFuncs = 1,
10300     DeducedReturn = 2,
10301     Constructors = 3,
10302     Destructors = 4,
10303     DeletedFuncs = 5,
10304     DefaultedFuncs = 6,
10305     ConstexprFuncs = 7,
10306     ConstevalFuncs = 8,
10307   };
10308   enum Different {
10309     CallingConv = 0,
10310     ReturnType = 1,
10311     ConstexprSpec = 2,
10312     InlineSpec = 3,
10313     StorageClass = 4,
10314     Linkage = 5,
10315   };
10316 
10317   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10318       !OldFD->getType()->getAs<FunctionProtoType>()) {
10319     Diag(OldFD->getLocation(), NoProtoDiagID);
10320     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10321     return true;
10322   }
10323 
10324   if (NoProtoDiagID.getDiagID() != 0 &&
10325       !NewFD->getType()->getAs<FunctionProtoType>())
10326     return Diag(NewFD->getLocation(), NoProtoDiagID);
10327 
10328   if (!TemplatesSupported &&
10329       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10330     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10331            << FuncTemplates;
10332 
10333   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10334     if (NewCXXFD->isVirtual())
10335       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10336              << VirtFuncs;
10337 
10338     if (isa<CXXConstructorDecl>(NewCXXFD))
10339       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10340              << Constructors;
10341 
10342     if (isa<CXXDestructorDecl>(NewCXXFD))
10343       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10344              << Destructors;
10345   }
10346 
10347   if (NewFD->isDeleted())
10348     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10349            << DeletedFuncs;
10350 
10351   if (NewFD->isDefaulted())
10352     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10353            << DefaultedFuncs;
10354 
10355   if (!ConstexprSupported && NewFD->isConstexpr())
10356     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10357            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10358 
10359   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10360   const auto *NewType = cast<FunctionType>(NewQType);
10361   QualType NewReturnType = NewType->getReturnType();
10362 
10363   if (NewReturnType->isUndeducedType())
10364     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10365            << DeducedReturn;
10366 
10367   // Ensure the return type is identical.
10368   if (OldFD) {
10369     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10370     const auto *OldType = cast<FunctionType>(OldQType);
10371     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10372     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10373 
10374     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10375       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10376 
10377     QualType OldReturnType = OldType->getReturnType();
10378 
10379     if (OldReturnType != NewReturnType)
10380       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10381 
10382     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10383       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10384 
10385     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10386       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10387 
10388     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10389       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10390 
10391     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10392       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10393 
10394     if (CheckEquivalentExceptionSpec(
10395             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10396             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10397       return true;
10398   }
10399   return false;
10400 }
10401 
10402 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10403                                              const FunctionDecl *NewFD,
10404                                              bool CausesMV,
10405                                              MultiVersionKind MVType) {
10406   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10407     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10408     if (OldFD)
10409       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10410     return true;
10411   }
10412 
10413   bool IsCPUSpecificCPUDispatchMVType =
10414       MVType == MultiVersionKind::CPUDispatch ||
10415       MVType == MultiVersionKind::CPUSpecific;
10416 
10417   if (CausesMV && OldFD &&
10418       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10419     return true;
10420 
10421   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10422     return true;
10423 
10424   // Only allow transition to MultiVersion if it hasn't been used.
10425   if (OldFD && CausesMV && OldFD->isUsed(false))
10426     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10427 
10428   return S.areMultiversionVariantFunctionsCompatible(
10429       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10430       PartialDiagnosticAt(NewFD->getLocation(),
10431                           S.PDiag(diag::note_multiversioning_caused_here)),
10432       PartialDiagnosticAt(NewFD->getLocation(),
10433                           S.PDiag(diag::err_multiversion_doesnt_support)
10434                               << IsCPUSpecificCPUDispatchMVType),
10435       PartialDiagnosticAt(NewFD->getLocation(),
10436                           S.PDiag(diag::err_multiversion_diff)),
10437       /*TemplatesSupported=*/false,
10438       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10439       /*CLinkageMayDiffer=*/false);
10440 }
10441 
10442 /// Check the validity of a multiversion function declaration that is the
10443 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10444 ///
10445 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10446 ///
10447 /// Returns true if there was an error, false otherwise.
10448 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10449                                            MultiVersionKind MVType,
10450                                            const TargetAttr *TA) {
10451   assert(MVType != MultiVersionKind::None &&
10452          "Function lacks multiversion attribute");
10453 
10454   // Target only causes MV if it is default, otherwise this is a normal
10455   // function.
10456   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10457     return false;
10458 
10459   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10460     FD->setInvalidDecl();
10461     return true;
10462   }
10463 
10464   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10465     FD->setInvalidDecl();
10466     return true;
10467   }
10468 
10469   FD->setIsMultiVersion();
10470   return false;
10471 }
10472 
10473 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10474   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10475     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10476       return true;
10477   }
10478 
10479   return false;
10480 }
10481 
10482 static bool CheckTargetCausesMultiVersioning(
10483     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10484     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10485     LookupResult &Previous) {
10486   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10487   ParsedTargetAttr NewParsed = NewTA->parse();
10488   // Sort order doesn't matter, it just needs to be consistent.
10489   llvm::sort(NewParsed.Features);
10490 
10491   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10492   // to change, this is a simple redeclaration.
10493   if (!NewTA->isDefaultVersion() &&
10494       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10495     return false;
10496 
10497   // Otherwise, this decl causes MultiVersioning.
10498   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10499     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10500     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10501     NewFD->setInvalidDecl();
10502     return true;
10503   }
10504 
10505   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10506                                        MultiVersionKind::Target)) {
10507     NewFD->setInvalidDecl();
10508     return true;
10509   }
10510 
10511   if (CheckMultiVersionValue(S, NewFD)) {
10512     NewFD->setInvalidDecl();
10513     return true;
10514   }
10515 
10516   // If this is 'default', permit the forward declaration.
10517   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10518     Redeclaration = true;
10519     OldDecl = OldFD;
10520     OldFD->setIsMultiVersion();
10521     NewFD->setIsMultiVersion();
10522     return false;
10523   }
10524 
10525   if (CheckMultiVersionValue(S, OldFD)) {
10526     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10527     NewFD->setInvalidDecl();
10528     return true;
10529   }
10530 
10531   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10532 
10533   if (OldParsed == NewParsed) {
10534     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10535     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10536     NewFD->setInvalidDecl();
10537     return true;
10538   }
10539 
10540   for (const auto *FD : OldFD->redecls()) {
10541     const auto *CurTA = FD->getAttr<TargetAttr>();
10542     // We allow forward declarations before ANY multiversioning attributes, but
10543     // nothing after the fact.
10544     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10545         (!CurTA || CurTA->isInherited())) {
10546       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10547           << 0;
10548       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10549       NewFD->setInvalidDecl();
10550       return true;
10551     }
10552   }
10553 
10554   OldFD->setIsMultiVersion();
10555   NewFD->setIsMultiVersion();
10556   Redeclaration = false;
10557   MergeTypeWithPrevious = false;
10558   OldDecl = nullptr;
10559   Previous.clear();
10560   return false;
10561 }
10562 
10563 /// Check the validity of a new function declaration being added to an existing
10564 /// multiversioned declaration collection.
10565 static bool CheckMultiVersionAdditionalDecl(
10566     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10567     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10568     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10569     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10570     LookupResult &Previous) {
10571 
10572   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10573   // Disallow mixing of multiversioning types.
10574   if ((OldMVType == MultiVersionKind::Target &&
10575        NewMVType != MultiVersionKind::Target) ||
10576       (NewMVType == MultiVersionKind::Target &&
10577        OldMVType != MultiVersionKind::Target)) {
10578     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10579     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10580     NewFD->setInvalidDecl();
10581     return true;
10582   }
10583 
10584   ParsedTargetAttr NewParsed;
10585   if (NewTA) {
10586     NewParsed = NewTA->parse();
10587     llvm::sort(NewParsed.Features);
10588   }
10589 
10590   bool UseMemberUsingDeclRules =
10591       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10592 
10593   // Next, check ALL non-overloads to see if this is a redeclaration of a
10594   // previous member of the MultiVersion set.
10595   for (NamedDecl *ND : Previous) {
10596     FunctionDecl *CurFD = ND->getAsFunction();
10597     if (!CurFD)
10598       continue;
10599     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10600       continue;
10601 
10602     if (NewMVType == MultiVersionKind::Target) {
10603       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10604       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10605         NewFD->setIsMultiVersion();
10606         Redeclaration = true;
10607         OldDecl = ND;
10608         return false;
10609       }
10610 
10611       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10612       if (CurParsed == NewParsed) {
10613         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10614         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10615         NewFD->setInvalidDecl();
10616         return true;
10617       }
10618     } else {
10619       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10620       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10621       // Handle CPUDispatch/CPUSpecific versions.
10622       // Only 1 CPUDispatch function is allowed, this will make it go through
10623       // the redeclaration errors.
10624       if (NewMVType == MultiVersionKind::CPUDispatch &&
10625           CurFD->hasAttr<CPUDispatchAttr>()) {
10626         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10627             std::equal(
10628                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10629                 NewCPUDisp->cpus_begin(),
10630                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10631                   return Cur->getName() == New->getName();
10632                 })) {
10633           NewFD->setIsMultiVersion();
10634           Redeclaration = true;
10635           OldDecl = ND;
10636           return false;
10637         }
10638 
10639         // If the declarations don't match, this is an error condition.
10640         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10641         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10642         NewFD->setInvalidDecl();
10643         return true;
10644       }
10645       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10646 
10647         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10648             std::equal(
10649                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10650                 NewCPUSpec->cpus_begin(),
10651                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10652                   return Cur->getName() == New->getName();
10653                 })) {
10654           NewFD->setIsMultiVersion();
10655           Redeclaration = true;
10656           OldDecl = ND;
10657           return false;
10658         }
10659 
10660         // Only 1 version of CPUSpecific is allowed for each CPU.
10661         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10662           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10663             if (CurII == NewII) {
10664               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10665                   << NewII;
10666               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10667               NewFD->setInvalidDecl();
10668               return true;
10669             }
10670           }
10671         }
10672       }
10673       // If the two decls aren't the same MVType, there is no possible error
10674       // condition.
10675     }
10676   }
10677 
10678   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10679   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10680   // handled in the attribute adding step.
10681   if (NewMVType == MultiVersionKind::Target &&
10682       CheckMultiVersionValue(S, NewFD)) {
10683     NewFD->setInvalidDecl();
10684     return true;
10685   }
10686 
10687   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10688                                        !OldFD->isMultiVersion(), NewMVType)) {
10689     NewFD->setInvalidDecl();
10690     return true;
10691   }
10692 
10693   // Permit forward declarations in the case where these two are compatible.
10694   if (!OldFD->isMultiVersion()) {
10695     OldFD->setIsMultiVersion();
10696     NewFD->setIsMultiVersion();
10697     Redeclaration = true;
10698     OldDecl = OldFD;
10699     return false;
10700   }
10701 
10702   NewFD->setIsMultiVersion();
10703   Redeclaration = false;
10704   MergeTypeWithPrevious = false;
10705   OldDecl = nullptr;
10706   Previous.clear();
10707   return false;
10708 }
10709 
10710 
10711 /// Check the validity of a mulitversion function declaration.
10712 /// Also sets the multiversion'ness' of the function itself.
10713 ///
10714 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10715 ///
10716 /// Returns true if there was an error, false otherwise.
10717 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10718                                       bool &Redeclaration, NamedDecl *&OldDecl,
10719                                       bool &MergeTypeWithPrevious,
10720                                       LookupResult &Previous) {
10721   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10722   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10723   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10724 
10725   // Mixing Multiversioning types is prohibited.
10726   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10727       (NewCPUDisp && NewCPUSpec)) {
10728     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10729     NewFD->setInvalidDecl();
10730     return true;
10731   }
10732 
10733   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10734 
10735   // Main isn't allowed to become a multiversion function, however it IS
10736   // permitted to have 'main' be marked with the 'target' optimization hint.
10737   if (NewFD->isMain()) {
10738     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10739         MVType == MultiVersionKind::CPUDispatch ||
10740         MVType == MultiVersionKind::CPUSpecific) {
10741       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10742       NewFD->setInvalidDecl();
10743       return true;
10744     }
10745     return false;
10746   }
10747 
10748   if (!OldDecl || !OldDecl->getAsFunction() ||
10749       OldDecl->getDeclContext()->getRedeclContext() !=
10750           NewFD->getDeclContext()->getRedeclContext()) {
10751     // If there's no previous declaration, AND this isn't attempting to cause
10752     // multiversioning, this isn't an error condition.
10753     if (MVType == MultiVersionKind::None)
10754       return false;
10755     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10756   }
10757 
10758   FunctionDecl *OldFD = OldDecl->getAsFunction();
10759 
10760   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10761     return false;
10762 
10763   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10764     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10765         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10766     NewFD->setInvalidDecl();
10767     return true;
10768   }
10769 
10770   // Handle the target potentially causes multiversioning case.
10771   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10772     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10773                                             Redeclaration, OldDecl,
10774                                             MergeTypeWithPrevious, Previous);
10775 
10776   // At this point, we have a multiversion function decl (in OldFD) AND an
10777   // appropriate attribute in the current function decl.  Resolve that these are
10778   // still compatible with previous declarations.
10779   return CheckMultiVersionAdditionalDecl(
10780       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10781       OldDecl, MergeTypeWithPrevious, Previous);
10782 }
10783 
10784 /// Perform semantic checking of a new function declaration.
10785 ///
10786 /// Performs semantic analysis of the new function declaration
10787 /// NewFD. This routine performs all semantic checking that does not
10788 /// require the actual declarator involved in the declaration, and is
10789 /// used both for the declaration of functions as they are parsed
10790 /// (called via ActOnDeclarator) and for the declaration of functions
10791 /// that have been instantiated via C++ template instantiation (called
10792 /// via InstantiateDecl).
10793 ///
10794 /// \param IsMemberSpecialization whether this new function declaration is
10795 /// a member specialization (that replaces any definition provided by the
10796 /// previous declaration).
10797 ///
10798 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10799 ///
10800 /// \returns true if the function declaration is a redeclaration.
10801 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10802                                     LookupResult &Previous,
10803                                     bool IsMemberSpecialization) {
10804   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10805          "Variably modified return types are not handled here");
10806 
10807   // Determine whether the type of this function should be merged with
10808   // a previous visible declaration. This never happens for functions in C++,
10809   // and always happens in C if the previous declaration was visible.
10810   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10811                                !Previous.isShadowed();
10812 
10813   bool Redeclaration = false;
10814   NamedDecl *OldDecl = nullptr;
10815   bool MayNeedOverloadableChecks = false;
10816 
10817   // Merge or overload the declaration with an existing declaration of
10818   // the same name, if appropriate.
10819   if (!Previous.empty()) {
10820     // Determine whether NewFD is an overload of PrevDecl or
10821     // a declaration that requires merging. If it's an overload,
10822     // there's no more work to do here; we'll just add the new
10823     // function to the scope.
10824     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10825       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10826       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10827         Redeclaration = true;
10828         OldDecl = Candidate;
10829       }
10830     } else {
10831       MayNeedOverloadableChecks = true;
10832       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10833                             /*NewIsUsingDecl*/ false)) {
10834       case Ovl_Match:
10835         Redeclaration = true;
10836         break;
10837 
10838       case Ovl_NonFunction:
10839         Redeclaration = true;
10840         break;
10841 
10842       case Ovl_Overload:
10843         Redeclaration = false;
10844         break;
10845       }
10846     }
10847   }
10848 
10849   // Check for a previous extern "C" declaration with this name.
10850   if (!Redeclaration &&
10851       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10852     if (!Previous.empty()) {
10853       // This is an extern "C" declaration with the same name as a previous
10854       // declaration, and thus redeclares that entity...
10855       Redeclaration = true;
10856       OldDecl = Previous.getFoundDecl();
10857       MergeTypeWithPrevious = false;
10858 
10859       // ... except in the presence of __attribute__((overloadable)).
10860       if (OldDecl->hasAttr<OverloadableAttr>() ||
10861           NewFD->hasAttr<OverloadableAttr>()) {
10862         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10863           MayNeedOverloadableChecks = true;
10864           Redeclaration = false;
10865           OldDecl = nullptr;
10866         }
10867       }
10868     }
10869   }
10870 
10871   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10872                                 MergeTypeWithPrevious, Previous))
10873     return Redeclaration;
10874 
10875   // PPC MMA non-pointer types are not allowed as function return types.
10876   if (Context.getTargetInfo().getTriple().isPPC64() &&
10877       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10878     NewFD->setInvalidDecl();
10879   }
10880 
10881   // C++11 [dcl.constexpr]p8:
10882   //   A constexpr specifier for a non-static member function that is not
10883   //   a constructor declares that member function to be const.
10884   //
10885   // This needs to be delayed until we know whether this is an out-of-line
10886   // definition of a static member function.
10887   //
10888   // This rule is not present in C++1y, so we produce a backwards
10889   // compatibility warning whenever it happens in C++11.
10890   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10891   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10892       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10893       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10894     CXXMethodDecl *OldMD = nullptr;
10895     if (OldDecl)
10896       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10897     if (!OldMD || !OldMD->isStatic()) {
10898       const FunctionProtoType *FPT =
10899         MD->getType()->castAs<FunctionProtoType>();
10900       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10901       EPI.TypeQuals.addConst();
10902       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10903                                           FPT->getParamTypes(), EPI));
10904 
10905       // Warn that we did this, if we're not performing template instantiation.
10906       // In that case, we'll have warned already when the template was defined.
10907       if (!inTemplateInstantiation()) {
10908         SourceLocation AddConstLoc;
10909         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10910                 .IgnoreParens().getAs<FunctionTypeLoc>())
10911           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10912 
10913         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10914           << FixItHint::CreateInsertion(AddConstLoc, " const");
10915       }
10916     }
10917   }
10918 
10919   if (Redeclaration) {
10920     // NewFD and OldDecl represent declarations that need to be
10921     // merged.
10922     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10923       NewFD->setInvalidDecl();
10924       return Redeclaration;
10925     }
10926 
10927     Previous.clear();
10928     Previous.addDecl(OldDecl);
10929 
10930     if (FunctionTemplateDecl *OldTemplateDecl =
10931             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10932       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10933       FunctionTemplateDecl *NewTemplateDecl
10934         = NewFD->getDescribedFunctionTemplate();
10935       assert(NewTemplateDecl && "Template/non-template mismatch");
10936 
10937       // The call to MergeFunctionDecl above may have created some state in
10938       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10939       // can add it as a redeclaration.
10940       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10941 
10942       NewFD->setPreviousDeclaration(OldFD);
10943       if (NewFD->isCXXClassMember()) {
10944         NewFD->setAccess(OldTemplateDecl->getAccess());
10945         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10946       }
10947 
10948       // If this is an explicit specialization of a member that is a function
10949       // template, mark it as a member specialization.
10950       if (IsMemberSpecialization &&
10951           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10952         NewTemplateDecl->setMemberSpecialization();
10953         assert(OldTemplateDecl->isMemberSpecialization());
10954         // Explicit specializations of a member template do not inherit deleted
10955         // status from the parent member template that they are specializing.
10956         if (OldFD->isDeleted()) {
10957           // FIXME: This assert will not hold in the presence of modules.
10958           assert(OldFD->getCanonicalDecl() == OldFD);
10959           // FIXME: We need an update record for this AST mutation.
10960           OldFD->setDeletedAsWritten(false);
10961         }
10962       }
10963 
10964     } else {
10965       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10966         auto *OldFD = cast<FunctionDecl>(OldDecl);
10967         // This needs to happen first so that 'inline' propagates.
10968         NewFD->setPreviousDeclaration(OldFD);
10969         if (NewFD->isCXXClassMember())
10970           NewFD->setAccess(OldFD->getAccess());
10971       }
10972     }
10973   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10974              !NewFD->getAttr<OverloadableAttr>()) {
10975     assert((Previous.empty() ||
10976             llvm::any_of(Previous,
10977                          [](const NamedDecl *ND) {
10978                            return ND->hasAttr<OverloadableAttr>();
10979                          })) &&
10980            "Non-redecls shouldn't happen without overloadable present");
10981 
10982     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10983       const auto *FD = dyn_cast<FunctionDecl>(ND);
10984       return FD && !FD->hasAttr<OverloadableAttr>();
10985     });
10986 
10987     if (OtherUnmarkedIter != Previous.end()) {
10988       Diag(NewFD->getLocation(),
10989            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10990       Diag((*OtherUnmarkedIter)->getLocation(),
10991            diag::note_attribute_overloadable_prev_overload)
10992           << false;
10993 
10994       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10995     }
10996   }
10997 
10998   if (LangOpts.OpenMP)
10999     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11000 
11001   // Semantic checking for this function declaration (in isolation).
11002 
11003   if (getLangOpts().CPlusPlus) {
11004     // C++-specific checks.
11005     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11006       CheckConstructor(Constructor);
11007     } else if (CXXDestructorDecl *Destructor =
11008                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11009       CXXRecordDecl *Record = Destructor->getParent();
11010       QualType ClassType = Context.getTypeDeclType(Record);
11011 
11012       // FIXME: Shouldn't we be able to perform this check even when the class
11013       // type is dependent? Both gcc and edg can handle that.
11014       if (!ClassType->isDependentType()) {
11015         DeclarationName Name
11016           = Context.DeclarationNames.getCXXDestructorName(
11017                                         Context.getCanonicalType(ClassType));
11018         if (NewFD->getDeclName() != Name) {
11019           Diag(NewFD->getLocation(), diag::err_destructor_name);
11020           NewFD->setInvalidDecl();
11021           return Redeclaration;
11022         }
11023       }
11024     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11025       if (auto *TD = Guide->getDescribedFunctionTemplate())
11026         CheckDeductionGuideTemplate(TD);
11027 
11028       // A deduction guide is not on the list of entities that can be
11029       // explicitly specialized.
11030       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11031         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11032             << /*explicit specialization*/ 1;
11033     }
11034 
11035     // Find any virtual functions that this function overrides.
11036     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11037       if (!Method->isFunctionTemplateSpecialization() &&
11038           !Method->getDescribedFunctionTemplate() &&
11039           Method->isCanonicalDecl()) {
11040         AddOverriddenMethods(Method->getParent(), Method);
11041       }
11042       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11043         // C++2a [class.virtual]p6
11044         // A virtual method shall not have a requires-clause.
11045         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11046              diag::err_constrained_virtual_method);
11047 
11048       if (Method->isStatic())
11049         checkThisInStaticMemberFunctionType(Method);
11050     }
11051 
11052     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11053       ActOnConversionDeclarator(Conversion);
11054 
11055     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11056     if (NewFD->isOverloadedOperator() &&
11057         CheckOverloadedOperatorDeclaration(NewFD)) {
11058       NewFD->setInvalidDecl();
11059       return Redeclaration;
11060     }
11061 
11062     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11063     if (NewFD->getLiteralIdentifier() &&
11064         CheckLiteralOperatorDeclaration(NewFD)) {
11065       NewFD->setInvalidDecl();
11066       return Redeclaration;
11067     }
11068 
11069     // In C++, check default arguments now that we have merged decls. Unless
11070     // the lexical context is the class, because in this case this is done
11071     // during delayed parsing anyway.
11072     if (!CurContext->isRecord())
11073       CheckCXXDefaultArguments(NewFD);
11074 
11075     // If this function is declared as being extern "C", then check to see if
11076     // the function returns a UDT (class, struct, or union type) that is not C
11077     // compatible, and if it does, warn the user.
11078     // But, issue any diagnostic on the first declaration only.
11079     if (Previous.empty() && NewFD->isExternC()) {
11080       QualType R = NewFD->getReturnType();
11081       if (R->isIncompleteType() && !R->isVoidType())
11082         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11083             << NewFD << R;
11084       else if (!R.isPODType(Context) && !R->isVoidType() &&
11085                !R->isObjCObjectPointerType())
11086         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11087     }
11088 
11089     // C++1z [dcl.fct]p6:
11090     //   [...] whether the function has a non-throwing exception-specification
11091     //   [is] part of the function type
11092     //
11093     // This results in an ABI break between C++14 and C++17 for functions whose
11094     // declared type includes an exception-specification in a parameter or
11095     // return type. (Exception specifications on the function itself are OK in
11096     // most cases, and exception specifications are not permitted in most other
11097     // contexts where they could make it into a mangling.)
11098     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11099       auto HasNoexcept = [&](QualType T) -> bool {
11100         // Strip off declarator chunks that could be between us and a function
11101         // type. We don't need to look far, exception specifications are very
11102         // restricted prior to C++17.
11103         if (auto *RT = T->getAs<ReferenceType>())
11104           T = RT->getPointeeType();
11105         else if (T->isAnyPointerType())
11106           T = T->getPointeeType();
11107         else if (auto *MPT = T->getAs<MemberPointerType>())
11108           T = MPT->getPointeeType();
11109         if (auto *FPT = T->getAs<FunctionProtoType>())
11110           if (FPT->isNothrow())
11111             return true;
11112         return false;
11113       };
11114 
11115       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11116       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11117       for (QualType T : FPT->param_types())
11118         AnyNoexcept |= HasNoexcept(T);
11119       if (AnyNoexcept)
11120         Diag(NewFD->getLocation(),
11121              diag::warn_cxx17_compat_exception_spec_in_signature)
11122             << NewFD;
11123     }
11124 
11125     if (!Redeclaration && LangOpts.CUDA)
11126       checkCUDATargetOverload(NewFD, Previous);
11127   }
11128   return Redeclaration;
11129 }
11130 
11131 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11132   // C++11 [basic.start.main]p3:
11133   //   A program that [...] declares main to be inline, static or
11134   //   constexpr is ill-formed.
11135   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11136   //   appear in a declaration of main.
11137   // static main is not an error under C99, but we should warn about it.
11138   // We accept _Noreturn main as an extension.
11139   if (FD->getStorageClass() == SC_Static)
11140     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11141          ? diag::err_static_main : diag::warn_static_main)
11142       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11143   if (FD->isInlineSpecified())
11144     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11145       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11146   if (DS.isNoreturnSpecified()) {
11147     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11148     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11149     Diag(NoreturnLoc, diag::ext_noreturn_main);
11150     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11151       << FixItHint::CreateRemoval(NoreturnRange);
11152   }
11153   if (FD->isConstexpr()) {
11154     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11155         << FD->isConsteval()
11156         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11157     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11158   }
11159 
11160   if (getLangOpts().OpenCL) {
11161     Diag(FD->getLocation(), diag::err_opencl_no_main)
11162         << FD->hasAttr<OpenCLKernelAttr>();
11163     FD->setInvalidDecl();
11164     return;
11165   }
11166 
11167   QualType T = FD->getType();
11168   assert(T->isFunctionType() && "function decl is not of function type");
11169   const FunctionType* FT = T->castAs<FunctionType>();
11170 
11171   // Set default calling convention for main()
11172   if (FT->getCallConv() != CC_C) {
11173     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11174     FD->setType(QualType(FT, 0));
11175     T = Context.getCanonicalType(FD->getType());
11176   }
11177 
11178   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11179     // In C with GNU extensions we allow main() to have non-integer return
11180     // type, but we should warn about the extension, and we disable the
11181     // implicit-return-zero rule.
11182 
11183     // GCC in C mode accepts qualified 'int'.
11184     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11185       FD->setHasImplicitReturnZero(true);
11186     else {
11187       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11188       SourceRange RTRange = FD->getReturnTypeSourceRange();
11189       if (RTRange.isValid())
11190         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11191             << FixItHint::CreateReplacement(RTRange, "int");
11192     }
11193   } else {
11194     // In C and C++, main magically returns 0 if you fall off the end;
11195     // set the flag which tells us that.
11196     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11197 
11198     // All the standards say that main() should return 'int'.
11199     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11200       FD->setHasImplicitReturnZero(true);
11201     else {
11202       // Otherwise, this is just a flat-out error.
11203       SourceRange RTRange = FD->getReturnTypeSourceRange();
11204       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11205           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11206                                 : FixItHint());
11207       FD->setInvalidDecl(true);
11208     }
11209   }
11210 
11211   // Treat protoless main() as nullary.
11212   if (isa<FunctionNoProtoType>(FT)) return;
11213 
11214   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11215   unsigned nparams = FTP->getNumParams();
11216   assert(FD->getNumParams() == nparams);
11217 
11218   bool HasExtraParameters = (nparams > 3);
11219 
11220   if (FTP->isVariadic()) {
11221     Diag(FD->getLocation(), diag::ext_variadic_main);
11222     // FIXME: if we had information about the location of the ellipsis, we
11223     // could add a FixIt hint to remove it as a parameter.
11224   }
11225 
11226   // Darwin passes an undocumented fourth argument of type char**.  If
11227   // other platforms start sprouting these, the logic below will start
11228   // getting shifty.
11229   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11230     HasExtraParameters = false;
11231 
11232   if (HasExtraParameters) {
11233     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11234     FD->setInvalidDecl(true);
11235     nparams = 3;
11236   }
11237 
11238   // FIXME: a lot of the following diagnostics would be improved
11239   // if we had some location information about types.
11240 
11241   QualType CharPP =
11242     Context.getPointerType(Context.getPointerType(Context.CharTy));
11243   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11244 
11245   for (unsigned i = 0; i < nparams; ++i) {
11246     QualType AT = FTP->getParamType(i);
11247 
11248     bool mismatch = true;
11249 
11250     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11251       mismatch = false;
11252     else if (Expected[i] == CharPP) {
11253       // As an extension, the following forms are okay:
11254       //   char const **
11255       //   char const * const *
11256       //   char * const *
11257 
11258       QualifierCollector qs;
11259       const PointerType* PT;
11260       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11261           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11262           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11263                               Context.CharTy)) {
11264         qs.removeConst();
11265         mismatch = !qs.empty();
11266       }
11267     }
11268 
11269     if (mismatch) {
11270       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11271       // TODO: suggest replacing given type with expected type
11272       FD->setInvalidDecl(true);
11273     }
11274   }
11275 
11276   if (nparams == 1 && !FD->isInvalidDecl()) {
11277     Diag(FD->getLocation(), diag::warn_main_one_arg);
11278   }
11279 
11280   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11281     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11282     FD->setInvalidDecl();
11283   }
11284 }
11285 
11286 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11287 
11288   // Default calling convention for main and wmain is __cdecl
11289   if (FD->getName() == "main" || FD->getName() == "wmain")
11290     return false;
11291 
11292   // Default calling convention for MinGW is __cdecl
11293   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11294   if (T.isWindowsGNUEnvironment())
11295     return false;
11296 
11297   // Default calling convention for WinMain, wWinMain and DllMain
11298   // is __stdcall on 32 bit Windows
11299   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11300     return true;
11301 
11302   return false;
11303 }
11304 
11305 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11306   QualType T = FD->getType();
11307   assert(T->isFunctionType() && "function decl is not of function type");
11308   const FunctionType *FT = T->castAs<FunctionType>();
11309 
11310   // Set an implicit return of 'zero' if the function can return some integral,
11311   // enumeration, pointer or nullptr type.
11312   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11313       FT->getReturnType()->isAnyPointerType() ||
11314       FT->getReturnType()->isNullPtrType())
11315     // DllMain is exempt because a return value of zero means it failed.
11316     if (FD->getName() != "DllMain")
11317       FD->setHasImplicitReturnZero(true);
11318 
11319   // Explicity specified calling conventions are applied to MSVC entry points
11320   if (!hasExplicitCallingConv(T)) {
11321     if (isDefaultStdCall(FD, *this)) {
11322       if (FT->getCallConv() != CC_X86StdCall) {
11323         FT = Context.adjustFunctionType(
11324             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11325         FD->setType(QualType(FT, 0));
11326       }
11327     } else if (FT->getCallConv() != CC_C) {
11328       FT = Context.adjustFunctionType(FT,
11329                                       FT->getExtInfo().withCallingConv(CC_C));
11330       FD->setType(QualType(FT, 0));
11331     }
11332   }
11333 
11334   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11335     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11336     FD->setInvalidDecl();
11337   }
11338 }
11339 
11340 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11341   // FIXME: Need strict checking.  In C89, we need to check for
11342   // any assignment, increment, decrement, function-calls, or
11343   // commas outside of a sizeof.  In C99, it's the same list,
11344   // except that the aforementioned are allowed in unevaluated
11345   // expressions.  Everything else falls under the
11346   // "may accept other forms of constant expressions" exception.
11347   //
11348   // Regular C++ code will not end up here (exceptions: language extensions,
11349   // OpenCL C++ etc), so the constant expression rules there don't matter.
11350   if (Init->isValueDependent()) {
11351     assert(Init->containsErrors() &&
11352            "Dependent code should only occur in error-recovery path.");
11353     return true;
11354   }
11355   const Expr *Culprit;
11356   if (Init->isConstantInitializer(Context, false, &Culprit))
11357     return false;
11358   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11359     << Culprit->getSourceRange();
11360   return true;
11361 }
11362 
11363 namespace {
11364   // Visits an initialization expression to see if OrigDecl is evaluated in
11365   // its own initialization and throws a warning if it does.
11366   class SelfReferenceChecker
11367       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11368     Sema &S;
11369     Decl *OrigDecl;
11370     bool isRecordType;
11371     bool isPODType;
11372     bool isReferenceType;
11373 
11374     bool isInitList;
11375     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11376 
11377   public:
11378     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11379 
11380     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11381                                                     S(S), OrigDecl(OrigDecl) {
11382       isPODType = false;
11383       isRecordType = false;
11384       isReferenceType = false;
11385       isInitList = false;
11386       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11387         isPODType = VD->getType().isPODType(S.Context);
11388         isRecordType = VD->getType()->isRecordType();
11389         isReferenceType = VD->getType()->isReferenceType();
11390       }
11391     }
11392 
11393     // For most expressions, just call the visitor.  For initializer lists,
11394     // track the index of the field being initialized since fields are
11395     // initialized in order allowing use of previously initialized fields.
11396     void CheckExpr(Expr *E) {
11397       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11398       if (!InitList) {
11399         Visit(E);
11400         return;
11401       }
11402 
11403       // Track and increment the index here.
11404       isInitList = true;
11405       InitFieldIndex.push_back(0);
11406       for (auto Child : InitList->children()) {
11407         CheckExpr(cast<Expr>(Child));
11408         ++InitFieldIndex.back();
11409       }
11410       InitFieldIndex.pop_back();
11411     }
11412 
11413     // Returns true if MemberExpr is checked and no further checking is needed.
11414     // Returns false if additional checking is required.
11415     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11416       llvm::SmallVector<FieldDecl*, 4> Fields;
11417       Expr *Base = E;
11418       bool ReferenceField = false;
11419 
11420       // Get the field members used.
11421       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11422         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11423         if (!FD)
11424           return false;
11425         Fields.push_back(FD);
11426         if (FD->getType()->isReferenceType())
11427           ReferenceField = true;
11428         Base = ME->getBase()->IgnoreParenImpCasts();
11429       }
11430 
11431       // Keep checking only if the base Decl is the same.
11432       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11433       if (!DRE || DRE->getDecl() != OrigDecl)
11434         return false;
11435 
11436       // A reference field can be bound to an unininitialized field.
11437       if (CheckReference && !ReferenceField)
11438         return true;
11439 
11440       // Convert FieldDecls to their index number.
11441       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11442       for (const FieldDecl *I : llvm::reverse(Fields))
11443         UsedFieldIndex.push_back(I->getFieldIndex());
11444 
11445       // See if a warning is needed by checking the first difference in index
11446       // numbers.  If field being used has index less than the field being
11447       // initialized, then the use is safe.
11448       for (auto UsedIter = UsedFieldIndex.begin(),
11449                 UsedEnd = UsedFieldIndex.end(),
11450                 OrigIter = InitFieldIndex.begin(),
11451                 OrigEnd = InitFieldIndex.end();
11452            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11453         if (*UsedIter < *OrigIter)
11454           return true;
11455         if (*UsedIter > *OrigIter)
11456           break;
11457       }
11458 
11459       // TODO: Add a different warning which will print the field names.
11460       HandleDeclRefExpr(DRE);
11461       return true;
11462     }
11463 
11464     // For most expressions, the cast is directly above the DeclRefExpr.
11465     // For conditional operators, the cast can be outside the conditional
11466     // operator if both expressions are DeclRefExpr's.
11467     void HandleValue(Expr *E) {
11468       E = E->IgnoreParens();
11469       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11470         HandleDeclRefExpr(DRE);
11471         return;
11472       }
11473 
11474       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11475         Visit(CO->getCond());
11476         HandleValue(CO->getTrueExpr());
11477         HandleValue(CO->getFalseExpr());
11478         return;
11479       }
11480 
11481       if (BinaryConditionalOperator *BCO =
11482               dyn_cast<BinaryConditionalOperator>(E)) {
11483         Visit(BCO->getCond());
11484         HandleValue(BCO->getFalseExpr());
11485         return;
11486       }
11487 
11488       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11489         HandleValue(OVE->getSourceExpr());
11490         return;
11491       }
11492 
11493       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11494         if (BO->getOpcode() == BO_Comma) {
11495           Visit(BO->getLHS());
11496           HandleValue(BO->getRHS());
11497           return;
11498         }
11499       }
11500 
11501       if (isa<MemberExpr>(E)) {
11502         if (isInitList) {
11503           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11504                                       false /*CheckReference*/))
11505             return;
11506         }
11507 
11508         Expr *Base = E->IgnoreParenImpCasts();
11509         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11510           // Check for static member variables and don't warn on them.
11511           if (!isa<FieldDecl>(ME->getMemberDecl()))
11512             return;
11513           Base = ME->getBase()->IgnoreParenImpCasts();
11514         }
11515         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11516           HandleDeclRefExpr(DRE);
11517         return;
11518       }
11519 
11520       Visit(E);
11521     }
11522 
11523     // Reference types not handled in HandleValue are handled here since all
11524     // uses of references are bad, not just r-value uses.
11525     void VisitDeclRefExpr(DeclRefExpr *E) {
11526       if (isReferenceType)
11527         HandleDeclRefExpr(E);
11528     }
11529 
11530     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11531       if (E->getCastKind() == CK_LValueToRValue) {
11532         HandleValue(E->getSubExpr());
11533         return;
11534       }
11535 
11536       Inherited::VisitImplicitCastExpr(E);
11537     }
11538 
11539     void VisitMemberExpr(MemberExpr *E) {
11540       if (isInitList) {
11541         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11542           return;
11543       }
11544 
11545       // Don't warn on arrays since they can be treated as pointers.
11546       if (E->getType()->canDecayToPointerType()) return;
11547 
11548       // Warn when a non-static method call is followed by non-static member
11549       // field accesses, which is followed by a DeclRefExpr.
11550       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11551       bool Warn = (MD && !MD->isStatic());
11552       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11553       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11554         if (!isa<FieldDecl>(ME->getMemberDecl()))
11555           Warn = false;
11556         Base = ME->getBase()->IgnoreParenImpCasts();
11557       }
11558 
11559       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11560         if (Warn)
11561           HandleDeclRefExpr(DRE);
11562         return;
11563       }
11564 
11565       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11566       // Visit that expression.
11567       Visit(Base);
11568     }
11569 
11570     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11571       Expr *Callee = E->getCallee();
11572 
11573       if (isa<UnresolvedLookupExpr>(Callee))
11574         return Inherited::VisitCXXOperatorCallExpr(E);
11575 
11576       Visit(Callee);
11577       for (auto Arg: E->arguments())
11578         HandleValue(Arg->IgnoreParenImpCasts());
11579     }
11580 
11581     void VisitUnaryOperator(UnaryOperator *E) {
11582       // For POD record types, addresses of its own members are well-defined.
11583       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11584           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11585         if (!isPODType)
11586           HandleValue(E->getSubExpr());
11587         return;
11588       }
11589 
11590       if (E->isIncrementDecrementOp()) {
11591         HandleValue(E->getSubExpr());
11592         return;
11593       }
11594 
11595       Inherited::VisitUnaryOperator(E);
11596     }
11597 
11598     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11599 
11600     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11601       if (E->getConstructor()->isCopyConstructor()) {
11602         Expr *ArgExpr = E->getArg(0);
11603         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11604           if (ILE->getNumInits() == 1)
11605             ArgExpr = ILE->getInit(0);
11606         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11607           if (ICE->getCastKind() == CK_NoOp)
11608             ArgExpr = ICE->getSubExpr();
11609         HandleValue(ArgExpr);
11610         return;
11611       }
11612       Inherited::VisitCXXConstructExpr(E);
11613     }
11614 
11615     void VisitCallExpr(CallExpr *E) {
11616       // Treat std::move as a use.
11617       if (E->isCallToStdMove()) {
11618         HandleValue(E->getArg(0));
11619         return;
11620       }
11621 
11622       Inherited::VisitCallExpr(E);
11623     }
11624 
11625     void VisitBinaryOperator(BinaryOperator *E) {
11626       if (E->isCompoundAssignmentOp()) {
11627         HandleValue(E->getLHS());
11628         Visit(E->getRHS());
11629         return;
11630       }
11631 
11632       Inherited::VisitBinaryOperator(E);
11633     }
11634 
11635     // A custom visitor for BinaryConditionalOperator is needed because the
11636     // regular visitor would check the condition and true expression separately
11637     // but both point to the same place giving duplicate diagnostics.
11638     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11639       Visit(E->getCond());
11640       Visit(E->getFalseExpr());
11641     }
11642 
11643     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11644       Decl* ReferenceDecl = DRE->getDecl();
11645       if (OrigDecl != ReferenceDecl) return;
11646       unsigned diag;
11647       if (isReferenceType) {
11648         diag = diag::warn_uninit_self_reference_in_reference_init;
11649       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11650         diag = diag::warn_static_self_reference_in_init;
11651       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11652                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11653                  DRE->getDecl()->getType()->isRecordType()) {
11654         diag = diag::warn_uninit_self_reference_in_init;
11655       } else {
11656         // Local variables will be handled by the CFG analysis.
11657         return;
11658       }
11659 
11660       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11661                             S.PDiag(diag)
11662                                 << DRE->getDecl() << OrigDecl->getLocation()
11663                                 << DRE->getSourceRange());
11664     }
11665   };
11666 
11667   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11668   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11669                                  bool DirectInit) {
11670     // Parameters arguments are occassionially constructed with itself,
11671     // for instance, in recursive functions.  Skip them.
11672     if (isa<ParmVarDecl>(OrigDecl))
11673       return;
11674 
11675     E = E->IgnoreParens();
11676 
11677     // Skip checking T a = a where T is not a record or reference type.
11678     // Doing so is a way to silence uninitialized warnings.
11679     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11680       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11681         if (ICE->getCastKind() == CK_LValueToRValue)
11682           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11683             if (DRE->getDecl() == OrigDecl)
11684               return;
11685 
11686     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11687   }
11688 } // end anonymous namespace
11689 
11690 namespace {
11691   // Simple wrapper to add the name of a variable or (if no variable is
11692   // available) a DeclarationName into a diagnostic.
11693   struct VarDeclOrName {
11694     VarDecl *VDecl;
11695     DeclarationName Name;
11696 
11697     friend const Sema::SemaDiagnosticBuilder &
11698     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11699       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11700     }
11701   };
11702 } // end anonymous namespace
11703 
11704 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11705                                             DeclarationName Name, QualType Type,
11706                                             TypeSourceInfo *TSI,
11707                                             SourceRange Range, bool DirectInit,
11708                                             Expr *Init) {
11709   bool IsInitCapture = !VDecl;
11710   assert((!VDecl || !VDecl->isInitCapture()) &&
11711          "init captures are expected to be deduced prior to initialization");
11712 
11713   VarDeclOrName VN{VDecl, Name};
11714 
11715   DeducedType *Deduced = Type->getContainedDeducedType();
11716   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11717 
11718   // C++11 [dcl.spec.auto]p3
11719   if (!Init) {
11720     assert(VDecl && "no init for init capture deduction?");
11721 
11722     // Except for class argument deduction, and then for an initializing
11723     // declaration only, i.e. no static at class scope or extern.
11724     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11725         VDecl->hasExternalStorage() ||
11726         VDecl->isStaticDataMember()) {
11727       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11728         << VDecl->getDeclName() << Type;
11729       return QualType();
11730     }
11731   }
11732 
11733   ArrayRef<Expr*> DeduceInits;
11734   if (Init)
11735     DeduceInits = Init;
11736 
11737   if (DirectInit) {
11738     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11739       DeduceInits = PL->exprs();
11740   }
11741 
11742   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11743     assert(VDecl && "non-auto type for init capture deduction?");
11744     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11745     InitializationKind Kind = InitializationKind::CreateForInit(
11746         VDecl->getLocation(), DirectInit, Init);
11747     // FIXME: Initialization should not be taking a mutable list of inits.
11748     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11749     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11750                                                        InitsCopy);
11751   }
11752 
11753   if (DirectInit) {
11754     if (auto *IL = dyn_cast<InitListExpr>(Init))
11755       DeduceInits = IL->inits();
11756   }
11757 
11758   // Deduction only works if we have exactly one source expression.
11759   if (DeduceInits.empty()) {
11760     // It isn't possible to write this directly, but it is possible to
11761     // end up in this situation with "auto x(some_pack...);"
11762     Diag(Init->getBeginLoc(), IsInitCapture
11763                                   ? diag::err_init_capture_no_expression
11764                                   : diag::err_auto_var_init_no_expression)
11765         << VN << Type << Range;
11766     return QualType();
11767   }
11768 
11769   if (DeduceInits.size() > 1) {
11770     Diag(DeduceInits[1]->getBeginLoc(),
11771          IsInitCapture ? diag::err_init_capture_multiple_expressions
11772                        : diag::err_auto_var_init_multiple_expressions)
11773         << VN << Type << Range;
11774     return QualType();
11775   }
11776 
11777   Expr *DeduceInit = DeduceInits[0];
11778   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11779     Diag(Init->getBeginLoc(), IsInitCapture
11780                                   ? diag::err_init_capture_paren_braces
11781                                   : diag::err_auto_var_init_paren_braces)
11782         << isa<InitListExpr>(Init) << VN << Type << Range;
11783     return QualType();
11784   }
11785 
11786   // Expressions default to 'id' when we're in a debugger.
11787   bool DefaultedAnyToId = false;
11788   if (getLangOpts().DebuggerCastResultToId &&
11789       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11790     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11791     if (Result.isInvalid()) {
11792       return QualType();
11793     }
11794     Init = Result.get();
11795     DefaultedAnyToId = true;
11796   }
11797 
11798   // C++ [dcl.decomp]p1:
11799   //   If the assignment-expression [...] has array type A and no ref-qualifier
11800   //   is present, e has type cv A
11801   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11802       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11803       DeduceInit->getType()->isConstantArrayType())
11804     return Context.getQualifiedType(DeduceInit->getType(),
11805                                     Type.getQualifiers());
11806 
11807   QualType DeducedType;
11808   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11809     if (!IsInitCapture)
11810       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11811     else if (isa<InitListExpr>(Init))
11812       Diag(Range.getBegin(),
11813            diag::err_init_capture_deduction_failure_from_init_list)
11814           << VN
11815           << (DeduceInit->getType().isNull() ? TSI->getType()
11816                                              : DeduceInit->getType())
11817           << DeduceInit->getSourceRange();
11818     else
11819       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11820           << VN << TSI->getType()
11821           << (DeduceInit->getType().isNull() ? TSI->getType()
11822                                              : DeduceInit->getType())
11823           << DeduceInit->getSourceRange();
11824   }
11825 
11826   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11827   // 'id' instead of a specific object type prevents most of our usual
11828   // checks.
11829   // We only want to warn outside of template instantiations, though:
11830   // inside a template, the 'id' could have come from a parameter.
11831   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11832       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11833     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11834     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11835   }
11836 
11837   return DeducedType;
11838 }
11839 
11840 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11841                                          Expr *Init) {
11842   assert(!Init || !Init->containsErrors());
11843   QualType DeducedType = deduceVarTypeFromInitializer(
11844       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11845       VDecl->getSourceRange(), DirectInit, Init);
11846   if (DeducedType.isNull()) {
11847     VDecl->setInvalidDecl();
11848     return true;
11849   }
11850 
11851   VDecl->setType(DeducedType);
11852   assert(VDecl->isLinkageValid());
11853 
11854   // In ARC, infer lifetime.
11855   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11856     VDecl->setInvalidDecl();
11857 
11858   if (getLangOpts().OpenCL)
11859     deduceOpenCLAddressSpace(VDecl);
11860 
11861   // If this is a redeclaration, check that the type we just deduced matches
11862   // the previously declared type.
11863   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11864     // We never need to merge the type, because we cannot form an incomplete
11865     // array of auto, nor deduce such a type.
11866     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11867   }
11868 
11869   // Check the deduced type is valid for a variable declaration.
11870   CheckVariableDeclarationType(VDecl);
11871   return VDecl->isInvalidDecl();
11872 }
11873 
11874 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11875                                               SourceLocation Loc) {
11876   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11877     Init = EWC->getSubExpr();
11878 
11879   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11880     Init = CE->getSubExpr();
11881 
11882   QualType InitType = Init->getType();
11883   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11884           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11885          "shouldn't be called if type doesn't have a non-trivial C struct");
11886   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11887     for (auto I : ILE->inits()) {
11888       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11889           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11890         continue;
11891       SourceLocation SL = I->getExprLoc();
11892       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11893     }
11894     return;
11895   }
11896 
11897   if (isa<ImplicitValueInitExpr>(Init)) {
11898     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11899       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11900                             NTCUK_Init);
11901   } else {
11902     // Assume all other explicit initializers involving copying some existing
11903     // object.
11904     // TODO: ignore any explicit initializers where we can guarantee
11905     // copy-elision.
11906     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11907       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11908   }
11909 }
11910 
11911 namespace {
11912 
11913 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11914   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11915   // in the source code or implicitly by the compiler if it is in a union
11916   // defined in a system header and has non-trivial ObjC ownership
11917   // qualifications. We don't want those fields to participate in determining
11918   // whether the containing union is non-trivial.
11919   return FD->hasAttr<UnavailableAttr>();
11920 }
11921 
11922 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11923     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11924                                     void> {
11925   using Super =
11926       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11927                                     void>;
11928 
11929   DiagNonTrivalCUnionDefaultInitializeVisitor(
11930       QualType OrigTy, SourceLocation OrigLoc,
11931       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11932       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11933 
11934   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11935                      const FieldDecl *FD, bool InNonTrivialUnion) {
11936     if (const auto *AT = S.Context.getAsArrayType(QT))
11937       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11938                                      InNonTrivialUnion);
11939     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11940   }
11941 
11942   void visitARCStrong(QualType QT, const FieldDecl *FD,
11943                       bool InNonTrivialUnion) {
11944     if (InNonTrivialUnion)
11945       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11946           << 1 << 0 << QT << FD->getName();
11947   }
11948 
11949   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11950     if (InNonTrivialUnion)
11951       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11952           << 1 << 0 << QT << FD->getName();
11953   }
11954 
11955   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11956     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11957     if (RD->isUnion()) {
11958       if (OrigLoc.isValid()) {
11959         bool IsUnion = false;
11960         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11961           IsUnion = OrigRD->isUnion();
11962         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11963             << 0 << OrigTy << IsUnion << UseContext;
11964         // Reset OrigLoc so that this diagnostic is emitted only once.
11965         OrigLoc = SourceLocation();
11966       }
11967       InNonTrivialUnion = true;
11968     }
11969 
11970     if (InNonTrivialUnion)
11971       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11972           << 0 << 0 << QT.getUnqualifiedType() << "";
11973 
11974     for (const FieldDecl *FD : RD->fields())
11975       if (!shouldIgnoreForRecordTriviality(FD))
11976         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11977   }
11978 
11979   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11980 
11981   // The non-trivial C union type or the struct/union type that contains a
11982   // non-trivial C union.
11983   QualType OrigTy;
11984   SourceLocation OrigLoc;
11985   Sema::NonTrivialCUnionContext UseContext;
11986   Sema &S;
11987 };
11988 
11989 struct DiagNonTrivalCUnionDestructedTypeVisitor
11990     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11991   using Super =
11992       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11993 
11994   DiagNonTrivalCUnionDestructedTypeVisitor(
11995       QualType OrigTy, SourceLocation OrigLoc,
11996       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11997       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11998 
11999   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12000                      const FieldDecl *FD, bool InNonTrivialUnion) {
12001     if (const auto *AT = S.Context.getAsArrayType(QT))
12002       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12003                                      InNonTrivialUnion);
12004     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12005   }
12006 
12007   void visitARCStrong(QualType QT, const FieldDecl *FD,
12008                       bool InNonTrivialUnion) {
12009     if (InNonTrivialUnion)
12010       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12011           << 1 << 1 << QT << FD->getName();
12012   }
12013 
12014   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12015     if (InNonTrivialUnion)
12016       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12017           << 1 << 1 << QT << FD->getName();
12018   }
12019 
12020   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12021     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12022     if (RD->isUnion()) {
12023       if (OrigLoc.isValid()) {
12024         bool IsUnion = false;
12025         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12026           IsUnion = OrigRD->isUnion();
12027         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12028             << 1 << OrigTy << IsUnion << UseContext;
12029         // Reset OrigLoc so that this diagnostic is emitted only once.
12030         OrigLoc = SourceLocation();
12031       }
12032       InNonTrivialUnion = true;
12033     }
12034 
12035     if (InNonTrivialUnion)
12036       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12037           << 0 << 1 << QT.getUnqualifiedType() << "";
12038 
12039     for (const FieldDecl *FD : RD->fields())
12040       if (!shouldIgnoreForRecordTriviality(FD))
12041         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12042   }
12043 
12044   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12045   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12046                           bool InNonTrivialUnion) {}
12047 
12048   // The non-trivial C union type or the struct/union type that contains a
12049   // non-trivial C union.
12050   QualType OrigTy;
12051   SourceLocation OrigLoc;
12052   Sema::NonTrivialCUnionContext UseContext;
12053   Sema &S;
12054 };
12055 
12056 struct DiagNonTrivalCUnionCopyVisitor
12057     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12058   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12059 
12060   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12061                                  Sema::NonTrivialCUnionContext UseContext,
12062                                  Sema &S)
12063       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12064 
12065   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12066                      const FieldDecl *FD, bool InNonTrivialUnion) {
12067     if (const auto *AT = S.Context.getAsArrayType(QT))
12068       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12069                                      InNonTrivialUnion);
12070     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12071   }
12072 
12073   void visitARCStrong(QualType QT, const FieldDecl *FD,
12074                       bool InNonTrivialUnion) {
12075     if (InNonTrivialUnion)
12076       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12077           << 1 << 2 << QT << FD->getName();
12078   }
12079 
12080   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12081     if (InNonTrivialUnion)
12082       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12083           << 1 << 2 << QT << FD->getName();
12084   }
12085 
12086   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12087     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12088     if (RD->isUnion()) {
12089       if (OrigLoc.isValid()) {
12090         bool IsUnion = false;
12091         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12092           IsUnion = OrigRD->isUnion();
12093         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12094             << 2 << OrigTy << IsUnion << UseContext;
12095         // Reset OrigLoc so that this diagnostic is emitted only once.
12096         OrigLoc = SourceLocation();
12097       }
12098       InNonTrivialUnion = true;
12099     }
12100 
12101     if (InNonTrivialUnion)
12102       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12103           << 0 << 2 << QT.getUnqualifiedType() << "";
12104 
12105     for (const FieldDecl *FD : RD->fields())
12106       if (!shouldIgnoreForRecordTriviality(FD))
12107         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12108   }
12109 
12110   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12111                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12112   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12113   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12114                             bool InNonTrivialUnion) {}
12115 
12116   // The non-trivial C union type or the struct/union type that contains a
12117   // non-trivial C union.
12118   QualType OrigTy;
12119   SourceLocation OrigLoc;
12120   Sema::NonTrivialCUnionContext UseContext;
12121   Sema &S;
12122 };
12123 
12124 } // namespace
12125 
12126 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12127                                  NonTrivialCUnionContext UseContext,
12128                                  unsigned NonTrivialKind) {
12129   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12130           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12131           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12132          "shouldn't be called if type doesn't have a non-trivial C union");
12133 
12134   if ((NonTrivialKind & NTCUK_Init) &&
12135       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12136     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12137         .visit(QT, nullptr, false);
12138   if ((NonTrivialKind & NTCUK_Destruct) &&
12139       QT.hasNonTrivialToPrimitiveDestructCUnion())
12140     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12141         .visit(QT, nullptr, false);
12142   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12143     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12144         .visit(QT, nullptr, false);
12145 }
12146 
12147 /// AddInitializerToDecl - Adds the initializer Init to the
12148 /// declaration dcl. If DirectInit is true, this is C++ direct
12149 /// initialization rather than copy initialization.
12150 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12151   // If there is no declaration, there was an error parsing it.  Just ignore
12152   // the initializer.
12153   if (!RealDecl || RealDecl->isInvalidDecl()) {
12154     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12155     return;
12156   }
12157 
12158   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12159     // Pure-specifiers are handled in ActOnPureSpecifier.
12160     Diag(Method->getLocation(), diag::err_member_function_initialization)
12161       << Method->getDeclName() << Init->getSourceRange();
12162     Method->setInvalidDecl();
12163     return;
12164   }
12165 
12166   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12167   if (!VDecl) {
12168     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12169     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12170     RealDecl->setInvalidDecl();
12171     return;
12172   }
12173 
12174   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12175   if (VDecl->getType()->isUndeducedType()) {
12176     // Attempt typo correction early so that the type of the init expression can
12177     // be deduced based on the chosen correction if the original init contains a
12178     // TypoExpr.
12179     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12180     if (!Res.isUsable()) {
12181       // There are unresolved typos in Init, just drop them.
12182       // FIXME: improve the recovery strategy to preserve the Init.
12183       RealDecl->setInvalidDecl();
12184       return;
12185     }
12186     if (Res.get()->containsErrors()) {
12187       // Invalidate the decl as we don't know the type for recovery-expr yet.
12188       RealDecl->setInvalidDecl();
12189       VDecl->setInit(Res.get());
12190       return;
12191     }
12192     Init = Res.get();
12193 
12194     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12195       return;
12196   }
12197 
12198   // dllimport cannot be used on variable definitions.
12199   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12200     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12201     VDecl->setInvalidDecl();
12202     return;
12203   }
12204 
12205   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12206     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12207     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12208     VDecl->setInvalidDecl();
12209     return;
12210   }
12211 
12212   if (!VDecl->getType()->isDependentType()) {
12213     // A definition must end up with a complete type, which means it must be
12214     // complete with the restriction that an array type might be completed by
12215     // the initializer; note that later code assumes this restriction.
12216     QualType BaseDeclType = VDecl->getType();
12217     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12218       BaseDeclType = Array->getElementType();
12219     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12220                             diag::err_typecheck_decl_incomplete_type)) {
12221       RealDecl->setInvalidDecl();
12222       return;
12223     }
12224 
12225     // The variable can not have an abstract class type.
12226     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12227                                diag::err_abstract_type_in_decl,
12228                                AbstractVariableType))
12229       VDecl->setInvalidDecl();
12230   }
12231 
12232   // If adding the initializer will turn this declaration into a definition,
12233   // and we already have a definition for this variable, diagnose or otherwise
12234   // handle the situation.
12235   if (VarDecl *Def = VDecl->getDefinition())
12236     if (Def != VDecl &&
12237         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12238         !VDecl->isThisDeclarationADemotedDefinition() &&
12239         checkVarDeclRedefinition(Def, VDecl))
12240       return;
12241 
12242   if (getLangOpts().CPlusPlus) {
12243     // C++ [class.static.data]p4
12244     //   If a static data member is of const integral or const
12245     //   enumeration type, its declaration in the class definition can
12246     //   specify a constant-initializer which shall be an integral
12247     //   constant expression (5.19). In that case, the member can appear
12248     //   in integral constant expressions. The member shall still be
12249     //   defined in a namespace scope if it is used in the program and the
12250     //   namespace scope definition shall not contain an initializer.
12251     //
12252     // We already performed a redefinition check above, but for static
12253     // data members we also need to check whether there was an in-class
12254     // declaration with an initializer.
12255     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12256       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12257           << VDecl->getDeclName();
12258       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12259            diag::note_previous_initializer)
12260           << 0;
12261       return;
12262     }
12263 
12264     if (VDecl->hasLocalStorage())
12265       setFunctionHasBranchProtectedScope();
12266 
12267     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12268       VDecl->setInvalidDecl();
12269       return;
12270     }
12271   }
12272 
12273   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12274   // a kernel function cannot be initialized."
12275   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12276     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12277     VDecl->setInvalidDecl();
12278     return;
12279   }
12280 
12281   // The LoaderUninitialized attribute acts as a definition (of undef).
12282   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12283     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12284     VDecl->setInvalidDecl();
12285     return;
12286   }
12287 
12288   // Get the decls type and save a reference for later, since
12289   // CheckInitializerTypes may change it.
12290   QualType DclT = VDecl->getType(), SavT = DclT;
12291 
12292   // Expressions default to 'id' when we're in a debugger
12293   // and we are assigning it to a variable of Objective-C pointer type.
12294   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12295       Init->getType() == Context.UnknownAnyTy) {
12296     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12297     if (Result.isInvalid()) {
12298       VDecl->setInvalidDecl();
12299       return;
12300     }
12301     Init = Result.get();
12302   }
12303 
12304   // Perform the initialization.
12305   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12306   if (!VDecl->isInvalidDecl()) {
12307     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12308     InitializationKind Kind = InitializationKind::CreateForInit(
12309         VDecl->getLocation(), DirectInit, Init);
12310 
12311     MultiExprArg Args = Init;
12312     if (CXXDirectInit)
12313       Args = MultiExprArg(CXXDirectInit->getExprs(),
12314                           CXXDirectInit->getNumExprs());
12315 
12316     // Try to correct any TypoExprs in the initialization arguments.
12317     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12318       ExprResult Res = CorrectDelayedTyposInExpr(
12319           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12320           [this, Entity, Kind](Expr *E) {
12321             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12322             return Init.Failed() ? ExprError() : E;
12323           });
12324       if (Res.isInvalid()) {
12325         VDecl->setInvalidDecl();
12326       } else if (Res.get() != Args[Idx]) {
12327         Args[Idx] = Res.get();
12328       }
12329     }
12330     if (VDecl->isInvalidDecl())
12331       return;
12332 
12333     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12334                                    /*TopLevelOfInitList=*/false,
12335                                    /*TreatUnavailableAsInvalid=*/false);
12336     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12337     if (Result.isInvalid()) {
12338       // If the provied initializer fails to initialize the var decl,
12339       // we attach a recovery expr for better recovery.
12340       auto RecoveryExpr =
12341           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12342       if (RecoveryExpr.get())
12343         VDecl->setInit(RecoveryExpr.get());
12344       return;
12345     }
12346 
12347     Init = Result.getAs<Expr>();
12348   }
12349 
12350   // Check for self-references within variable initializers.
12351   // Variables declared within a function/method body (except for references)
12352   // are handled by a dataflow analysis.
12353   // This is undefined behavior in C++, but valid in C.
12354   if (getLangOpts().CPlusPlus)
12355     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12356         VDecl->getType()->isReferenceType())
12357       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12358 
12359   // If the type changed, it means we had an incomplete type that was
12360   // completed by the initializer. For example:
12361   //   int ary[] = { 1, 3, 5 };
12362   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12363   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12364     VDecl->setType(DclT);
12365 
12366   if (!VDecl->isInvalidDecl()) {
12367     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12368 
12369     if (VDecl->hasAttr<BlocksAttr>())
12370       checkRetainCycles(VDecl, Init);
12371 
12372     // It is safe to assign a weak reference into a strong variable.
12373     // Although this code can still have problems:
12374     //   id x = self.weakProp;
12375     //   id y = self.weakProp;
12376     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12377     // paths through the function. This should be revisited if
12378     // -Wrepeated-use-of-weak is made flow-sensitive.
12379     if (FunctionScopeInfo *FSI = getCurFunction())
12380       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12381            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12382           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12383                            Init->getBeginLoc()))
12384         FSI->markSafeWeakUse(Init);
12385   }
12386 
12387   // The initialization is usually a full-expression.
12388   //
12389   // FIXME: If this is a braced initialization of an aggregate, it is not
12390   // an expression, and each individual field initializer is a separate
12391   // full-expression. For instance, in:
12392   //
12393   //   struct Temp { ~Temp(); };
12394   //   struct S { S(Temp); };
12395   //   struct T { S a, b; } t = { Temp(), Temp() }
12396   //
12397   // we should destroy the first Temp before constructing the second.
12398   ExprResult Result =
12399       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12400                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12401   if (Result.isInvalid()) {
12402     VDecl->setInvalidDecl();
12403     return;
12404   }
12405   Init = Result.get();
12406 
12407   // Attach the initializer to the decl.
12408   VDecl->setInit(Init);
12409 
12410   if (VDecl->isLocalVarDecl()) {
12411     // Don't check the initializer if the declaration is malformed.
12412     if (VDecl->isInvalidDecl()) {
12413       // do nothing
12414 
12415     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12416     // This is true even in C++ for OpenCL.
12417     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12418       CheckForConstantInitializer(Init, DclT);
12419 
12420     // Otherwise, C++ does not restrict the initializer.
12421     } else if (getLangOpts().CPlusPlus) {
12422       // do nothing
12423 
12424     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12425     // static storage duration shall be constant expressions or string literals.
12426     } else if (VDecl->getStorageClass() == SC_Static) {
12427       CheckForConstantInitializer(Init, DclT);
12428 
12429     // C89 is stricter than C99 for aggregate initializers.
12430     // C89 6.5.7p3: All the expressions [...] in an initializer list
12431     // for an object that has aggregate or union type shall be
12432     // constant expressions.
12433     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12434                isa<InitListExpr>(Init)) {
12435       const Expr *Culprit;
12436       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12437         Diag(Culprit->getExprLoc(),
12438              diag::ext_aggregate_init_not_constant)
12439           << Culprit->getSourceRange();
12440       }
12441     }
12442 
12443     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12444       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12445         if (VDecl->hasLocalStorage())
12446           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12447   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12448              VDecl->getLexicalDeclContext()->isRecord()) {
12449     // This is an in-class initialization for a static data member, e.g.,
12450     //
12451     // struct S {
12452     //   static const int value = 17;
12453     // };
12454 
12455     // C++ [class.mem]p4:
12456     //   A member-declarator can contain a constant-initializer only
12457     //   if it declares a static member (9.4) of const integral or
12458     //   const enumeration type, see 9.4.2.
12459     //
12460     // C++11 [class.static.data]p3:
12461     //   If a non-volatile non-inline const static data member is of integral
12462     //   or enumeration type, its declaration in the class definition can
12463     //   specify a brace-or-equal-initializer in which every initializer-clause
12464     //   that is an assignment-expression is a constant expression. A static
12465     //   data member of literal type can be declared in the class definition
12466     //   with the constexpr specifier; if so, its declaration shall specify a
12467     //   brace-or-equal-initializer in which every initializer-clause that is
12468     //   an assignment-expression is a constant expression.
12469 
12470     // Do nothing on dependent types.
12471     if (DclT->isDependentType()) {
12472 
12473     // Allow any 'static constexpr' members, whether or not they are of literal
12474     // type. We separately check that every constexpr variable is of literal
12475     // type.
12476     } else if (VDecl->isConstexpr()) {
12477 
12478     // Require constness.
12479     } else if (!DclT.isConstQualified()) {
12480       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12481         << Init->getSourceRange();
12482       VDecl->setInvalidDecl();
12483 
12484     // We allow integer constant expressions in all cases.
12485     } else if (DclT->isIntegralOrEnumerationType()) {
12486       // Check whether the expression is a constant expression.
12487       SourceLocation Loc;
12488       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12489         // In C++11, a non-constexpr const static data member with an
12490         // in-class initializer cannot be volatile.
12491         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12492       else if (Init->isValueDependent())
12493         ; // Nothing to check.
12494       else if (Init->isIntegerConstantExpr(Context, &Loc))
12495         ; // Ok, it's an ICE!
12496       else if (Init->getType()->isScopedEnumeralType() &&
12497                Init->isCXX11ConstantExpr(Context))
12498         ; // Ok, it is a scoped-enum constant expression.
12499       else if (Init->isEvaluatable(Context)) {
12500         // If we can constant fold the initializer through heroics, accept it,
12501         // but report this as a use of an extension for -pedantic.
12502         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12503           << Init->getSourceRange();
12504       } else {
12505         // Otherwise, this is some crazy unknown case.  Report the issue at the
12506         // location provided by the isIntegerConstantExpr failed check.
12507         Diag(Loc, diag::err_in_class_initializer_non_constant)
12508           << Init->getSourceRange();
12509         VDecl->setInvalidDecl();
12510       }
12511 
12512     // We allow foldable floating-point constants as an extension.
12513     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12514       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12515       // it anyway and provide a fixit to add the 'constexpr'.
12516       if (getLangOpts().CPlusPlus11) {
12517         Diag(VDecl->getLocation(),
12518              diag::ext_in_class_initializer_float_type_cxx11)
12519             << DclT << Init->getSourceRange();
12520         Diag(VDecl->getBeginLoc(),
12521              diag::note_in_class_initializer_float_type_cxx11)
12522             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12523       } else {
12524         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12525           << DclT << Init->getSourceRange();
12526 
12527         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12528           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12529             << Init->getSourceRange();
12530           VDecl->setInvalidDecl();
12531         }
12532       }
12533 
12534     // Suggest adding 'constexpr' in C++11 for literal types.
12535     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12536       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12537           << DclT << Init->getSourceRange()
12538           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12539       VDecl->setConstexpr(true);
12540 
12541     } else {
12542       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12543         << DclT << Init->getSourceRange();
12544       VDecl->setInvalidDecl();
12545     }
12546   } else if (VDecl->isFileVarDecl()) {
12547     // In C, extern is typically used to avoid tentative definitions when
12548     // declaring variables in headers, but adding an intializer makes it a
12549     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12550     // In C++, extern is often used to give implictly static const variables
12551     // external linkage, so don't warn in that case. If selectany is present,
12552     // this might be header code intended for C and C++ inclusion, so apply the
12553     // C++ rules.
12554     if (VDecl->getStorageClass() == SC_Extern &&
12555         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12556          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12557         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12558         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12559       Diag(VDecl->getLocation(), diag::warn_extern_init);
12560 
12561     // In Microsoft C++ mode, a const variable defined in namespace scope has
12562     // external linkage by default if the variable is declared with
12563     // __declspec(dllexport).
12564     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12565         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12566         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12567       VDecl->setStorageClass(SC_Extern);
12568 
12569     // C99 6.7.8p4. All file scoped initializers need to be constant.
12570     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12571       CheckForConstantInitializer(Init, DclT);
12572   }
12573 
12574   QualType InitType = Init->getType();
12575   if (!InitType.isNull() &&
12576       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12577        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12578     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12579 
12580   // We will represent direct-initialization similarly to copy-initialization:
12581   //    int x(1);  -as-> int x = 1;
12582   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12583   //
12584   // Clients that want to distinguish between the two forms, can check for
12585   // direct initializer using VarDecl::getInitStyle().
12586   // A major benefit is that clients that don't particularly care about which
12587   // exactly form was it (like the CodeGen) can handle both cases without
12588   // special case code.
12589 
12590   // C++ 8.5p11:
12591   // The form of initialization (using parentheses or '=') is generally
12592   // insignificant, but does matter when the entity being initialized has a
12593   // class type.
12594   if (CXXDirectInit) {
12595     assert(DirectInit && "Call-style initializer must be direct init.");
12596     VDecl->setInitStyle(VarDecl::CallInit);
12597   } else if (DirectInit) {
12598     // This must be list-initialization. No other way is direct-initialization.
12599     VDecl->setInitStyle(VarDecl::ListInit);
12600   }
12601 
12602   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12603     DeclsToCheckForDeferredDiags.insert(VDecl);
12604   CheckCompleteVariableDeclaration(VDecl);
12605 }
12606 
12607 /// ActOnInitializerError - Given that there was an error parsing an
12608 /// initializer for the given declaration, try to return to some form
12609 /// of sanity.
12610 void Sema::ActOnInitializerError(Decl *D) {
12611   // Our main concern here is re-establishing invariants like "a
12612   // variable's type is either dependent or complete".
12613   if (!D || D->isInvalidDecl()) return;
12614 
12615   VarDecl *VD = dyn_cast<VarDecl>(D);
12616   if (!VD) return;
12617 
12618   // Bindings are not usable if we can't make sense of the initializer.
12619   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12620     for (auto *BD : DD->bindings())
12621       BD->setInvalidDecl();
12622 
12623   // Auto types are meaningless if we can't make sense of the initializer.
12624   if (VD->getType()->isUndeducedType()) {
12625     D->setInvalidDecl();
12626     return;
12627   }
12628 
12629   QualType Ty = VD->getType();
12630   if (Ty->isDependentType()) return;
12631 
12632   // Require a complete type.
12633   if (RequireCompleteType(VD->getLocation(),
12634                           Context.getBaseElementType(Ty),
12635                           diag::err_typecheck_decl_incomplete_type)) {
12636     VD->setInvalidDecl();
12637     return;
12638   }
12639 
12640   // Require a non-abstract type.
12641   if (RequireNonAbstractType(VD->getLocation(), Ty,
12642                              diag::err_abstract_type_in_decl,
12643                              AbstractVariableType)) {
12644     VD->setInvalidDecl();
12645     return;
12646   }
12647 
12648   // Don't bother complaining about constructors or destructors,
12649   // though.
12650 }
12651 
12652 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12653   // If there is no declaration, there was an error parsing it. Just ignore it.
12654   if (!RealDecl)
12655     return;
12656 
12657   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12658     QualType Type = Var->getType();
12659 
12660     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12661     if (isa<DecompositionDecl>(RealDecl)) {
12662       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12663       Var->setInvalidDecl();
12664       return;
12665     }
12666 
12667     if (Type->isUndeducedType() &&
12668         DeduceVariableDeclarationType(Var, false, nullptr))
12669       return;
12670 
12671     // C++11 [class.static.data]p3: A static data member can be declared with
12672     // the constexpr specifier; if so, its declaration shall specify
12673     // a brace-or-equal-initializer.
12674     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12675     // the definition of a variable [...] or the declaration of a static data
12676     // member.
12677     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12678         !Var->isThisDeclarationADemotedDefinition()) {
12679       if (Var->isStaticDataMember()) {
12680         // C++1z removes the relevant rule; the in-class declaration is always
12681         // a definition there.
12682         if (!getLangOpts().CPlusPlus17 &&
12683             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12684           Diag(Var->getLocation(),
12685                diag::err_constexpr_static_mem_var_requires_init)
12686               << Var;
12687           Var->setInvalidDecl();
12688           return;
12689         }
12690       } else {
12691         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12692         Var->setInvalidDecl();
12693         return;
12694       }
12695     }
12696 
12697     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12698     // be initialized.
12699     if (!Var->isInvalidDecl() &&
12700         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12701         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12702       bool HasConstExprDefaultConstructor = false;
12703       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12704         for (auto *Ctor : RD->ctors()) {
12705           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12706               Ctor->getMethodQualifiers().getAddressSpace() ==
12707                   LangAS::opencl_constant) {
12708             HasConstExprDefaultConstructor = true;
12709           }
12710         }
12711       }
12712       if (!HasConstExprDefaultConstructor) {
12713         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12714         Var->setInvalidDecl();
12715         return;
12716       }
12717     }
12718 
12719     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12720       if (Var->getStorageClass() == SC_Extern) {
12721         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12722             << Var;
12723         Var->setInvalidDecl();
12724         return;
12725       }
12726       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12727                               diag::err_typecheck_decl_incomplete_type)) {
12728         Var->setInvalidDecl();
12729         return;
12730       }
12731       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12732         if (!RD->hasTrivialDefaultConstructor()) {
12733           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12734           Var->setInvalidDecl();
12735           return;
12736         }
12737       }
12738       // The declaration is unitialized, no need for further checks.
12739       return;
12740     }
12741 
12742     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12743     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12744         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12745       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12746                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12747 
12748 
12749     switch (DefKind) {
12750     case VarDecl::Definition:
12751       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12752         break;
12753 
12754       // We have an out-of-line definition of a static data member
12755       // that has an in-class initializer, so we type-check this like
12756       // a declaration.
12757       //
12758       LLVM_FALLTHROUGH;
12759 
12760     case VarDecl::DeclarationOnly:
12761       // It's only a declaration.
12762 
12763       // Block scope. C99 6.7p7: If an identifier for an object is
12764       // declared with no linkage (C99 6.2.2p6), the type for the
12765       // object shall be complete.
12766       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12767           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12768           RequireCompleteType(Var->getLocation(), Type,
12769                               diag::err_typecheck_decl_incomplete_type))
12770         Var->setInvalidDecl();
12771 
12772       // Make sure that the type is not abstract.
12773       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12774           RequireNonAbstractType(Var->getLocation(), Type,
12775                                  diag::err_abstract_type_in_decl,
12776                                  AbstractVariableType))
12777         Var->setInvalidDecl();
12778       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12779           Var->getStorageClass() == SC_PrivateExtern) {
12780         Diag(Var->getLocation(), diag::warn_private_extern);
12781         Diag(Var->getLocation(), diag::note_private_extern);
12782       }
12783 
12784       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12785           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12786         ExternalDeclarations.push_back(Var);
12787 
12788       return;
12789 
12790     case VarDecl::TentativeDefinition:
12791       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12792       // object that has file scope without an initializer, and without a
12793       // storage-class specifier or with the storage-class specifier "static",
12794       // constitutes a tentative definition. Note: A tentative definition with
12795       // external linkage is valid (C99 6.2.2p5).
12796       if (!Var->isInvalidDecl()) {
12797         if (const IncompleteArrayType *ArrayT
12798                                     = Context.getAsIncompleteArrayType(Type)) {
12799           if (RequireCompleteSizedType(
12800                   Var->getLocation(), ArrayT->getElementType(),
12801                   diag::err_array_incomplete_or_sizeless_type))
12802             Var->setInvalidDecl();
12803         } else if (Var->getStorageClass() == SC_Static) {
12804           // C99 6.9.2p3: If the declaration of an identifier for an object is
12805           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12806           // declared type shall not be an incomplete type.
12807           // NOTE: code such as the following
12808           //     static struct s;
12809           //     struct s { int a; };
12810           // is accepted by gcc. Hence here we issue a warning instead of
12811           // an error and we do not invalidate the static declaration.
12812           // NOTE: to avoid multiple warnings, only check the first declaration.
12813           if (Var->isFirstDecl())
12814             RequireCompleteType(Var->getLocation(), Type,
12815                                 diag::ext_typecheck_decl_incomplete_type);
12816         }
12817       }
12818 
12819       // Record the tentative definition; we're done.
12820       if (!Var->isInvalidDecl())
12821         TentativeDefinitions.push_back(Var);
12822       return;
12823     }
12824 
12825     // Provide a specific diagnostic for uninitialized variable
12826     // definitions with incomplete array type.
12827     if (Type->isIncompleteArrayType()) {
12828       Diag(Var->getLocation(),
12829            diag::err_typecheck_incomplete_array_needs_initializer);
12830       Var->setInvalidDecl();
12831       return;
12832     }
12833 
12834     // Provide a specific diagnostic for uninitialized variable
12835     // definitions with reference type.
12836     if (Type->isReferenceType()) {
12837       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12838           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12839       Var->setInvalidDecl();
12840       return;
12841     }
12842 
12843     // Do not attempt to type-check the default initializer for a
12844     // variable with dependent type.
12845     if (Type->isDependentType())
12846       return;
12847 
12848     if (Var->isInvalidDecl())
12849       return;
12850 
12851     if (!Var->hasAttr<AliasAttr>()) {
12852       if (RequireCompleteType(Var->getLocation(),
12853                               Context.getBaseElementType(Type),
12854                               diag::err_typecheck_decl_incomplete_type)) {
12855         Var->setInvalidDecl();
12856         return;
12857       }
12858     } else {
12859       return;
12860     }
12861 
12862     // The variable can not have an abstract class type.
12863     if (RequireNonAbstractType(Var->getLocation(), Type,
12864                                diag::err_abstract_type_in_decl,
12865                                AbstractVariableType)) {
12866       Var->setInvalidDecl();
12867       return;
12868     }
12869 
12870     // Check for jumps past the implicit initializer.  C++0x
12871     // clarifies that this applies to a "variable with automatic
12872     // storage duration", not a "local variable".
12873     // C++11 [stmt.dcl]p3
12874     //   A program that jumps from a point where a variable with automatic
12875     //   storage duration is not in scope to a point where it is in scope is
12876     //   ill-formed unless the variable has scalar type, class type with a
12877     //   trivial default constructor and a trivial destructor, a cv-qualified
12878     //   version of one of these types, or an array of one of the preceding
12879     //   types and is declared without an initializer.
12880     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12881       if (const RecordType *Record
12882             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12883         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12884         // Mark the function (if we're in one) for further checking even if the
12885         // looser rules of C++11 do not require such checks, so that we can
12886         // diagnose incompatibilities with C++98.
12887         if (!CXXRecord->isPOD())
12888           setFunctionHasBranchProtectedScope();
12889       }
12890     }
12891     // In OpenCL, we can't initialize objects in the __local address space,
12892     // even implicitly, so don't synthesize an implicit initializer.
12893     if (getLangOpts().OpenCL &&
12894         Var->getType().getAddressSpace() == LangAS::opencl_local)
12895       return;
12896     // C++03 [dcl.init]p9:
12897     //   If no initializer is specified for an object, and the
12898     //   object is of (possibly cv-qualified) non-POD class type (or
12899     //   array thereof), the object shall be default-initialized; if
12900     //   the object is of const-qualified type, the underlying class
12901     //   type shall have a user-declared default
12902     //   constructor. Otherwise, if no initializer is specified for
12903     //   a non- static object, the object and its subobjects, if
12904     //   any, have an indeterminate initial value); if the object
12905     //   or any of its subobjects are of const-qualified type, the
12906     //   program is ill-formed.
12907     // C++0x [dcl.init]p11:
12908     //   If no initializer is specified for an object, the object is
12909     //   default-initialized; [...].
12910     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12911     InitializationKind Kind
12912       = InitializationKind::CreateDefault(Var->getLocation());
12913 
12914     InitializationSequence InitSeq(*this, Entity, Kind, None);
12915     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12916 
12917     if (Init.get()) {
12918       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12919       // This is important for template substitution.
12920       Var->setInitStyle(VarDecl::CallInit);
12921     } else if (Init.isInvalid()) {
12922       // If default-init fails, attach a recovery-expr initializer to track
12923       // that initialization was attempted and failed.
12924       auto RecoveryExpr =
12925           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12926       if (RecoveryExpr.get())
12927         Var->setInit(RecoveryExpr.get());
12928     }
12929 
12930     CheckCompleteVariableDeclaration(Var);
12931   }
12932 }
12933 
12934 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12935   // If there is no declaration, there was an error parsing it. Ignore it.
12936   if (!D)
12937     return;
12938 
12939   VarDecl *VD = dyn_cast<VarDecl>(D);
12940   if (!VD) {
12941     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12942     D->setInvalidDecl();
12943     return;
12944   }
12945 
12946   VD->setCXXForRangeDecl(true);
12947 
12948   // for-range-declaration cannot be given a storage class specifier.
12949   int Error = -1;
12950   switch (VD->getStorageClass()) {
12951   case SC_None:
12952     break;
12953   case SC_Extern:
12954     Error = 0;
12955     break;
12956   case SC_Static:
12957     Error = 1;
12958     break;
12959   case SC_PrivateExtern:
12960     Error = 2;
12961     break;
12962   case SC_Auto:
12963     Error = 3;
12964     break;
12965   case SC_Register:
12966     Error = 4;
12967     break;
12968   }
12969 
12970   // for-range-declaration cannot be given a storage class specifier con't.
12971   switch (VD->getTSCSpec()) {
12972   case TSCS_thread_local:
12973     Error = 6;
12974     break;
12975   case TSCS___thread:
12976   case TSCS__Thread_local:
12977   case TSCS_unspecified:
12978     break;
12979   }
12980 
12981   if (Error != -1) {
12982     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12983         << VD << Error;
12984     D->setInvalidDecl();
12985   }
12986 }
12987 
12988 StmtResult
12989 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12990                                  IdentifierInfo *Ident,
12991                                  ParsedAttributes &Attrs,
12992                                  SourceLocation AttrEnd) {
12993   // C++1y [stmt.iter]p1:
12994   //   A range-based for statement of the form
12995   //      for ( for-range-identifier : for-range-initializer ) statement
12996   //   is equivalent to
12997   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12998   DeclSpec DS(Attrs.getPool().getFactory());
12999 
13000   const char *PrevSpec;
13001   unsigned DiagID;
13002   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13003                      getPrintingPolicy());
13004 
13005   Declarator D(DS, DeclaratorContext::ForInit);
13006   D.SetIdentifier(Ident, IdentLoc);
13007   D.takeAttributes(Attrs, AttrEnd);
13008 
13009   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13010                 IdentLoc);
13011   Decl *Var = ActOnDeclarator(S, D);
13012   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13013   FinalizeDeclaration(Var);
13014   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13015                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13016 }
13017 
13018 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13019   if (var->isInvalidDecl()) return;
13020 
13021   MaybeAddCUDAConstantAttr(var);
13022 
13023   if (getLangOpts().OpenCL) {
13024     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13025     // initialiser
13026     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13027         !var->hasInit()) {
13028       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13029           << 1 /*Init*/;
13030       var->setInvalidDecl();
13031       return;
13032     }
13033   }
13034 
13035   // In Objective-C, don't allow jumps past the implicit initialization of a
13036   // local retaining variable.
13037   if (getLangOpts().ObjC &&
13038       var->hasLocalStorage()) {
13039     switch (var->getType().getObjCLifetime()) {
13040     case Qualifiers::OCL_None:
13041     case Qualifiers::OCL_ExplicitNone:
13042     case Qualifiers::OCL_Autoreleasing:
13043       break;
13044 
13045     case Qualifiers::OCL_Weak:
13046     case Qualifiers::OCL_Strong:
13047       setFunctionHasBranchProtectedScope();
13048       break;
13049     }
13050   }
13051 
13052   if (var->hasLocalStorage() &&
13053       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13054     setFunctionHasBranchProtectedScope();
13055 
13056   // Warn about externally-visible variables being defined without a
13057   // prior declaration.  We only want to do this for global
13058   // declarations, but we also specifically need to avoid doing it for
13059   // class members because the linkage of an anonymous class can
13060   // change if it's later given a typedef name.
13061   if (var->isThisDeclarationADefinition() &&
13062       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13063       var->isExternallyVisible() && var->hasLinkage() &&
13064       !var->isInline() && !var->getDescribedVarTemplate() &&
13065       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13066       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13067       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13068                                   var->getLocation())) {
13069     // Find a previous declaration that's not a definition.
13070     VarDecl *prev = var->getPreviousDecl();
13071     while (prev && prev->isThisDeclarationADefinition())
13072       prev = prev->getPreviousDecl();
13073 
13074     if (!prev) {
13075       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13076       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13077           << /* variable */ 0;
13078     }
13079   }
13080 
13081   // Cache the result of checking for constant initialization.
13082   Optional<bool> CacheHasConstInit;
13083   const Expr *CacheCulprit = nullptr;
13084   auto checkConstInit = [&]() mutable {
13085     if (!CacheHasConstInit)
13086       CacheHasConstInit = var->getInit()->isConstantInitializer(
13087             Context, var->getType()->isReferenceType(), &CacheCulprit);
13088     return *CacheHasConstInit;
13089   };
13090 
13091   if (var->getTLSKind() == VarDecl::TLS_Static) {
13092     if (var->getType().isDestructedType()) {
13093       // GNU C++98 edits for __thread, [basic.start.term]p3:
13094       //   The type of an object with thread storage duration shall not
13095       //   have a non-trivial destructor.
13096       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13097       if (getLangOpts().CPlusPlus11)
13098         Diag(var->getLocation(), diag::note_use_thread_local);
13099     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13100       if (!checkConstInit()) {
13101         // GNU C++98 edits for __thread, [basic.start.init]p4:
13102         //   An object of thread storage duration shall not require dynamic
13103         //   initialization.
13104         // FIXME: Need strict checking here.
13105         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13106           << CacheCulprit->getSourceRange();
13107         if (getLangOpts().CPlusPlus11)
13108           Diag(var->getLocation(), diag::note_use_thread_local);
13109       }
13110     }
13111   }
13112 
13113 
13114   if (!var->getType()->isStructureType() && var->hasInit() &&
13115       isa<InitListExpr>(var->getInit())) {
13116     const auto *ILE = cast<InitListExpr>(var->getInit());
13117     unsigned NumInits = ILE->getNumInits();
13118     if (NumInits > 2)
13119       for (unsigned I = 0; I < NumInits; ++I) {
13120         const auto *Init = ILE->getInit(I);
13121         if (!Init)
13122           break;
13123         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13124         if (!SL)
13125           break;
13126 
13127         unsigned NumConcat = SL->getNumConcatenated();
13128         // Diagnose missing comma in string array initialization.
13129         // Do not warn when all the elements in the initializer are concatenated
13130         // together. Do not warn for macros too.
13131         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13132           bool OnlyOneMissingComma = true;
13133           for (unsigned J = I + 1; J < NumInits; ++J) {
13134             const auto *Init = ILE->getInit(J);
13135             if (!Init)
13136               break;
13137             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13138             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13139               OnlyOneMissingComma = false;
13140               break;
13141             }
13142           }
13143 
13144           if (OnlyOneMissingComma) {
13145             SmallVector<FixItHint, 1> Hints;
13146             for (unsigned i = 0; i < NumConcat - 1; ++i)
13147               Hints.push_back(FixItHint::CreateInsertion(
13148                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13149 
13150             Diag(SL->getStrTokenLoc(1),
13151                  diag::warn_concatenated_literal_array_init)
13152                 << Hints;
13153             Diag(SL->getBeginLoc(),
13154                  diag::note_concatenated_string_literal_silence);
13155           }
13156           // In any case, stop now.
13157           break;
13158         }
13159       }
13160   }
13161 
13162 
13163   QualType type = var->getType();
13164 
13165   if (var->hasAttr<BlocksAttr>())
13166     getCurFunction()->addByrefBlockVar(var);
13167 
13168   Expr *Init = var->getInit();
13169   bool GlobalStorage = var->hasGlobalStorage();
13170   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13171   QualType baseType = Context.getBaseElementType(type);
13172   bool HasConstInit = true;
13173 
13174   // Check whether the initializer is sufficiently constant.
13175   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13176       !Init->isValueDependent() &&
13177       (GlobalStorage || var->isConstexpr() ||
13178        var->mightBeUsableInConstantExpressions(Context))) {
13179     // If this variable might have a constant initializer or might be usable in
13180     // constant expressions, check whether or not it actually is now.  We can't
13181     // do this lazily, because the result might depend on things that change
13182     // later, such as which constexpr functions happen to be defined.
13183     SmallVector<PartialDiagnosticAt, 8> Notes;
13184     if (!getLangOpts().CPlusPlus11) {
13185       // Prior to C++11, in contexts where a constant initializer is required,
13186       // the set of valid constant initializers is described by syntactic rules
13187       // in [expr.const]p2-6.
13188       // FIXME: Stricter checking for these rules would be useful for constinit /
13189       // -Wglobal-constructors.
13190       HasConstInit = checkConstInit();
13191 
13192       // Compute and cache the constant value, and remember that we have a
13193       // constant initializer.
13194       if (HasConstInit) {
13195         (void)var->checkForConstantInitialization(Notes);
13196         Notes.clear();
13197       } else if (CacheCulprit) {
13198         Notes.emplace_back(CacheCulprit->getExprLoc(),
13199                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13200         Notes.back().second << CacheCulprit->getSourceRange();
13201       }
13202     } else {
13203       // Evaluate the initializer to see if it's a constant initializer.
13204       HasConstInit = var->checkForConstantInitialization(Notes);
13205     }
13206 
13207     if (HasConstInit) {
13208       // FIXME: Consider replacing the initializer with a ConstantExpr.
13209     } else if (var->isConstexpr()) {
13210       SourceLocation DiagLoc = var->getLocation();
13211       // If the note doesn't add any useful information other than a source
13212       // location, fold it into the primary diagnostic.
13213       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13214                                    diag::note_invalid_subexpr_in_const_expr) {
13215         DiagLoc = Notes[0].first;
13216         Notes.clear();
13217       }
13218       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13219           << var << Init->getSourceRange();
13220       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13221         Diag(Notes[I].first, Notes[I].second);
13222     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13223       auto *Attr = var->getAttr<ConstInitAttr>();
13224       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13225           << Init->getSourceRange();
13226       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13227           << Attr->getRange() << Attr->isConstinit();
13228       for (auto &it : Notes)
13229         Diag(it.first, it.second);
13230     } else if (IsGlobal &&
13231                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13232                                            var->getLocation())) {
13233       // Warn about globals which don't have a constant initializer.  Don't
13234       // warn about globals with a non-trivial destructor because we already
13235       // warned about them.
13236       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13237       if (!(RD && !RD->hasTrivialDestructor())) {
13238         // checkConstInit() here permits trivial default initialization even in
13239         // C++11 onwards, where such an initializer is not a constant initializer
13240         // but nonetheless doesn't require a global constructor.
13241         if (!checkConstInit())
13242           Diag(var->getLocation(), diag::warn_global_constructor)
13243               << Init->getSourceRange();
13244       }
13245     }
13246   }
13247 
13248   // Apply section attributes and pragmas to global variables.
13249   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13250       !inTemplateInstantiation()) {
13251     PragmaStack<StringLiteral *> *Stack = nullptr;
13252     int SectionFlags = ASTContext::PSF_Read;
13253     if (var->getType().isConstQualified()) {
13254       if (HasConstInit)
13255         Stack = &ConstSegStack;
13256       else {
13257         Stack = &BSSSegStack;
13258         SectionFlags |= ASTContext::PSF_Write;
13259       }
13260     } else if (var->hasInit() && HasConstInit) {
13261       Stack = &DataSegStack;
13262       SectionFlags |= ASTContext::PSF_Write;
13263     } else {
13264       Stack = &BSSSegStack;
13265       SectionFlags |= ASTContext::PSF_Write;
13266     }
13267     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13268       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13269         SectionFlags |= ASTContext::PSF_Implicit;
13270       UnifySection(SA->getName(), SectionFlags, var);
13271     } else if (Stack->CurrentValue) {
13272       SectionFlags |= ASTContext::PSF_Implicit;
13273       auto SectionName = Stack->CurrentValue->getString();
13274       var->addAttr(SectionAttr::CreateImplicit(
13275           Context, SectionName, Stack->CurrentPragmaLocation,
13276           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13277       if (UnifySection(SectionName, SectionFlags, var))
13278         var->dropAttr<SectionAttr>();
13279     }
13280 
13281     // Apply the init_seg attribute if this has an initializer.  If the
13282     // initializer turns out to not be dynamic, we'll end up ignoring this
13283     // attribute.
13284     if (CurInitSeg && var->getInit())
13285       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13286                                                CurInitSegLoc,
13287                                                AttributeCommonInfo::AS_Pragma));
13288   }
13289 
13290   // All the following checks are C++ only.
13291   if (!getLangOpts().CPlusPlus) {
13292     // If this variable must be emitted, add it as an initializer for the
13293     // current module.
13294     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13295       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13296     return;
13297   }
13298 
13299   // Require the destructor.
13300   if (!type->isDependentType())
13301     if (const RecordType *recordType = baseType->getAs<RecordType>())
13302       FinalizeVarWithDestructor(var, recordType);
13303 
13304   // If this variable must be emitted, add it as an initializer for the current
13305   // module.
13306   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13307     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13308 
13309   // Build the bindings if this is a structured binding declaration.
13310   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13311     CheckCompleteDecompositionDeclaration(DD);
13312 }
13313 
13314 /// Check if VD needs to be dllexport/dllimport due to being in a
13315 /// dllexport/import function.
13316 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13317   assert(VD->isStaticLocal());
13318 
13319   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13320 
13321   // Find outermost function when VD is in lambda function.
13322   while (FD && !getDLLAttr(FD) &&
13323          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13324          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13325     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13326   }
13327 
13328   if (!FD)
13329     return;
13330 
13331   // Static locals inherit dll attributes from their function.
13332   if (Attr *A = getDLLAttr(FD)) {
13333     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13334     NewAttr->setInherited(true);
13335     VD->addAttr(NewAttr);
13336   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13337     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13338     NewAttr->setInherited(true);
13339     VD->addAttr(NewAttr);
13340 
13341     // Export this function to enforce exporting this static variable even
13342     // if it is not used in this compilation unit.
13343     if (!FD->hasAttr<DLLExportAttr>())
13344       FD->addAttr(NewAttr);
13345 
13346   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13347     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13348     NewAttr->setInherited(true);
13349     VD->addAttr(NewAttr);
13350   }
13351 }
13352 
13353 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13354 /// any semantic actions necessary after any initializer has been attached.
13355 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13356   // Note that we are no longer parsing the initializer for this declaration.
13357   ParsingInitForAutoVars.erase(ThisDecl);
13358 
13359   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13360   if (!VD)
13361     return;
13362 
13363   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13364   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13365       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13366     if (PragmaClangBSSSection.Valid)
13367       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13368           Context, PragmaClangBSSSection.SectionName,
13369           PragmaClangBSSSection.PragmaLocation,
13370           AttributeCommonInfo::AS_Pragma));
13371     if (PragmaClangDataSection.Valid)
13372       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13373           Context, PragmaClangDataSection.SectionName,
13374           PragmaClangDataSection.PragmaLocation,
13375           AttributeCommonInfo::AS_Pragma));
13376     if (PragmaClangRodataSection.Valid)
13377       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13378           Context, PragmaClangRodataSection.SectionName,
13379           PragmaClangRodataSection.PragmaLocation,
13380           AttributeCommonInfo::AS_Pragma));
13381     if (PragmaClangRelroSection.Valid)
13382       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13383           Context, PragmaClangRelroSection.SectionName,
13384           PragmaClangRelroSection.PragmaLocation,
13385           AttributeCommonInfo::AS_Pragma));
13386   }
13387 
13388   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13389     for (auto *BD : DD->bindings()) {
13390       FinalizeDeclaration(BD);
13391     }
13392   }
13393 
13394   checkAttributesAfterMerging(*this, *VD);
13395 
13396   // Perform TLS alignment check here after attributes attached to the variable
13397   // which may affect the alignment have been processed. Only perform the check
13398   // if the target has a maximum TLS alignment (zero means no constraints).
13399   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13400     // Protect the check so that it's not performed on dependent types and
13401     // dependent alignments (we can't determine the alignment in that case).
13402     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13403       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13404       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13405         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13406           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13407           << (unsigned)MaxAlignChars.getQuantity();
13408       }
13409     }
13410   }
13411 
13412   if (VD->isStaticLocal())
13413     CheckStaticLocalForDllExport(VD);
13414 
13415   // Perform check for initializers of device-side global variables.
13416   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13417   // 7.5). We must also apply the same checks to all __shared__
13418   // variables whether they are local or not. CUDA also allows
13419   // constant initializers for __constant__ and __device__ variables.
13420   if (getLangOpts().CUDA)
13421     checkAllowedCUDAInitializer(VD);
13422 
13423   // Grab the dllimport or dllexport attribute off of the VarDecl.
13424   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13425 
13426   // Imported static data members cannot be defined out-of-line.
13427   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13428     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13429         VD->isThisDeclarationADefinition()) {
13430       // We allow definitions of dllimport class template static data members
13431       // with a warning.
13432       CXXRecordDecl *Context =
13433         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13434       bool IsClassTemplateMember =
13435           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13436           Context->getDescribedClassTemplate();
13437 
13438       Diag(VD->getLocation(),
13439            IsClassTemplateMember
13440                ? diag::warn_attribute_dllimport_static_field_definition
13441                : diag::err_attribute_dllimport_static_field_definition);
13442       Diag(IA->getLocation(), diag::note_attribute);
13443       if (!IsClassTemplateMember)
13444         VD->setInvalidDecl();
13445     }
13446   }
13447 
13448   // dllimport/dllexport variables cannot be thread local, their TLS index
13449   // isn't exported with the variable.
13450   if (DLLAttr && VD->getTLSKind()) {
13451     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13452     if (F && getDLLAttr(F)) {
13453       assert(VD->isStaticLocal());
13454       // But if this is a static local in a dlimport/dllexport function, the
13455       // function will never be inlined, which means the var would never be
13456       // imported, so having it marked import/export is safe.
13457     } else {
13458       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13459                                                                     << DLLAttr;
13460       VD->setInvalidDecl();
13461     }
13462   }
13463 
13464   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13465     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13466       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13467           << Attr;
13468       VD->dropAttr<UsedAttr>();
13469     }
13470   }
13471   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13472     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13473       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13474           << Attr;
13475       VD->dropAttr<RetainAttr>();
13476     }
13477   }
13478 
13479   const DeclContext *DC = VD->getDeclContext();
13480   // If there's a #pragma GCC visibility in scope, and this isn't a class
13481   // member, set the visibility of this variable.
13482   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13483     AddPushedVisibilityAttribute(VD);
13484 
13485   // FIXME: Warn on unused var template partial specializations.
13486   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13487     MarkUnusedFileScopedDecl(VD);
13488 
13489   // Now we have parsed the initializer and can update the table of magic
13490   // tag values.
13491   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13492       !VD->getType()->isIntegralOrEnumerationType())
13493     return;
13494 
13495   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13496     const Expr *MagicValueExpr = VD->getInit();
13497     if (!MagicValueExpr) {
13498       continue;
13499     }
13500     Optional<llvm::APSInt> MagicValueInt;
13501     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13502       Diag(I->getRange().getBegin(),
13503            diag::err_type_tag_for_datatype_not_ice)
13504         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13505       continue;
13506     }
13507     if (MagicValueInt->getActiveBits() > 64) {
13508       Diag(I->getRange().getBegin(),
13509            diag::err_type_tag_for_datatype_too_large)
13510         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13511       continue;
13512     }
13513     uint64_t MagicValue = MagicValueInt->getZExtValue();
13514     RegisterTypeTagForDatatype(I->getArgumentKind(),
13515                                MagicValue,
13516                                I->getMatchingCType(),
13517                                I->getLayoutCompatible(),
13518                                I->getMustBeNull());
13519   }
13520 }
13521 
13522 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13523   auto *VD = dyn_cast<VarDecl>(DD);
13524   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13525 }
13526 
13527 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13528                                                    ArrayRef<Decl *> Group) {
13529   SmallVector<Decl*, 8> Decls;
13530 
13531   if (DS.isTypeSpecOwned())
13532     Decls.push_back(DS.getRepAsDecl());
13533 
13534   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13535   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13536   bool DiagnosedMultipleDecomps = false;
13537   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13538   bool DiagnosedNonDeducedAuto = false;
13539 
13540   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13541     if (Decl *D = Group[i]) {
13542       // For declarators, there are some additional syntactic-ish checks we need
13543       // to perform.
13544       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13545         if (!FirstDeclaratorInGroup)
13546           FirstDeclaratorInGroup = DD;
13547         if (!FirstDecompDeclaratorInGroup)
13548           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13549         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13550             !hasDeducedAuto(DD))
13551           FirstNonDeducedAutoInGroup = DD;
13552 
13553         if (FirstDeclaratorInGroup != DD) {
13554           // A decomposition declaration cannot be combined with any other
13555           // declaration in the same group.
13556           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13557             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13558                  diag::err_decomp_decl_not_alone)
13559                 << FirstDeclaratorInGroup->getSourceRange()
13560                 << DD->getSourceRange();
13561             DiagnosedMultipleDecomps = true;
13562           }
13563 
13564           // A declarator that uses 'auto' in any way other than to declare a
13565           // variable with a deduced type cannot be combined with any other
13566           // declarator in the same group.
13567           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13568             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13569                  diag::err_auto_non_deduced_not_alone)
13570                 << FirstNonDeducedAutoInGroup->getType()
13571                        ->hasAutoForTrailingReturnType()
13572                 << FirstDeclaratorInGroup->getSourceRange()
13573                 << DD->getSourceRange();
13574             DiagnosedNonDeducedAuto = true;
13575           }
13576         }
13577       }
13578 
13579       Decls.push_back(D);
13580     }
13581   }
13582 
13583   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13584     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13585       handleTagNumbering(Tag, S);
13586       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13587           getLangOpts().CPlusPlus)
13588         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13589     }
13590   }
13591 
13592   return BuildDeclaratorGroup(Decls);
13593 }
13594 
13595 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13596 /// group, performing any necessary semantic checking.
13597 Sema::DeclGroupPtrTy
13598 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13599   // C++14 [dcl.spec.auto]p7: (DR1347)
13600   //   If the type that replaces the placeholder type is not the same in each
13601   //   deduction, the program is ill-formed.
13602   if (Group.size() > 1) {
13603     QualType Deduced;
13604     VarDecl *DeducedDecl = nullptr;
13605     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13606       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13607       if (!D || D->isInvalidDecl())
13608         break;
13609       DeducedType *DT = D->getType()->getContainedDeducedType();
13610       if (!DT || DT->getDeducedType().isNull())
13611         continue;
13612       if (Deduced.isNull()) {
13613         Deduced = DT->getDeducedType();
13614         DeducedDecl = D;
13615       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13616         auto *AT = dyn_cast<AutoType>(DT);
13617         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13618                         diag::err_auto_different_deductions)
13619                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13620                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13621                    << D->getDeclName();
13622         if (DeducedDecl->hasInit())
13623           Dia << DeducedDecl->getInit()->getSourceRange();
13624         if (D->getInit())
13625           Dia << D->getInit()->getSourceRange();
13626         D->setInvalidDecl();
13627         break;
13628       }
13629     }
13630   }
13631 
13632   ActOnDocumentableDecls(Group);
13633 
13634   return DeclGroupPtrTy::make(
13635       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13636 }
13637 
13638 void Sema::ActOnDocumentableDecl(Decl *D) {
13639   ActOnDocumentableDecls(D);
13640 }
13641 
13642 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13643   // Don't parse the comment if Doxygen diagnostics are ignored.
13644   if (Group.empty() || !Group[0])
13645     return;
13646 
13647   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13648                       Group[0]->getLocation()) &&
13649       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13650                       Group[0]->getLocation()))
13651     return;
13652 
13653   if (Group.size() >= 2) {
13654     // This is a decl group.  Normally it will contain only declarations
13655     // produced from declarator list.  But in case we have any definitions or
13656     // additional declaration references:
13657     //   'typedef struct S {} S;'
13658     //   'typedef struct S *S;'
13659     //   'struct S *pS;'
13660     // FinalizeDeclaratorGroup adds these as separate declarations.
13661     Decl *MaybeTagDecl = Group[0];
13662     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13663       Group = Group.slice(1);
13664     }
13665   }
13666 
13667   // FIMXE: We assume every Decl in the group is in the same file.
13668   // This is false when preprocessor constructs the group from decls in
13669   // different files (e. g. macros or #include).
13670   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13671 }
13672 
13673 /// Common checks for a parameter-declaration that should apply to both function
13674 /// parameters and non-type template parameters.
13675 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13676   // Check that there are no default arguments inside the type of this
13677   // parameter.
13678   if (getLangOpts().CPlusPlus)
13679     CheckExtraCXXDefaultArguments(D);
13680 
13681   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13682   if (D.getCXXScopeSpec().isSet()) {
13683     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13684       << D.getCXXScopeSpec().getRange();
13685   }
13686 
13687   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13688   // simple identifier except [...irrelevant cases...].
13689   switch (D.getName().getKind()) {
13690   case UnqualifiedIdKind::IK_Identifier:
13691     break;
13692 
13693   case UnqualifiedIdKind::IK_OperatorFunctionId:
13694   case UnqualifiedIdKind::IK_ConversionFunctionId:
13695   case UnqualifiedIdKind::IK_LiteralOperatorId:
13696   case UnqualifiedIdKind::IK_ConstructorName:
13697   case UnqualifiedIdKind::IK_DestructorName:
13698   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13699   case UnqualifiedIdKind::IK_DeductionGuideName:
13700     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13701       << GetNameForDeclarator(D).getName();
13702     break;
13703 
13704   case UnqualifiedIdKind::IK_TemplateId:
13705   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13706     // GetNameForDeclarator would not produce a useful name in this case.
13707     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13708     break;
13709   }
13710 }
13711 
13712 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13713 /// to introduce parameters into function prototype scope.
13714 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13715   const DeclSpec &DS = D.getDeclSpec();
13716 
13717   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13718 
13719   // C++03 [dcl.stc]p2 also permits 'auto'.
13720   StorageClass SC = SC_None;
13721   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13722     SC = SC_Register;
13723     // In C++11, the 'register' storage class specifier is deprecated.
13724     // In C++17, it is not allowed, but we tolerate it as an extension.
13725     if (getLangOpts().CPlusPlus11) {
13726       Diag(DS.getStorageClassSpecLoc(),
13727            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13728                                      : diag::warn_deprecated_register)
13729         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13730     }
13731   } else if (getLangOpts().CPlusPlus &&
13732              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13733     SC = SC_Auto;
13734   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13735     Diag(DS.getStorageClassSpecLoc(),
13736          diag::err_invalid_storage_class_in_func_decl);
13737     D.getMutableDeclSpec().ClearStorageClassSpecs();
13738   }
13739 
13740   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13741     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13742       << DeclSpec::getSpecifierName(TSCS);
13743   if (DS.isInlineSpecified())
13744     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13745         << getLangOpts().CPlusPlus17;
13746   if (DS.hasConstexprSpecifier())
13747     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13748         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13749 
13750   DiagnoseFunctionSpecifiers(DS);
13751 
13752   CheckFunctionOrTemplateParamDeclarator(S, D);
13753 
13754   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13755   QualType parmDeclType = TInfo->getType();
13756 
13757   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13758   IdentifierInfo *II = D.getIdentifier();
13759   if (II) {
13760     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13761                    ForVisibleRedeclaration);
13762     LookupName(R, S);
13763     if (R.isSingleResult()) {
13764       NamedDecl *PrevDecl = R.getFoundDecl();
13765       if (PrevDecl->isTemplateParameter()) {
13766         // Maybe we will complain about the shadowed template parameter.
13767         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13768         // Just pretend that we didn't see the previous declaration.
13769         PrevDecl = nullptr;
13770       } else if (S->isDeclScope(PrevDecl)) {
13771         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13772         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13773 
13774         // Recover by removing the name
13775         II = nullptr;
13776         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13777         D.setInvalidType(true);
13778       }
13779     }
13780   }
13781 
13782   // Temporarily put parameter variables in the translation unit, not
13783   // the enclosing context.  This prevents them from accidentally
13784   // looking like class members in C++.
13785   ParmVarDecl *New =
13786       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13787                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13788 
13789   if (D.isInvalidType())
13790     New->setInvalidDecl();
13791 
13792   assert(S->isFunctionPrototypeScope());
13793   assert(S->getFunctionPrototypeDepth() >= 1);
13794   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13795                     S->getNextFunctionPrototypeIndex());
13796 
13797   // Add the parameter declaration into this scope.
13798   S->AddDecl(New);
13799   if (II)
13800     IdResolver.AddDecl(New);
13801 
13802   ProcessDeclAttributes(S, New, D);
13803 
13804   if (D.getDeclSpec().isModulePrivateSpecified())
13805     Diag(New->getLocation(), diag::err_module_private_local)
13806         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13807         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13808 
13809   if (New->hasAttr<BlocksAttr>()) {
13810     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13811   }
13812 
13813   if (getLangOpts().OpenCL)
13814     deduceOpenCLAddressSpace(New);
13815 
13816   return New;
13817 }
13818 
13819 /// Synthesizes a variable for a parameter arising from a
13820 /// typedef.
13821 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13822                                               SourceLocation Loc,
13823                                               QualType T) {
13824   /* FIXME: setting StartLoc == Loc.
13825      Would it be worth to modify callers so as to provide proper source
13826      location for the unnamed parameters, embedding the parameter's type? */
13827   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13828                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13829                                            SC_None, nullptr);
13830   Param->setImplicit();
13831   return Param;
13832 }
13833 
13834 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13835   // Don't diagnose unused-parameter errors in template instantiations; we
13836   // will already have done so in the template itself.
13837   if (inTemplateInstantiation())
13838     return;
13839 
13840   for (const ParmVarDecl *Parameter : Parameters) {
13841     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13842         !Parameter->hasAttr<UnusedAttr>()) {
13843       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13844         << Parameter->getDeclName();
13845     }
13846   }
13847 }
13848 
13849 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13850     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13851   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13852     return;
13853 
13854   // Warn if the return value is pass-by-value and larger than the specified
13855   // threshold.
13856   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13857     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13858     if (Size > LangOpts.NumLargeByValueCopy)
13859       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13860   }
13861 
13862   // Warn if any parameter is pass-by-value and larger than the specified
13863   // threshold.
13864   for (const ParmVarDecl *Parameter : Parameters) {
13865     QualType T = Parameter->getType();
13866     if (T->isDependentType() || !T.isPODType(Context))
13867       continue;
13868     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13869     if (Size > LangOpts.NumLargeByValueCopy)
13870       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13871           << Parameter << Size;
13872   }
13873 }
13874 
13875 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13876                                   SourceLocation NameLoc, IdentifierInfo *Name,
13877                                   QualType T, TypeSourceInfo *TSInfo,
13878                                   StorageClass SC) {
13879   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13880   if (getLangOpts().ObjCAutoRefCount &&
13881       T.getObjCLifetime() == Qualifiers::OCL_None &&
13882       T->isObjCLifetimeType()) {
13883 
13884     Qualifiers::ObjCLifetime lifetime;
13885 
13886     // Special cases for arrays:
13887     //   - if it's const, use __unsafe_unretained
13888     //   - otherwise, it's an error
13889     if (T->isArrayType()) {
13890       if (!T.isConstQualified()) {
13891         if (DelayedDiagnostics.shouldDelayDiagnostics())
13892           DelayedDiagnostics.add(
13893               sema::DelayedDiagnostic::makeForbiddenType(
13894               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13895         else
13896           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13897               << TSInfo->getTypeLoc().getSourceRange();
13898       }
13899       lifetime = Qualifiers::OCL_ExplicitNone;
13900     } else {
13901       lifetime = T->getObjCARCImplicitLifetime();
13902     }
13903     T = Context.getLifetimeQualifiedType(T, lifetime);
13904   }
13905 
13906   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13907                                          Context.getAdjustedParameterType(T),
13908                                          TSInfo, SC, nullptr);
13909 
13910   // Make a note if we created a new pack in the scope of a lambda, so that
13911   // we know that references to that pack must also be expanded within the
13912   // lambda scope.
13913   if (New->isParameterPack())
13914     if (auto *LSI = getEnclosingLambda())
13915       LSI->LocalPacks.push_back(New);
13916 
13917   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13918       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13919     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13920                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13921 
13922   // Parameters can not be abstract class types.
13923   // For record types, this is done by the AbstractClassUsageDiagnoser once
13924   // the class has been completely parsed.
13925   if (!CurContext->isRecord() &&
13926       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13927                              AbstractParamType))
13928     New->setInvalidDecl();
13929 
13930   // Parameter declarators cannot be interface types. All ObjC objects are
13931   // passed by reference.
13932   if (T->isObjCObjectType()) {
13933     SourceLocation TypeEndLoc =
13934         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13935     Diag(NameLoc,
13936          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13937       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13938     T = Context.getObjCObjectPointerType(T);
13939     New->setType(T);
13940   }
13941 
13942   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13943   // duration shall not be qualified by an address-space qualifier."
13944   // Since all parameters have automatic store duration, they can not have
13945   // an address space.
13946   if (T.getAddressSpace() != LangAS::Default &&
13947       // OpenCL allows function arguments declared to be an array of a type
13948       // to be qualified with an address space.
13949       !(getLangOpts().OpenCL &&
13950         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13951     Diag(NameLoc, diag::err_arg_with_address_space);
13952     New->setInvalidDecl();
13953   }
13954 
13955   // PPC MMA non-pointer types are not allowed as function argument types.
13956   if (Context.getTargetInfo().getTriple().isPPC64() &&
13957       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13958     New->setInvalidDecl();
13959   }
13960 
13961   return New;
13962 }
13963 
13964 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13965                                            SourceLocation LocAfterDecls) {
13966   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13967 
13968   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13969   // for a K&R function.
13970   if (!FTI.hasPrototype) {
13971     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13972       --i;
13973       if (FTI.Params[i].Param == nullptr) {
13974         SmallString<256> Code;
13975         llvm::raw_svector_ostream(Code)
13976             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13977         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13978             << FTI.Params[i].Ident
13979             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13980 
13981         // Implicitly declare the argument as type 'int' for lack of a better
13982         // type.
13983         AttributeFactory attrs;
13984         DeclSpec DS(attrs);
13985         const char* PrevSpec; // unused
13986         unsigned DiagID; // unused
13987         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13988                            DiagID, Context.getPrintingPolicy());
13989         // Use the identifier location for the type source range.
13990         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13991         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13992         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13993         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13994         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13995       }
13996     }
13997   }
13998 }
13999 
14000 Decl *
14001 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14002                               MultiTemplateParamsArg TemplateParameterLists,
14003                               SkipBodyInfo *SkipBody) {
14004   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14005   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14006   Scope *ParentScope = FnBodyScope->getParent();
14007 
14008   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14009   // we define a non-templated function definition, we will create a declaration
14010   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14011   // The base function declaration will have the equivalent of an `omp declare
14012   // variant` annotation which specifies the mangled definition as a
14013   // specialization function under the OpenMP context defined as part of the
14014   // `omp begin declare variant`.
14015   SmallVector<FunctionDecl *, 4> Bases;
14016   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14017     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14018         ParentScope, D, TemplateParameterLists, Bases);
14019 
14020   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14021   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14022   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14023 
14024   if (!Bases.empty())
14025     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14026 
14027   return Dcl;
14028 }
14029 
14030 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14031   Consumer.HandleInlineFunctionDefinition(D);
14032 }
14033 
14034 static bool
14035 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14036                                 const FunctionDecl *&PossiblePrototype) {
14037   // Don't warn about invalid declarations.
14038   if (FD->isInvalidDecl())
14039     return false;
14040 
14041   // Or declarations that aren't global.
14042   if (!FD->isGlobal())
14043     return false;
14044 
14045   // Don't warn about C++ member functions.
14046   if (isa<CXXMethodDecl>(FD))
14047     return false;
14048 
14049   // Don't warn about 'main'.
14050   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14051     if (IdentifierInfo *II = FD->getIdentifier())
14052       if (II->isStr("main") || II->isStr("efi_main"))
14053         return false;
14054 
14055   // Don't warn about inline functions.
14056   if (FD->isInlined())
14057     return false;
14058 
14059   // Don't warn about function templates.
14060   if (FD->getDescribedFunctionTemplate())
14061     return false;
14062 
14063   // Don't warn about function template specializations.
14064   if (FD->isFunctionTemplateSpecialization())
14065     return false;
14066 
14067   // Don't warn for OpenCL kernels.
14068   if (FD->hasAttr<OpenCLKernelAttr>())
14069     return false;
14070 
14071   // Don't warn on explicitly deleted functions.
14072   if (FD->isDeleted())
14073     return false;
14074 
14075   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14076        Prev; Prev = Prev->getPreviousDecl()) {
14077     // Ignore any declarations that occur in function or method
14078     // scope, because they aren't visible from the header.
14079     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14080       continue;
14081 
14082     PossiblePrototype = Prev;
14083     return Prev->getType()->isFunctionNoProtoType();
14084   }
14085 
14086   return true;
14087 }
14088 
14089 void
14090 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14091                                    const FunctionDecl *EffectiveDefinition,
14092                                    SkipBodyInfo *SkipBody) {
14093   const FunctionDecl *Definition = EffectiveDefinition;
14094   if (!Definition &&
14095       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14096     return;
14097 
14098   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14099     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14100       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14101         // A merged copy of the same function, instantiated as a member of
14102         // the same class, is OK.
14103         if (declaresSameEntity(OrigFD, OrigDef) &&
14104             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14105                                cast<Decl>(FD->getLexicalDeclContext())))
14106           return;
14107       }
14108     }
14109   }
14110 
14111   if (canRedefineFunction(Definition, getLangOpts()))
14112     return;
14113 
14114   // Don't emit an error when this is redefinition of a typo-corrected
14115   // definition.
14116   if (TypoCorrectedFunctionDefinitions.count(Definition))
14117     return;
14118 
14119   // If we don't have a visible definition of the function, and it's inline or
14120   // a template, skip the new definition.
14121   if (SkipBody && !hasVisibleDefinition(Definition) &&
14122       (Definition->getFormalLinkage() == InternalLinkage ||
14123        Definition->isInlined() ||
14124        Definition->getDescribedFunctionTemplate() ||
14125        Definition->getNumTemplateParameterLists())) {
14126     SkipBody->ShouldSkip = true;
14127     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14128     if (auto *TD = Definition->getDescribedFunctionTemplate())
14129       makeMergedDefinitionVisible(TD);
14130     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14131     return;
14132   }
14133 
14134   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14135       Definition->getStorageClass() == SC_Extern)
14136     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14137         << FD << getLangOpts().CPlusPlus;
14138   else
14139     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14140 
14141   Diag(Definition->getLocation(), diag::note_previous_definition);
14142   FD->setInvalidDecl();
14143 }
14144 
14145 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14146                                    Sema &S) {
14147   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14148 
14149   LambdaScopeInfo *LSI = S.PushLambdaScope();
14150   LSI->CallOperator = CallOperator;
14151   LSI->Lambda = LambdaClass;
14152   LSI->ReturnType = CallOperator->getReturnType();
14153   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14154 
14155   if (LCD == LCD_None)
14156     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14157   else if (LCD == LCD_ByCopy)
14158     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14159   else if (LCD == LCD_ByRef)
14160     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14161   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14162 
14163   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14164   LSI->Mutable = !CallOperator->isConst();
14165 
14166   // Add the captures to the LSI so they can be noted as already
14167   // captured within tryCaptureVar.
14168   auto I = LambdaClass->field_begin();
14169   for (const auto &C : LambdaClass->captures()) {
14170     if (C.capturesVariable()) {
14171       VarDecl *VD = C.getCapturedVar();
14172       if (VD->isInitCapture())
14173         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14174       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14175       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14176           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14177           /*EllipsisLoc*/C.isPackExpansion()
14178                          ? C.getEllipsisLoc() : SourceLocation(),
14179           I->getType(), /*Invalid*/false);
14180 
14181     } else if (C.capturesThis()) {
14182       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14183                           C.getCaptureKind() == LCK_StarThis);
14184     } else {
14185       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14186                              I->getType());
14187     }
14188     ++I;
14189   }
14190 }
14191 
14192 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14193                                     SkipBodyInfo *SkipBody) {
14194   if (!D) {
14195     // Parsing the function declaration failed in some way. Push on a fake scope
14196     // anyway so we can try to parse the function body.
14197     PushFunctionScope();
14198     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14199     return D;
14200   }
14201 
14202   FunctionDecl *FD = nullptr;
14203 
14204   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14205     FD = FunTmpl->getTemplatedDecl();
14206   else
14207     FD = cast<FunctionDecl>(D);
14208 
14209   // Do not push if it is a lambda because one is already pushed when building
14210   // the lambda in ActOnStartOfLambdaDefinition().
14211   if (!isLambdaCallOperator(FD))
14212     PushExpressionEvaluationContext(
14213         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14214                           : ExprEvalContexts.back().Context);
14215 
14216   // Check for defining attributes before the check for redefinition.
14217   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14218     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14219     FD->dropAttr<AliasAttr>();
14220     FD->setInvalidDecl();
14221   }
14222   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14223     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14224     FD->dropAttr<IFuncAttr>();
14225     FD->setInvalidDecl();
14226   }
14227 
14228   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14229     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14230         Ctor->isDefaultConstructor() &&
14231         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14232       // If this is an MS ABI dllexport default constructor, instantiate any
14233       // default arguments.
14234       InstantiateDefaultCtorDefaultArgs(Ctor);
14235     }
14236   }
14237 
14238   // See if this is a redefinition. If 'will have body' (or similar) is already
14239   // set, then these checks were already performed when it was set.
14240   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14241       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14242     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14243 
14244     // If we're skipping the body, we're done. Don't enter the scope.
14245     if (SkipBody && SkipBody->ShouldSkip)
14246       return D;
14247   }
14248 
14249   // Mark this function as "will have a body eventually".  This lets users to
14250   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14251   // this function.
14252   FD->setWillHaveBody();
14253 
14254   // If we are instantiating a generic lambda call operator, push
14255   // a LambdaScopeInfo onto the function stack.  But use the information
14256   // that's already been calculated (ActOnLambdaExpr) to prime the current
14257   // LambdaScopeInfo.
14258   // When the template operator is being specialized, the LambdaScopeInfo,
14259   // has to be properly restored so that tryCaptureVariable doesn't try
14260   // and capture any new variables. In addition when calculating potential
14261   // captures during transformation of nested lambdas, it is necessary to
14262   // have the LSI properly restored.
14263   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14264     assert(inTemplateInstantiation() &&
14265            "There should be an active template instantiation on the stack "
14266            "when instantiating a generic lambda!");
14267     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14268   } else {
14269     // Enter a new function scope
14270     PushFunctionScope();
14271   }
14272 
14273   // Builtin functions cannot be defined.
14274   if (unsigned BuiltinID = FD->getBuiltinID()) {
14275     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14276         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14277       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14278       FD->setInvalidDecl();
14279     }
14280   }
14281 
14282   // The return type of a function definition must be complete
14283   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14284   QualType ResultType = FD->getReturnType();
14285   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14286       !FD->isInvalidDecl() &&
14287       RequireCompleteType(FD->getLocation(), ResultType,
14288                           diag::err_func_def_incomplete_result))
14289     FD->setInvalidDecl();
14290 
14291   if (FnBodyScope)
14292     PushDeclContext(FnBodyScope, FD);
14293 
14294   // Check the validity of our function parameters
14295   CheckParmsForFunctionDef(FD->parameters(),
14296                            /*CheckParameterNames=*/true);
14297 
14298   // Add non-parameter declarations already in the function to the current
14299   // scope.
14300   if (FnBodyScope) {
14301     for (Decl *NPD : FD->decls()) {
14302       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14303       if (!NonParmDecl)
14304         continue;
14305       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14306              "parameters should not be in newly created FD yet");
14307 
14308       // If the decl has a name, make it accessible in the current scope.
14309       if (NonParmDecl->getDeclName())
14310         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14311 
14312       // Similarly, dive into enums and fish their constants out, making them
14313       // accessible in this scope.
14314       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14315         for (auto *EI : ED->enumerators())
14316           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14317       }
14318     }
14319   }
14320 
14321   // Introduce our parameters into the function scope
14322   for (auto Param : FD->parameters()) {
14323     Param->setOwningFunction(FD);
14324 
14325     // If this has an identifier, add it to the scope stack.
14326     if (Param->getIdentifier() && FnBodyScope) {
14327       CheckShadow(FnBodyScope, Param);
14328 
14329       PushOnScopeChains(Param, FnBodyScope);
14330     }
14331   }
14332 
14333   // Ensure that the function's exception specification is instantiated.
14334   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14335     ResolveExceptionSpec(D->getLocation(), FPT);
14336 
14337   // dllimport cannot be applied to non-inline function definitions.
14338   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14339       !FD->isTemplateInstantiation()) {
14340     assert(!FD->hasAttr<DLLExportAttr>());
14341     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14342     FD->setInvalidDecl();
14343     return D;
14344   }
14345   // We want to attach documentation to original Decl (which might be
14346   // a function template).
14347   ActOnDocumentableDecl(D);
14348   if (getCurLexicalContext()->isObjCContainer() &&
14349       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14350       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14351     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14352 
14353   return D;
14354 }
14355 
14356 /// Given the set of return statements within a function body,
14357 /// compute the variables that are subject to the named return value
14358 /// optimization.
14359 ///
14360 /// Each of the variables that is subject to the named return value
14361 /// optimization will be marked as NRVO variables in the AST, and any
14362 /// return statement that has a marked NRVO variable as its NRVO candidate can
14363 /// use the named return value optimization.
14364 ///
14365 /// This function applies a very simplistic algorithm for NRVO: if every return
14366 /// statement in the scope of a variable has the same NRVO candidate, that
14367 /// candidate is an NRVO variable.
14368 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14369   ReturnStmt **Returns = Scope->Returns.data();
14370 
14371   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14372     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14373       if (!NRVOCandidate->isNRVOVariable())
14374         Returns[I]->setNRVOCandidate(nullptr);
14375     }
14376   }
14377 }
14378 
14379 bool Sema::canDelayFunctionBody(const Declarator &D) {
14380   // We can't delay parsing the body of a constexpr function template (yet).
14381   if (D.getDeclSpec().hasConstexprSpecifier())
14382     return false;
14383 
14384   // We can't delay parsing the body of a function template with a deduced
14385   // return type (yet).
14386   if (D.getDeclSpec().hasAutoTypeSpec()) {
14387     // If the placeholder introduces a non-deduced trailing return type,
14388     // we can still delay parsing it.
14389     if (D.getNumTypeObjects()) {
14390       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14391       if (Outer.Kind == DeclaratorChunk::Function &&
14392           Outer.Fun.hasTrailingReturnType()) {
14393         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14394         return Ty.isNull() || !Ty->isUndeducedType();
14395       }
14396     }
14397     return false;
14398   }
14399 
14400   return true;
14401 }
14402 
14403 bool Sema::canSkipFunctionBody(Decl *D) {
14404   // We cannot skip the body of a function (or function template) which is
14405   // constexpr, since we may need to evaluate its body in order to parse the
14406   // rest of the file.
14407   // We cannot skip the body of a function with an undeduced return type,
14408   // because any callers of that function need to know the type.
14409   if (const FunctionDecl *FD = D->getAsFunction()) {
14410     if (FD->isConstexpr())
14411       return false;
14412     // We can't simply call Type::isUndeducedType here, because inside template
14413     // auto can be deduced to a dependent type, which is not considered
14414     // "undeduced".
14415     if (FD->getReturnType()->getContainedDeducedType())
14416       return false;
14417   }
14418   return Consumer.shouldSkipFunctionBody(D);
14419 }
14420 
14421 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14422   if (!Decl)
14423     return nullptr;
14424   if (FunctionDecl *FD = Decl->getAsFunction())
14425     FD->setHasSkippedBody();
14426   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14427     MD->setHasSkippedBody();
14428   return Decl;
14429 }
14430 
14431 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14432   return ActOnFinishFunctionBody(D, BodyArg, false);
14433 }
14434 
14435 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14436 /// body.
14437 class ExitFunctionBodyRAII {
14438 public:
14439   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14440   ~ExitFunctionBodyRAII() {
14441     if (!IsLambda)
14442       S.PopExpressionEvaluationContext();
14443   }
14444 
14445 private:
14446   Sema &S;
14447   bool IsLambda = false;
14448 };
14449 
14450 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14451   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14452 
14453   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14454     if (EscapeInfo.count(BD))
14455       return EscapeInfo[BD];
14456 
14457     bool R = false;
14458     const BlockDecl *CurBD = BD;
14459 
14460     do {
14461       R = !CurBD->doesNotEscape();
14462       if (R)
14463         break;
14464       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14465     } while (CurBD);
14466 
14467     return EscapeInfo[BD] = R;
14468   };
14469 
14470   // If the location where 'self' is implicitly retained is inside a escaping
14471   // block, emit a diagnostic.
14472   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14473        S.ImplicitlyRetainedSelfLocs)
14474     if (IsOrNestedInEscapingBlock(P.second))
14475       S.Diag(P.first, diag::warn_implicitly_retains_self)
14476           << FixItHint::CreateInsertion(P.first, "self->");
14477 }
14478 
14479 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14480                                     bool IsInstantiation) {
14481   FunctionScopeInfo *FSI = getCurFunction();
14482   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14483 
14484   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14485     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14486 
14487   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14488   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14489 
14490   if (getLangOpts().Coroutines && FSI->isCoroutine())
14491     CheckCompletedCoroutineBody(FD, Body);
14492 
14493   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14494   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14495   // meant to pop the context added in ActOnStartOfFunctionDef().
14496   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14497 
14498   if (FD) {
14499     FD->setBody(Body);
14500     FD->setWillHaveBody(false);
14501 
14502     if (getLangOpts().CPlusPlus14) {
14503       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14504           FD->getReturnType()->isUndeducedType()) {
14505         // If the function has a deduced result type but contains no 'return'
14506         // statements, the result type as written must be exactly 'auto', and
14507         // the deduced result type is 'void'.
14508         if (!FD->getReturnType()->getAs<AutoType>()) {
14509           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14510               << FD->getReturnType();
14511           FD->setInvalidDecl();
14512         } else {
14513           // Substitute 'void' for the 'auto' in the type.
14514           TypeLoc ResultType = getReturnTypeLoc(FD);
14515           Context.adjustDeducedFunctionResultType(
14516               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14517         }
14518       }
14519     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14520       // In C++11, we don't use 'auto' deduction rules for lambda call
14521       // operators because we don't support return type deduction.
14522       auto *LSI = getCurLambda();
14523       if (LSI->HasImplicitReturnType) {
14524         deduceClosureReturnType(*LSI);
14525 
14526         // C++11 [expr.prim.lambda]p4:
14527         //   [...] if there are no return statements in the compound-statement
14528         //   [the deduced type is] the type void
14529         QualType RetType =
14530             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14531 
14532         // Update the return type to the deduced type.
14533         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14534         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14535                                             Proto->getExtProtoInfo()));
14536       }
14537     }
14538 
14539     // If the function implicitly returns zero (like 'main') or is naked,
14540     // don't complain about missing return statements.
14541     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14542       WP.disableCheckFallThrough();
14543 
14544     // MSVC permits the use of pure specifier (=0) on function definition,
14545     // defined at class scope, warn about this non-standard construct.
14546     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14547       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14548 
14549     if (!FD->isInvalidDecl()) {
14550       // Don't diagnose unused parameters of defaulted or deleted functions.
14551       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14552         DiagnoseUnusedParameters(FD->parameters());
14553       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14554                                              FD->getReturnType(), FD);
14555 
14556       // If this is a structor, we need a vtable.
14557       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14558         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14559       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14560         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14561 
14562       // Try to apply the named return value optimization. We have to check
14563       // if we can do this here because lambdas keep return statements around
14564       // to deduce an implicit return type.
14565       if (FD->getReturnType()->isRecordType() &&
14566           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14567         computeNRVO(Body, FSI);
14568     }
14569 
14570     // GNU warning -Wmissing-prototypes:
14571     //   Warn if a global function is defined without a previous
14572     //   prototype declaration. This warning is issued even if the
14573     //   definition itself provides a prototype. The aim is to detect
14574     //   global functions that fail to be declared in header files.
14575     const FunctionDecl *PossiblePrototype = nullptr;
14576     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14577       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14578 
14579       if (PossiblePrototype) {
14580         // We found a declaration that is not a prototype,
14581         // but that could be a zero-parameter prototype
14582         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14583           TypeLoc TL = TI->getTypeLoc();
14584           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14585             Diag(PossiblePrototype->getLocation(),
14586                  diag::note_declaration_not_a_prototype)
14587                 << (FD->getNumParams() != 0)
14588                 << (FD->getNumParams() == 0
14589                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14590                         : FixItHint{});
14591         }
14592       } else {
14593         // Returns true if the token beginning at this Loc is `const`.
14594         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14595                                 const LangOptions &LangOpts) {
14596           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14597           if (LocInfo.first.isInvalid())
14598             return false;
14599 
14600           bool Invalid = false;
14601           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14602           if (Invalid)
14603             return false;
14604 
14605           if (LocInfo.second > Buffer.size())
14606             return false;
14607 
14608           const char *LexStart = Buffer.data() + LocInfo.second;
14609           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14610 
14611           return StartTok.consume_front("const") &&
14612                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14613                   StartTok.startswith("/*") || StartTok.startswith("//"));
14614         };
14615 
14616         auto findBeginLoc = [&]() {
14617           // If the return type has `const` qualifier, we want to insert
14618           // `static` before `const` (and not before the typename).
14619           if ((FD->getReturnType()->isAnyPointerType() &&
14620                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14621               FD->getReturnType().isConstQualified()) {
14622             // But only do this if we can determine where the `const` is.
14623 
14624             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14625                              getLangOpts()))
14626 
14627               return FD->getBeginLoc();
14628           }
14629           return FD->getTypeSpecStartLoc();
14630         };
14631         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14632             << /* function */ 1
14633             << (FD->getStorageClass() == SC_None
14634                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14635                     : FixItHint{});
14636       }
14637 
14638       // GNU warning -Wstrict-prototypes
14639       //   Warn if K&R function is defined without a previous declaration.
14640       //   This warning is issued only if the definition itself does not provide
14641       //   a prototype. Only K&R definitions do not provide a prototype.
14642       if (!FD->hasWrittenPrototype()) {
14643         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14644         TypeLoc TL = TI->getTypeLoc();
14645         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14646         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14647       }
14648     }
14649 
14650     // Warn on CPUDispatch with an actual body.
14651     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14652       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14653         if (!CmpndBody->body_empty())
14654           Diag(CmpndBody->body_front()->getBeginLoc(),
14655                diag::warn_dispatch_body_ignored);
14656 
14657     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14658       const CXXMethodDecl *KeyFunction;
14659       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14660           MD->isVirtual() &&
14661           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14662           MD == KeyFunction->getCanonicalDecl()) {
14663         // Update the key-function state if necessary for this ABI.
14664         if (FD->isInlined() &&
14665             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14666           Context.setNonKeyFunction(MD);
14667 
14668           // If the newly-chosen key function is already defined, then we
14669           // need to mark the vtable as used retroactively.
14670           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14671           const FunctionDecl *Definition;
14672           if (KeyFunction && KeyFunction->isDefined(Definition))
14673             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14674         } else {
14675           // We just defined they key function; mark the vtable as used.
14676           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14677         }
14678       }
14679     }
14680 
14681     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14682            "Function parsing confused");
14683   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14684     assert(MD == getCurMethodDecl() && "Method parsing confused");
14685     MD->setBody(Body);
14686     if (!MD->isInvalidDecl()) {
14687       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14688                                              MD->getReturnType(), MD);
14689 
14690       if (Body)
14691         computeNRVO(Body, FSI);
14692     }
14693     if (FSI->ObjCShouldCallSuper) {
14694       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14695           << MD->getSelector().getAsString();
14696       FSI->ObjCShouldCallSuper = false;
14697     }
14698     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14699       const ObjCMethodDecl *InitMethod = nullptr;
14700       bool isDesignated =
14701           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14702       assert(isDesignated && InitMethod);
14703       (void)isDesignated;
14704 
14705       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14706         auto IFace = MD->getClassInterface();
14707         if (!IFace)
14708           return false;
14709         auto SuperD = IFace->getSuperClass();
14710         if (!SuperD)
14711           return false;
14712         return SuperD->getIdentifier() ==
14713             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14714       };
14715       // Don't issue this warning for unavailable inits or direct subclasses
14716       // of NSObject.
14717       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14718         Diag(MD->getLocation(),
14719              diag::warn_objc_designated_init_missing_super_call);
14720         Diag(InitMethod->getLocation(),
14721              diag::note_objc_designated_init_marked_here);
14722       }
14723       FSI->ObjCWarnForNoDesignatedInitChain = false;
14724     }
14725     if (FSI->ObjCWarnForNoInitDelegation) {
14726       // Don't issue this warning for unavaialable inits.
14727       if (!MD->isUnavailable())
14728         Diag(MD->getLocation(),
14729              diag::warn_objc_secondary_init_missing_init_call);
14730       FSI->ObjCWarnForNoInitDelegation = false;
14731     }
14732 
14733     diagnoseImplicitlyRetainedSelf(*this);
14734   } else {
14735     // Parsing the function declaration failed in some way. Pop the fake scope
14736     // we pushed on.
14737     PopFunctionScopeInfo(ActivePolicy, dcl);
14738     return nullptr;
14739   }
14740 
14741   if (Body && FSI->HasPotentialAvailabilityViolations)
14742     DiagnoseUnguardedAvailabilityViolations(dcl);
14743 
14744   assert(!FSI->ObjCShouldCallSuper &&
14745          "This should only be set for ObjC methods, which should have been "
14746          "handled in the block above.");
14747 
14748   // Verify and clean out per-function state.
14749   if (Body && (!FD || !FD->isDefaulted())) {
14750     // C++ constructors that have function-try-blocks can't have return
14751     // statements in the handlers of that block. (C++ [except.handle]p14)
14752     // Verify this.
14753     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14754       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14755 
14756     // Verify that gotos and switch cases don't jump into scopes illegally.
14757     if (FSI->NeedsScopeChecking() &&
14758         !PP.isCodeCompletionEnabled())
14759       DiagnoseInvalidJumps(Body);
14760 
14761     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14762       if (!Destructor->getParent()->isDependentType())
14763         CheckDestructor(Destructor);
14764 
14765       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14766                                              Destructor->getParent());
14767     }
14768 
14769     // If any errors have occurred, clear out any temporaries that may have
14770     // been leftover. This ensures that these temporaries won't be picked up for
14771     // deletion in some later function.
14772     if (hasUncompilableErrorOccurred() ||
14773         getDiagnostics().getSuppressAllDiagnostics()) {
14774       DiscardCleanupsInEvaluationContext();
14775     }
14776     if (!hasUncompilableErrorOccurred() &&
14777         !isa<FunctionTemplateDecl>(dcl)) {
14778       // Since the body is valid, issue any analysis-based warnings that are
14779       // enabled.
14780       ActivePolicy = &WP;
14781     }
14782 
14783     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14784         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14785       FD->setInvalidDecl();
14786 
14787     if (FD && FD->hasAttr<NakedAttr>()) {
14788       for (const Stmt *S : Body->children()) {
14789         // Allow local register variables without initializer as they don't
14790         // require prologue.
14791         bool RegisterVariables = false;
14792         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14793           for (const auto *Decl : DS->decls()) {
14794             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14795               RegisterVariables =
14796                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14797               if (!RegisterVariables)
14798                 break;
14799             }
14800           }
14801         }
14802         if (RegisterVariables)
14803           continue;
14804         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14805           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14806           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14807           FD->setInvalidDecl();
14808           break;
14809         }
14810       }
14811     }
14812 
14813     assert(ExprCleanupObjects.size() ==
14814                ExprEvalContexts.back().NumCleanupObjects &&
14815            "Leftover temporaries in function");
14816     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14817     assert(MaybeODRUseExprs.empty() &&
14818            "Leftover expressions for odr-use checking");
14819   }
14820 
14821   if (!IsInstantiation)
14822     PopDeclContext();
14823 
14824   PopFunctionScopeInfo(ActivePolicy, dcl);
14825   // If any errors have occurred, clear out any temporaries that may have
14826   // been leftover. This ensures that these temporaries won't be picked up for
14827   // deletion in some later function.
14828   if (hasUncompilableErrorOccurred()) {
14829     DiscardCleanupsInEvaluationContext();
14830   }
14831 
14832   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14833     auto ES = getEmissionStatus(FD);
14834     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14835         ES == Sema::FunctionEmissionStatus::Unknown)
14836       DeclsToCheckForDeferredDiags.insert(FD);
14837   }
14838 
14839   return dcl;
14840 }
14841 
14842 /// When we finish delayed parsing of an attribute, we must attach it to the
14843 /// relevant Decl.
14844 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14845                                        ParsedAttributes &Attrs) {
14846   // Always attach attributes to the underlying decl.
14847   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14848     D = TD->getTemplatedDecl();
14849   ProcessDeclAttributeList(S, D, Attrs);
14850 
14851   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14852     if (Method->isStatic())
14853       checkThisInStaticMemberFunctionAttributes(Method);
14854 }
14855 
14856 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14857 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14858 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14859                                           IdentifierInfo &II, Scope *S) {
14860   // Find the scope in which the identifier is injected and the corresponding
14861   // DeclContext.
14862   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14863   // In that case, we inject the declaration into the translation unit scope
14864   // instead.
14865   Scope *BlockScope = S;
14866   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14867     BlockScope = BlockScope->getParent();
14868 
14869   Scope *ContextScope = BlockScope;
14870   while (!ContextScope->getEntity())
14871     ContextScope = ContextScope->getParent();
14872   ContextRAII SavedContext(*this, ContextScope->getEntity());
14873 
14874   // Before we produce a declaration for an implicitly defined
14875   // function, see whether there was a locally-scoped declaration of
14876   // this name as a function or variable. If so, use that
14877   // (non-visible) declaration, and complain about it.
14878   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14879   if (ExternCPrev) {
14880     // We still need to inject the function into the enclosing block scope so
14881     // that later (non-call) uses can see it.
14882     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14883 
14884     // C89 footnote 38:
14885     //   If in fact it is not defined as having type "function returning int",
14886     //   the behavior is undefined.
14887     if (!isa<FunctionDecl>(ExternCPrev) ||
14888         !Context.typesAreCompatible(
14889             cast<FunctionDecl>(ExternCPrev)->getType(),
14890             Context.getFunctionNoProtoType(Context.IntTy))) {
14891       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14892           << ExternCPrev << !getLangOpts().C99;
14893       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14894       return ExternCPrev;
14895     }
14896   }
14897 
14898   // Extension in C99.  Legal in C90, but warn about it.
14899   unsigned diag_id;
14900   if (II.getName().startswith("__builtin_"))
14901     diag_id = diag::warn_builtin_unknown;
14902   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14903   else if (getLangOpts().OpenCL)
14904     diag_id = diag::err_opencl_implicit_function_decl;
14905   else if (getLangOpts().C99)
14906     diag_id = diag::ext_implicit_function_decl;
14907   else
14908     diag_id = diag::warn_implicit_function_decl;
14909   Diag(Loc, diag_id) << &II;
14910 
14911   // If we found a prior declaration of this function, don't bother building
14912   // another one. We've already pushed that one into scope, so there's nothing
14913   // more to do.
14914   if (ExternCPrev)
14915     return ExternCPrev;
14916 
14917   // Because typo correction is expensive, only do it if the implicit
14918   // function declaration is going to be treated as an error.
14919   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14920     TypoCorrection Corrected;
14921     DeclFilterCCC<FunctionDecl> CCC{};
14922     if (S && (Corrected =
14923                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14924                               S, nullptr, CCC, CTK_NonError)))
14925       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14926                    /*ErrorRecovery*/false);
14927   }
14928 
14929   // Set a Declarator for the implicit definition: int foo();
14930   const char *Dummy;
14931   AttributeFactory attrFactory;
14932   DeclSpec DS(attrFactory);
14933   unsigned DiagID;
14934   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14935                                   Context.getPrintingPolicy());
14936   (void)Error; // Silence warning.
14937   assert(!Error && "Error setting up implicit decl!");
14938   SourceLocation NoLoc;
14939   Declarator D(DS, DeclaratorContext::Block);
14940   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14941                                              /*IsAmbiguous=*/false,
14942                                              /*LParenLoc=*/NoLoc,
14943                                              /*Params=*/nullptr,
14944                                              /*NumParams=*/0,
14945                                              /*EllipsisLoc=*/NoLoc,
14946                                              /*RParenLoc=*/NoLoc,
14947                                              /*RefQualifierIsLvalueRef=*/true,
14948                                              /*RefQualifierLoc=*/NoLoc,
14949                                              /*MutableLoc=*/NoLoc, EST_None,
14950                                              /*ESpecRange=*/SourceRange(),
14951                                              /*Exceptions=*/nullptr,
14952                                              /*ExceptionRanges=*/nullptr,
14953                                              /*NumExceptions=*/0,
14954                                              /*NoexceptExpr=*/nullptr,
14955                                              /*ExceptionSpecTokens=*/nullptr,
14956                                              /*DeclsInPrototype=*/None, Loc,
14957                                              Loc, D),
14958                 std::move(DS.getAttributes()), SourceLocation());
14959   D.SetIdentifier(&II, Loc);
14960 
14961   // Insert this function into the enclosing block scope.
14962   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14963   FD->setImplicit();
14964 
14965   AddKnownFunctionAttributes(FD);
14966 
14967   return FD;
14968 }
14969 
14970 /// If this function is a C++ replaceable global allocation function
14971 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14972 /// adds any function attributes that we know a priori based on the standard.
14973 ///
14974 /// We need to check for duplicate attributes both here and where user-written
14975 /// attributes are applied to declarations.
14976 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14977     FunctionDecl *FD) {
14978   if (FD->isInvalidDecl())
14979     return;
14980 
14981   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14982       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14983     return;
14984 
14985   Optional<unsigned> AlignmentParam;
14986   bool IsNothrow = false;
14987   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14988     return;
14989 
14990   // C++2a [basic.stc.dynamic.allocation]p4:
14991   //   An allocation function that has a non-throwing exception specification
14992   //   indicates failure by returning a null pointer value. Any other allocation
14993   //   function never returns a null pointer value and indicates failure only by
14994   //   throwing an exception [...]
14995   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14996     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14997 
14998   // C++2a [basic.stc.dynamic.allocation]p2:
14999   //   An allocation function attempts to allocate the requested amount of
15000   //   storage. [...] If the request succeeds, the value returned by a
15001   //   replaceable allocation function is a [...] pointer value p0 different
15002   //   from any previously returned value p1 [...]
15003   //
15004   // However, this particular information is being added in codegen,
15005   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15006 
15007   // C++2a [basic.stc.dynamic.allocation]p2:
15008   //   An allocation function attempts to allocate the requested amount of
15009   //   storage. If it is successful, it returns the address of the start of a
15010   //   block of storage whose length in bytes is at least as large as the
15011   //   requested size.
15012   if (!FD->hasAttr<AllocSizeAttr>()) {
15013     FD->addAttr(AllocSizeAttr::CreateImplicit(
15014         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15015         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15016   }
15017 
15018   // C++2a [basic.stc.dynamic.allocation]p3:
15019   //   For an allocation function [...], the pointer returned on a successful
15020   //   call shall represent the address of storage that is aligned as follows:
15021   //   (3.1) If the allocation function takes an argument of type
15022   //         std​::​align_­val_­t, the storage will have the alignment
15023   //         specified by the value of this argument.
15024   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15025     FD->addAttr(AllocAlignAttr::CreateImplicit(
15026         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15027   }
15028 
15029   // FIXME:
15030   // C++2a [basic.stc.dynamic.allocation]p3:
15031   //   For an allocation function [...], the pointer returned on a successful
15032   //   call shall represent the address of storage that is aligned as follows:
15033   //   (3.2) Otherwise, if the allocation function is named operator new[],
15034   //         the storage is aligned for any object that does not have
15035   //         new-extended alignment ([basic.align]) and is no larger than the
15036   //         requested size.
15037   //   (3.3) Otherwise, the storage is aligned for any object that does not
15038   //         have new-extended alignment and is of the requested size.
15039 }
15040 
15041 /// Adds any function attributes that we know a priori based on
15042 /// the declaration of this function.
15043 ///
15044 /// These attributes can apply both to implicitly-declared builtins
15045 /// (like __builtin___printf_chk) or to library-declared functions
15046 /// like NSLog or printf.
15047 ///
15048 /// We need to check for duplicate attributes both here and where user-written
15049 /// attributes are applied to declarations.
15050 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15051   if (FD->isInvalidDecl())
15052     return;
15053 
15054   // If this is a built-in function, map its builtin attributes to
15055   // actual attributes.
15056   if (unsigned BuiltinID = FD->getBuiltinID()) {
15057     // Handle printf-formatting attributes.
15058     unsigned FormatIdx;
15059     bool HasVAListArg;
15060     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15061       if (!FD->hasAttr<FormatAttr>()) {
15062         const char *fmt = "printf";
15063         unsigned int NumParams = FD->getNumParams();
15064         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15065             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15066           fmt = "NSString";
15067         FD->addAttr(FormatAttr::CreateImplicit(Context,
15068                                                &Context.Idents.get(fmt),
15069                                                FormatIdx+1,
15070                                                HasVAListArg ? 0 : FormatIdx+2,
15071                                                FD->getLocation()));
15072       }
15073     }
15074     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15075                                              HasVAListArg)) {
15076      if (!FD->hasAttr<FormatAttr>())
15077        FD->addAttr(FormatAttr::CreateImplicit(Context,
15078                                               &Context.Idents.get("scanf"),
15079                                               FormatIdx+1,
15080                                               HasVAListArg ? 0 : FormatIdx+2,
15081                                               FD->getLocation()));
15082     }
15083 
15084     // Handle automatically recognized callbacks.
15085     SmallVector<int, 4> Encoding;
15086     if (!FD->hasAttr<CallbackAttr>() &&
15087         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15088       FD->addAttr(CallbackAttr::CreateImplicit(
15089           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15090 
15091     // Mark const if we don't care about errno and that is the only thing
15092     // preventing the function from being const. This allows IRgen to use LLVM
15093     // intrinsics for such functions.
15094     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15095         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15096       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15097 
15098     // We make "fma" on some platforms const because we know it does not set
15099     // errno in those environments even though it could set errno based on the
15100     // C standard.
15101     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15102     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15103         !FD->hasAttr<ConstAttr>()) {
15104       switch (BuiltinID) {
15105       case Builtin::BI__builtin_fma:
15106       case Builtin::BI__builtin_fmaf:
15107       case Builtin::BI__builtin_fmal:
15108       case Builtin::BIfma:
15109       case Builtin::BIfmaf:
15110       case Builtin::BIfmal:
15111         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15112         break;
15113       default:
15114         break;
15115       }
15116     }
15117 
15118     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15119         !FD->hasAttr<ReturnsTwiceAttr>())
15120       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15121                                          FD->getLocation()));
15122     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15123       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15124     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15125       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15126     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15127       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15128     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15129         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15130       // Add the appropriate attribute, depending on the CUDA compilation mode
15131       // and which target the builtin belongs to. For example, during host
15132       // compilation, aux builtins are __device__, while the rest are __host__.
15133       if (getLangOpts().CUDAIsDevice !=
15134           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15135         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15136       else
15137         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15138     }
15139   }
15140 
15141   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15142 
15143   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15144   // throw, add an implicit nothrow attribute to any extern "C" function we come
15145   // across.
15146   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15147       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15148     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15149     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15150       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15151   }
15152 
15153   IdentifierInfo *Name = FD->getIdentifier();
15154   if (!Name)
15155     return;
15156   if ((!getLangOpts().CPlusPlus &&
15157        FD->getDeclContext()->isTranslationUnit()) ||
15158       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15159        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15160        LinkageSpecDecl::lang_c)) {
15161     // Okay: this could be a libc/libm/Objective-C function we know
15162     // about.
15163   } else
15164     return;
15165 
15166   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15167     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15168     // target-specific builtins, perhaps?
15169     if (!FD->hasAttr<FormatAttr>())
15170       FD->addAttr(FormatAttr::CreateImplicit(Context,
15171                                              &Context.Idents.get("printf"), 2,
15172                                              Name->isStr("vasprintf") ? 0 : 3,
15173                                              FD->getLocation()));
15174   }
15175 
15176   if (Name->isStr("__CFStringMakeConstantString")) {
15177     // We already have a __builtin___CFStringMakeConstantString,
15178     // but builds that use -fno-constant-cfstrings don't go through that.
15179     if (!FD->hasAttr<FormatArgAttr>())
15180       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15181                                                 FD->getLocation()));
15182   }
15183 }
15184 
15185 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15186                                     TypeSourceInfo *TInfo) {
15187   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15188   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15189 
15190   if (!TInfo) {
15191     assert(D.isInvalidType() && "no declarator info for valid type");
15192     TInfo = Context.getTrivialTypeSourceInfo(T);
15193   }
15194 
15195   // Scope manipulation handled by caller.
15196   TypedefDecl *NewTD =
15197       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15198                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15199 
15200   // Bail out immediately if we have an invalid declaration.
15201   if (D.isInvalidType()) {
15202     NewTD->setInvalidDecl();
15203     return NewTD;
15204   }
15205 
15206   if (D.getDeclSpec().isModulePrivateSpecified()) {
15207     if (CurContext->isFunctionOrMethod())
15208       Diag(NewTD->getLocation(), diag::err_module_private_local)
15209           << 2 << NewTD
15210           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15211           << FixItHint::CreateRemoval(
15212                  D.getDeclSpec().getModulePrivateSpecLoc());
15213     else
15214       NewTD->setModulePrivate();
15215   }
15216 
15217   // C++ [dcl.typedef]p8:
15218   //   If the typedef declaration defines an unnamed class (or
15219   //   enum), the first typedef-name declared by the declaration
15220   //   to be that class type (or enum type) is used to denote the
15221   //   class type (or enum type) for linkage purposes only.
15222   // We need to check whether the type was declared in the declaration.
15223   switch (D.getDeclSpec().getTypeSpecType()) {
15224   case TST_enum:
15225   case TST_struct:
15226   case TST_interface:
15227   case TST_union:
15228   case TST_class: {
15229     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15230     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15231     break;
15232   }
15233 
15234   default:
15235     break;
15236   }
15237 
15238   return NewTD;
15239 }
15240 
15241 /// Check that this is a valid underlying type for an enum declaration.
15242 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15243   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15244   QualType T = TI->getType();
15245 
15246   if (T->isDependentType())
15247     return false;
15248 
15249   // This doesn't use 'isIntegralType' despite the error message mentioning
15250   // integral type because isIntegralType would also allow enum types in C.
15251   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15252     if (BT->isInteger())
15253       return false;
15254 
15255   if (T->isExtIntType())
15256     return false;
15257 
15258   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15259 }
15260 
15261 /// Check whether this is a valid redeclaration of a previous enumeration.
15262 /// \return true if the redeclaration was invalid.
15263 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15264                                   QualType EnumUnderlyingTy, bool IsFixed,
15265                                   const EnumDecl *Prev) {
15266   if (IsScoped != Prev->isScoped()) {
15267     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15268       << Prev->isScoped();
15269     Diag(Prev->getLocation(), diag::note_previous_declaration);
15270     return true;
15271   }
15272 
15273   if (IsFixed && Prev->isFixed()) {
15274     if (!EnumUnderlyingTy->isDependentType() &&
15275         !Prev->getIntegerType()->isDependentType() &&
15276         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15277                                         Prev->getIntegerType())) {
15278       // TODO: Highlight the underlying type of the redeclaration.
15279       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15280         << EnumUnderlyingTy << Prev->getIntegerType();
15281       Diag(Prev->getLocation(), diag::note_previous_declaration)
15282           << Prev->getIntegerTypeRange();
15283       return true;
15284     }
15285   } else if (IsFixed != Prev->isFixed()) {
15286     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15287       << Prev->isFixed();
15288     Diag(Prev->getLocation(), diag::note_previous_declaration);
15289     return true;
15290   }
15291 
15292   return false;
15293 }
15294 
15295 /// Get diagnostic %select index for tag kind for
15296 /// redeclaration diagnostic message.
15297 /// WARNING: Indexes apply to particular diagnostics only!
15298 ///
15299 /// \returns diagnostic %select index.
15300 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15301   switch (Tag) {
15302   case TTK_Struct: return 0;
15303   case TTK_Interface: return 1;
15304   case TTK_Class:  return 2;
15305   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15306   }
15307 }
15308 
15309 /// Determine if tag kind is a class-key compatible with
15310 /// class for redeclaration (class, struct, or __interface).
15311 ///
15312 /// \returns true iff the tag kind is compatible.
15313 static bool isClassCompatTagKind(TagTypeKind Tag)
15314 {
15315   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15316 }
15317 
15318 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15319                                              TagTypeKind TTK) {
15320   if (isa<TypedefDecl>(PrevDecl))
15321     return NTK_Typedef;
15322   else if (isa<TypeAliasDecl>(PrevDecl))
15323     return NTK_TypeAlias;
15324   else if (isa<ClassTemplateDecl>(PrevDecl))
15325     return NTK_Template;
15326   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15327     return NTK_TypeAliasTemplate;
15328   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15329     return NTK_TemplateTemplateArgument;
15330   switch (TTK) {
15331   case TTK_Struct:
15332   case TTK_Interface:
15333   case TTK_Class:
15334     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15335   case TTK_Union:
15336     return NTK_NonUnion;
15337   case TTK_Enum:
15338     return NTK_NonEnum;
15339   }
15340   llvm_unreachable("invalid TTK");
15341 }
15342 
15343 /// Determine whether a tag with a given kind is acceptable
15344 /// as a redeclaration of the given tag declaration.
15345 ///
15346 /// \returns true if the new tag kind is acceptable, false otherwise.
15347 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15348                                         TagTypeKind NewTag, bool isDefinition,
15349                                         SourceLocation NewTagLoc,
15350                                         const IdentifierInfo *Name) {
15351   // C++ [dcl.type.elab]p3:
15352   //   The class-key or enum keyword present in the
15353   //   elaborated-type-specifier shall agree in kind with the
15354   //   declaration to which the name in the elaborated-type-specifier
15355   //   refers. This rule also applies to the form of
15356   //   elaborated-type-specifier that declares a class-name or
15357   //   friend class since it can be construed as referring to the
15358   //   definition of the class. Thus, in any
15359   //   elaborated-type-specifier, the enum keyword shall be used to
15360   //   refer to an enumeration (7.2), the union class-key shall be
15361   //   used to refer to a union (clause 9), and either the class or
15362   //   struct class-key shall be used to refer to a class (clause 9)
15363   //   declared using the class or struct class-key.
15364   TagTypeKind OldTag = Previous->getTagKind();
15365   if (OldTag != NewTag &&
15366       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15367     return false;
15368 
15369   // Tags are compatible, but we might still want to warn on mismatched tags.
15370   // Non-class tags can't be mismatched at this point.
15371   if (!isClassCompatTagKind(NewTag))
15372     return true;
15373 
15374   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15375   // by our warning analysis. We don't want to warn about mismatches with (eg)
15376   // declarations in system headers that are designed to be specialized, but if
15377   // a user asks us to warn, we should warn if their code contains mismatched
15378   // declarations.
15379   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15380     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15381                                       Loc);
15382   };
15383   if (IsIgnoredLoc(NewTagLoc))
15384     return true;
15385 
15386   auto IsIgnored = [&](const TagDecl *Tag) {
15387     return IsIgnoredLoc(Tag->getLocation());
15388   };
15389   while (IsIgnored(Previous)) {
15390     Previous = Previous->getPreviousDecl();
15391     if (!Previous)
15392       return true;
15393     OldTag = Previous->getTagKind();
15394   }
15395 
15396   bool isTemplate = false;
15397   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15398     isTemplate = Record->getDescribedClassTemplate();
15399 
15400   if (inTemplateInstantiation()) {
15401     if (OldTag != NewTag) {
15402       // In a template instantiation, do not offer fix-its for tag mismatches
15403       // since they usually mess up the template instead of fixing the problem.
15404       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15405         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15406         << getRedeclDiagFromTagKind(OldTag);
15407       // FIXME: Note previous location?
15408     }
15409     return true;
15410   }
15411 
15412   if (isDefinition) {
15413     // On definitions, check all previous tags and issue a fix-it for each
15414     // one that doesn't match the current tag.
15415     if (Previous->getDefinition()) {
15416       // Don't suggest fix-its for redefinitions.
15417       return true;
15418     }
15419 
15420     bool previousMismatch = false;
15421     for (const TagDecl *I : Previous->redecls()) {
15422       if (I->getTagKind() != NewTag) {
15423         // Ignore previous declarations for which the warning was disabled.
15424         if (IsIgnored(I))
15425           continue;
15426 
15427         if (!previousMismatch) {
15428           previousMismatch = true;
15429           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15430             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15431             << getRedeclDiagFromTagKind(I->getTagKind());
15432         }
15433         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15434           << getRedeclDiagFromTagKind(NewTag)
15435           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15436                TypeWithKeyword::getTagTypeKindName(NewTag));
15437       }
15438     }
15439     return true;
15440   }
15441 
15442   // Identify the prevailing tag kind: this is the kind of the definition (if
15443   // there is a non-ignored definition), or otherwise the kind of the prior
15444   // (non-ignored) declaration.
15445   const TagDecl *PrevDef = Previous->getDefinition();
15446   if (PrevDef && IsIgnored(PrevDef))
15447     PrevDef = nullptr;
15448   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15449   if (Redecl->getTagKind() != NewTag) {
15450     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15451       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15452       << getRedeclDiagFromTagKind(OldTag);
15453     Diag(Redecl->getLocation(), diag::note_previous_use);
15454 
15455     // If there is a previous definition, suggest a fix-it.
15456     if (PrevDef) {
15457       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15458         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15459         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15460              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15461     }
15462   }
15463 
15464   return true;
15465 }
15466 
15467 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15468 /// from an outer enclosing namespace or file scope inside a friend declaration.
15469 /// This should provide the commented out code in the following snippet:
15470 ///   namespace N {
15471 ///     struct X;
15472 ///     namespace M {
15473 ///       struct Y { friend struct /*N::*/ X; };
15474 ///     }
15475 ///   }
15476 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15477                                          SourceLocation NameLoc) {
15478   // While the decl is in a namespace, do repeated lookup of that name and see
15479   // if we get the same namespace back.  If we do not, continue until
15480   // translation unit scope, at which point we have a fully qualified NNS.
15481   SmallVector<IdentifierInfo *, 4> Namespaces;
15482   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15483   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15484     // This tag should be declared in a namespace, which can only be enclosed by
15485     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15486     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15487     if (!Namespace || Namespace->isAnonymousNamespace())
15488       return FixItHint();
15489     IdentifierInfo *II = Namespace->getIdentifier();
15490     Namespaces.push_back(II);
15491     NamedDecl *Lookup = SemaRef.LookupSingleName(
15492         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15493     if (Lookup == Namespace)
15494       break;
15495   }
15496 
15497   // Once we have all the namespaces, reverse them to go outermost first, and
15498   // build an NNS.
15499   SmallString<64> Insertion;
15500   llvm::raw_svector_ostream OS(Insertion);
15501   if (DC->isTranslationUnit())
15502     OS << "::";
15503   std::reverse(Namespaces.begin(), Namespaces.end());
15504   for (auto *II : Namespaces)
15505     OS << II->getName() << "::";
15506   return FixItHint::CreateInsertion(NameLoc, Insertion);
15507 }
15508 
15509 /// Determine whether a tag originally declared in context \p OldDC can
15510 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15511 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15512 /// using-declaration).
15513 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15514                                          DeclContext *NewDC) {
15515   OldDC = OldDC->getRedeclContext();
15516   NewDC = NewDC->getRedeclContext();
15517 
15518   if (OldDC->Equals(NewDC))
15519     return true;
15520 
15521   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15522   // encloses the other).
15523   if (S.getLangOpts().MSVCCompat &&
15524       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15525     return true;
15526 
15527   return false;
15528 }
15529 
15530 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15531 /// former case, Name will be non-null.  In the later case, Name will be null.
15532 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15533 /// reference/declaration/definition of a tag.
15534 ///
15535 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15536 /// trailing-type-specifier) other than one in an alias-declaration.
15537 ///
15538 /// \param SkipBody If non-null, will be set to indicate if the caller should
15539 /// skip the definition of this tag and treat it as if it were a declaration.
15540 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15541                      SourceLocation KWLoc, CXXScopeSpec &SS,
15542                      IdentifierInfo *Name, SourceLocation NameLoc,
15543                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15544                      SourceLocation ModulePrivateLoc,
15545                      MultiTemplateParamsArg TemplateParameterLists,
15546                      bool &OwnedDecl, bool &IsDependent,
15547                      SourceLocation ScopedEnumKWLoc,
15548                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15549                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15550                      SkipBodyInfo *SkipBody) {
15551   // If this is not a definition, it must have a name.
15552   IdentifierInfo *OrigName = Name;
15553   assert((Name != nullptr || TUK == TUK_Definition) &&
15554          "Nameless record must be a definition!");
15555   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15556 
15557   OwnedDecl = false;
15558   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15559   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15560 
15561   // FIXME: Check member specializations more carefully.
15562   bool isMemberSpecialization = false;
15563   bool Invalid = false;
15564 
15565   // We only need to do this matching if we have template parameters
15566   // or a scope specifier, which also conveniently avoids this work
15567   // for non-C++ cases.
15568   if (TemplateParameterLists.size() > 0 ||
15569       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15570     if (TemplateParameterList *TemplateParams =
15571             MatchTemplateParametersToScopeSpecifier(
15572                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15573                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15574       if (Kind == TTK_Enum) {
15575         Diag(KWLoc, diag::err_enum_template);
15576         return nullptr;
15577       }
15578 
15579       if (TemplateParams->size() > 0) {
15580         // This is a declaration or definition of a class template (which may
15581         // be a member of another template).
15582 
15583         if (Invalid)
15584           return nullptr;
15585 
15586         OwnedDecl = false;
15587         DeclResult Result = CheckClassTemplate(
15588             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15589             AS, ModulePrivateLoc,
15590             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15591             TemplateParameterLists.data(), SkipBody);
15592         return Result.get();
15593       } else {
15594         // The "template<>" header is extraneous.
15595         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15596           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15597         isMemberSpecialization = true;
15598       }
15599     }
15600 
15601     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15602         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15603       return nullptr;
15604   }
15605 
15606   // Figure out the underlying type if this a enum declaration. We need to do
15607   // this early, because it's needed to detect if this is an incompatible
15608   // redeclaration.
15609   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15610   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15611 
15612   if (Kind == TTK_Enum) {
15613     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15614       // No underlying type explicitly specified, or we failed to parse the
15615       // type, default to int.
15616       EnumUnderlying = Context.IntTy.getTypePtr();
15617     } else if (UnderlyingType.get()) {
15618       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15619       // integral type; any cv-qualification is ignored.
15620       TypeSourceInfo *TI = nullptr;
15621       GetTypeFromParser(UnderlyingType.get(), &TI);
15622       EnumUnderlying = TI;
15623 
15624       if (CheckEnumUnderlyingType(TI))
15625         // Recover by falling back to int.
15626         EnumUnderlying = Context.IntTy.getTypePtr();
15627 
15628       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15629                                           UPPC_FixedUnderlyingType))
15630         EnumUnderlying = Context.IntTy.getTypePtr();
15631 
15632     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15633       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15634       // of 'int'. However, if this is an unfixed forward declaration, don't set
15635       // the underlying type unless the user enables -fms-compatibility. This
15636       // makes unfixed forward declared enums incomplete and is more conforming.
15637       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15638         EnumUnderlying = Context.IntTy.getTypePtr();
15639     }
15640   }
15641 
15642   DeclContext *SearchDC = CurContext;
15643   DeclContext *DC = CurContext;
15644   bool isStdBadAlloc = false;
15645   bool isStdAlignValT = false;
15646 
15647   RedeclarationKind Redecl = forRedeclarationInCurContext();
15648   if (TUK == TUK_Friend || TUK == TUK_Reference)
15649     Redecl = NotForRedeclaration;
15650 
15651   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15652   /// implemented asks for structural equivalence checking, the returned decl
15653   /// here is passed back to the parser, allowing the tag body to be parsed.
15654   auto createTagFromNewDecl = [&]() -> TagDecl * {
15655     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15656     // If there is an identifier, use the location of the identifier as the
15657     // location of the decl, otherwise use the location of the struct/union
15658     // keyword.
15659     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15660     TagDecl *New = nullptr;
15661 
15662     if (Kind == TTK_Enum) {
15663       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15664                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15665       // If this is an undefined enum, bail.
15666       if (TUK != TUK_Definition && !Invalid)
15667         return nullptr;
15668       if (EnumUnderlying) {
15669         EnumDecl *ED = cast<EnumDecl>(New);
15670         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15671           ED->setIntegerTypeSourceInfo(TI);
15672         else
15673           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15674         ED->setPromotionType(ED->getIntegerType());
15675       }
15676     } else { // struct/union
15677       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15678                                nullptr);
15679     }
15680 
15681     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15682       // Add alignment attributes if necessary; these attributes are checked
15683       // when the ASTContext lays out the structure.
15684       //
15685       // It is important for implementing the correct semantics that this
15686       // happen here (in ActOnTag). The #pragma pack stack is
15687       // maintained as a result of parser callbacks which can occur at
15688       // many points during the parsing of a struct declaration (because
15689       // the #pragma tokens are effectively skipped over during the
15690       // parsing of the struct).
15691       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15692         AddAlignmentAttributesForRecord(RD);
15693         AddMsStructLayoutForRecord(RD);
15694       }
15695     }
15696     New->setLexicalDeclContext(CurContext);
15697     return New;
15698   };
15699 
15700   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15701   if (Name && SS.isNotEmpty()) {
15702     // We have a nested-name tag ('struct foo::bar').
15703 
15704     // Check for invalid 'foo::'.
15705     if (SS.isInvalid()) {
15706       Name = nullptr;
15707       goto CreateNewDecl;
15708     }
15709 
15710     // If this is a friend or a reference to a class in a dependent
15711     // context, don't try to make a decl for it.
15712     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15713       DC = computeDeclContext(SS, false);
15714       if (!DC) {
15715         IsDependent = true;
15716         return nullptr;
15717       }
15718     } else {
15719       DC = computeDeclContext(SS, true);
15720       if (!DC) {
15721         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15722           << SS.getRange();
15723         return nullptr;
15724       }
15725     }
15726 
15727     if (RequireCompleteDeclContext(SS, DC))
15728       return nullptr;
15729 
15730     SearchDC = DC;
15731     // Look-up name inside 'foo::'.
15732     LookupQualifiedName(Previous, DC);
15733 
15734     if (Previous.isAmbiguous())
15735       return nullptr;
15736 
15737     if (Previous.empty()) {
15738       // Name lookup did not find anything. However, if the
15739       // nested-name-specifier refers to the current instantiation,
15740       // and that current instantiation has any dependent base
15741       // classes, we might find something at instantiation time: treat
15742       // this as a dependent elaborated-type-specifier.
15743       // But this only makes any sense for reference-like lookups.
15744       if (Previous.wasNotFoundInCurrentInstantiation() &&
15745           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15746         IsDependent = true;
15747         return nullptr;
15748       }
15749 
15750       // A tag 'foo::bar' must already exist.
15751       Diag(NameLoc, diag::err_not_tag_in_scope)
15752         << Kind << Name << DC << SS.getRange();
15753       Name = nullptr;
15754       Invalid = true;
15755       goto CreateNewDecl;
15756     }
15757   } else if (Name) {
15758     // C++14 [class.mem]p14:
15759     //   If T is the name of a class, then each of the following shall have a
15760     //   name different from T:
15761     //    -- every member of class T that is itself a type
15762     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15763         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15764       return nullptr;
15765 
15766     // If this is a named struct, check to see if there was a previous forward
15767     // declaration or definition.
15768     // FIXME: We're looking into outer scopes here, even when we
15769     // shouldn't be. Doing so can result in ambiguities that we
15770     // shouldn't be diagnosing.
15771     LookupName(Previous, S);
15772 
15773     // When declaring or defining a tag, ignore ambiguities introduced
15774     // by types using'ed into this scope.
15775     if (Previous.isAmbiguous() &&
15776         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15777       LookupResult::Filter F = Previous.makeFilter();
15778       while (F.hasNext()) {
15779         NamedDecl *ND = F.next();
15780         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15781                 SearchDC->getRedeclContext()))
15782           F.erase();
15783       }
15784       F.done();
15785     }
15786 
15787     // C++11 [namespace.memdef]p3:
15788     //   If the name in a friend declaration is neither qualified nor
15789     //   a template-id and the declaration is a function or an
15790     //   elaborated-type-specifier, the lookup to determine whether
15791     //   the entity has been previously declared shall not consider
15792     //   any scopes outside the innermost enclosing namespace.
15793     //
15794     // MSVC doesn't implement the above rule for types, so a friend tag
15795     // declaration may be a redeclaration of a type declared in an enclosing
15796     // scope.  They do implement this rule for friend functions.
15797     //
15798     // Does it matter that this should be by scope instead of by
15799     // semantic context?
15800     if (!Previous.empty() && TUK == TUK_Friend) {
15801       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15802       LookupResult::Filter F = Previous.makeFilter();
15803       bool FriendSawTagOutsideEnclosingNamespace = false;
15804       while (F.hasNext()) {
15805         NamedDecl *ND = F.next();
15806         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15807         if (DC->isFileContext() &&
15808             !EnclosingNS->Encloses(ND->getDeclContext())) {
15809           if (getLangOpts().MSVCCompat)
15810             FriendSawTagOutsideEnclosingNamespace = true;
15811           else
15812             F.erase();
15813         }
15814       }
15815       F.done();
15816 
15817       // Diagnose this MSVC extension in the easy case where lookup would have
15818       // unambiguously found something outside the enclosing namespace.
15819       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15820         NamedDecl *ND = Previous.getFoundDecl();
15821         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15822             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15823       }
15824     }
15825 
15826     // Note:  there used to be some attempt at recovery here.
15827     if (Previous.isAmbiguous())
15828       return nullptr;
15829 
15830     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15831       // FIXME: This makes sure that we ignore the contexts associated
15832       // with C structs, unions, and enums when looking for a matching
15833       // tag declaration or definition. See the similar lookup tweak
15834       // in Sema::LookupName; is there a better way to deal with this?
15835       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15836         SearchDC = SearchDC->getParent();
15837     }
15838   }
15839 
15840   if (Previous.isSingleResult() &&
15841       Previous.getFoundDecl()->isTemplateParameter()) {
15842     // Maybe we will complain about the shadowed template parameter.
15843     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15844     // Just pretend that we didn't see the previous declaration.
15845     Previous.clear();
15846   }
15847 
15848   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15849       DC->Equals(getStdNamespace())) {
15850     if (Name->isStr("bad_alloc")) {
15851       // This is a declaration of or a reference to "std::bad_alloc".
15852       isStdBadAlloc = true;
15853 
15854       // If std::bad_alloc has been implicitly declared (but made invisible to
15855       // name lookup), fill in this implicit declaration as the previous
15856       // declaration, so that the declarations get chained appropriately.
15857       if (Previous.empty() && StdBadAlloc)
15858         Previous.addDecl(getStdBadAlloc());
15859     } else if (Name->isStr("align_val_t")) {
15860       isStdAlignValT = true;
15861       if (Previous.empty() && StdAlignValT)
15862         Previous.addDecl(getStdAlignValT());
15863     }
15864   }
15865 
15866   // If we didn't find a previous declaration, and this is a reference
15867   // (or friend reference), move to the correct scope.  In C++, we
15868   // also need to do a redeclaration lookup there, just in case
15869   // there's a shadow friend decl.
15870   if (Name && Previous.empty() &&
15871       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15872     if (Invalid) goto CreateNewDecl;
15873     assert(SS.isEmpty());
15874 
15875     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15876       // C++ [basic.scope.pdecl]p5:
15877       //   -- for an elaborated-type-specifier of the form
15878       //
15879       //          class-key identifier
15880       //
15881       //      if the elaborated-type-specifier is used in the
15882       //      decl-specifier-seq or parameter-declaration-clause of a
15883       //      function defined in namespace scope, the identifier is
15884       //      declared as a class-name in the namespace that contains
15885       //      the declaration; otherwise, except as a friend
15886       //      declaration, the identifier is declared in the smallest
15887       //      non-class, non-function-prototype scope that contains the
15888       //      declaration.
15889       //
15890       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15891       // C structs and unions.
15892       //
15893       // It is an error in C++ to declare (rather than define) an enum
15894       // type, including via an elaborated type specifier.  We'll
15895       // diagnose that later; for now, declare the enum in the same
15896       // scope as we would have picked for any other tag type.
15897       //
15898       // GNU C also supports this behavior as part of its incomplete
15899       // enum types extension, while GNU C++ does not.
15900       //
15901       // Find the context where we'll be declaring the tag.
15902       // FIXME: We would like to maintain the current DeclContext as the
15903       // lexical context,
15904       SearchDC = getTagInjectionContext(SearchDC);
15905 
15906       // Find the scope where we'll be declaring the tag.
15907       S = getTagInjectionScope(S, getLangOpts());
15908     } else {
15909       assert(TUK == TUK_Friend);
15910       // C++ [namespace.memdef]p3:
15911       //   If a friend declaration in a non-local class first declares a
15912       //   class or function, the friend class or function is a member of
15913       //   the innermost enclosing namespace.
15914       SearchDC = SearchDC->getEnclosingNamespaceContext();
15915     }
15916 
15917     // In C++, we need to do a redeclaration lookup to properly
15918     // diagnose some problems.
15919     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15920     // hidden declaration so that we don't get ambiguity errors when using a
15921     // type declared by an elaborated-type-specifier.  In C that is not correct
15922     // and we should instead merge compatible types found by lookup.
15923     if (getLangOpts().CPlusPlus) {
15924       // FIXME: This can perform qualified lookups into function contexts,
15925       // which are meaningless.
15926       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15927       LookupQualifiedName(Previous, SearchDC);
15928     } else {
15929       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15930       LookupName(Previous, S);
15931     }
15932   }
15933 
15934   // If we have a known previous declaration to use, then use it.
15935   if (Previous.empty() && SkipBody && SkipBody->Previous)
15936     Previous.addDecl(SkipBody->Previous);
15937 
15938   if (!Previous.empty()) {
15939     NamedDecl *PrevDecl = Previous.getFoundDecl();
15940     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15941 
15942     // It's okay to have a tag decl in the same scope as a typedef
15943     // which hides a tag decl in the same scope.  Finding this
15944     // insanity with a redeclaration lookup can only actually happen
15945     // in C++.
15946     //
15947     // This is also okay for elaborated-type-specifiers, which is
15948     // technically forbidden by the current standard but which is
15949     // okay according to the likely resolution of an open issue;
15950     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15951     if (getLangOpts().CPlusPlus) {
15952       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15953         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15954           TagDecl *Tag = TT->getDecl();
15955           if (Tag->getDeclName() == Name &&
15956               Tag->getDeclContext()->getRedeclContext()
15957                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15958             PrevDecl = Tag;
15959             Previous.clear();
15960             Previous.addDecl(Tag);
15961             Previous.resolveKind();
15962           }
15963         }
15964       }
15965     }
15966 
15967     // If this is a redeclaration of a using shadow declaration, it must
15968     // declare a tag in the same context. In MSVC mode, we allow a
15969     // redefinition if either context is within the other.
15970     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15971       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15972       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15973           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15974           !(OldTag && isAcceptableTagRedeclContext(
15975                           *this, OldTag->getDeclContext(), SearchDC))) {
15976         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15977         Diag(Shadow->getTargetDecl()->getLocation(),
15978              diag::note_using_decl_target);
15979         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
15980             << 0;
15981         // Recover by ignoring the old declaration.
15982         Previous.clear();
15983         goto CreateNewDecl;
15984       }
15985     }
15986 
15987     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15988       // If this is a use of a previous tag, or if the tag is already declared
15989       // in the same scope (so that the definition/declaration completes or
15990       // rementions the tag), reuse the decl.
15991       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15992           isDeclInScope(DirectPrevDecl, SearchDC, S,
15993                         SS.isNotEmpty() || isMemberSpecialization)) {
15994         // Make sure that this wasn't declared as an enum and now used as a
15995         // struct or something similar.
15996         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15997                                           TUK == TUK_Definition, KWLoc,
15998                                           Name)) {
15999           bool SafeToContinue
16000             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16001                Kind != TTK_Enum);
16002           if (SafeToContinue)
16003             Diag(KWLoc, diag::err_use_with_wrong_tag)
16004               << Name
16005               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16006                                               PrevTagDecl->getKindName());
16007           else
16008             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16009           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16010 
16011           if (SafeToContinue)
16012             Kind = PrevTagDecl->getTagKind();
16013           else {
16014             // Recover by making this an anonymous redefinition.
16015             Name = nullptr;
16016             Previous.clear();
16017             Invalid = true;
16018           }
16019         }
16020 
16021         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16022           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16023           if (TUK == TUK_Reference || TUK == TUK_Friend)
16024             return PrevTagDecl;
16025 
16026           QualType EnumUnderlyingTy;
16027           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16028             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16029           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16030             EnumUnderlyingTy = QualType(T, 0);
16031 
16032           // All conflicts with previous declarations are recovered by
16033           // returning the previous declaration, unless this is a definition,
16034           // in which case we want the caller to bail out.
16035           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16036                                      ScopedEnum, EnumUnderlyingTy,
16037                                      IsFixed, PrevEnum))
16038             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16039         }
16040 
16041         // C++11 [class.mem]p1:
16042         //   A member shall not be declared twice in the member-specification,
16043         //   except that a nested class or member class template can be declared
16044         //   and then later defined.
16045         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16046             S->isDeclScope(PrevDecl)) {
16047           Diag(NameLoc, diag::ext_member_redeclared);
16048           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16049         }
16050 
16051         if (!Invalid) {
16052           // If this is a use, just return the declaration we found, unless
16053           // we have attributes.
16054           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16055             if (!Attrs.empty()) {
16056               // FIXME: Diagnose these attributes. For now, we create a new
16057               // declaration to hold them.
16058             } else if (TUK == TUK_Reference &&
16059                        (PrevTagDecl->getFriendObjectKind() ==
16060                             Decl::FOK_Undeclared ||
16061                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16062                        SS.isEmpty()) {
16063               // This declaration is a reference to an existing entity, but
16064               // has different visibility from that entity: it either makes
16065               // a friend visible or it makes a type visible in a new module.
16066               // In either case, create a new declaration. We only do this if
16067               // the declaration would have meant the same thing if no prior
16068               // declaration were found, that is, if it was found in the same
16069               // scope where we would have injected a declaration.
16070               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16071                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16072                 return PrevTagDecl;
16073               // This is in the injected scope, create a new declaration in
16074               // that scope.
16075               S = getTagInjectionScope(S, getLangOpts());
16076             } else {
16077               return PrevTagDecl;
16078             }
16079           }
16080 
16081           // Diagnose attempts to redefine a tag.
16082           if (TUK == TUK_Definition) {
16083             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16084               // If we're defining a specialization and the previous definition
16085               // is from an implicit instantiation, don't emit an error
16086               // here; we'll catch this in the general case below.
16087               bool IsExplicitSpecializationAfterInstantiation = false;
16088               if (isMemberSpecialization) {
16089                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16090                   IsExplicitSpecializationAfterInstantiation =
16091                     RD->getTemplateSpecializationKind() !=
16092                     TSK_ExplicitSpecialization;
16093                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16094                   IsExplicitSpecializationAfterInstantiation =
16095                     ED->getTemplateSpecializationKind() !=
16096                     TSK_ExplicitSpecialization;
16097               }
16098 
16099               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16100               // not keep more that one definition around (merge them). However,
16101               // ensure the decl passes the structural compatibility check in
16102               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16103               NamedDecl *Hidden = nullptr;
16104               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16105                 // There is a definition of this tag, but it is not visible. We
16106                 // explicitly make use of C++'s one definition rule here, and
16107                 // assume that this definition is identical to the hidden one
16108                 // we already have. Make the existing definition visible and
16109                 // use it in place of this one.
16110                 if (!getLangOpts().CPlusPlus) {
16111                   // Postpone making the old definition visible until after we
16112                   // complete parsing the new one and do the structural
16113                   // comparison.
16114                   SkipBody->CheckSameAsPrevious = true;
16115                   SkipBody->New = createTagFromNewDecl();
16116                   SkipBody->Previous = Def;
16117                   return Def;
16118                 } else {
16119                   SkipBody->ShouldSkip = true;
16120                   SkipBody->Previous = Def;
16121                   makeMergedDefinitionVisible(Hidden);
16122                   // Carry on and handle it like a normal definition. We'll
16123                   // skip starting the definitiion later.
16124                 }
16125               } else if (!IsExplicitSpecializationAfterInstantiation) {
16126                 // A redeclaration in function prototype scope in C isn't
16127                 // visible elsewhere, so merely issue a warning.
16128                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16129                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16130                 else
16131                   Diag(NameLoc, diag::err_redefinition) << Name;
16132                 notePreviousDefinition(Def,
16133                                        NameLoc.isValid() ? NameLoc : KWLoc);
16134                 // If this is a redefinition, recover by making this
16135                 // struct be anonymous, which will make any later
16136                 // references get the previous definition.
16137                 Name = nullptr;
16138                 Previous.clear();
16139                 Invalid = true;
16140               }
16141             } else {
16142               // If the type is currently being defined, complain
16143               // about a nested redefinition.
16144               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16145               if (TD->isBeingDefined()) {
16146                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16147                 Diag(PrevTagDecl->getLocation(),
16148                      diag::note_previous_definition);
16149                 Name = nullptr;
16150                 Previous.clear();
16151                 Invalid = true;
16152               }
16153             }
16154 
16155             // Okay, this is definition of a previously declared or referenced
16156             // tag. We're going to create a new Decl for it.
16157           }
16158 
16159           // Okay, we're going to make a redeclaration.  If this is some kind
16160           // of reference, make sure we build the redeclaration in the same DC
16161           // as the original, and ignore the current access specifier.
16162           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16163             SearchDC = PrevTagDecl->getDeclContext();
16164             AS = AS_none;
16165           }
16166         }
16167         // If we get here we have (another) forward declaration or we
16168         // have a definition.  Just create a new decl.
16169 
16170       } else {
16171         // If we get here, this is a definition of a new tag type in a nested
16172         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16173         // new decl/type.  We set PrevDecl to NULL so that the entities
16174         // have distinct types.
16175         Previous.clear();
16176       }
16177       // If we get here, we're going to create a new Decl. If PrevDecl
16178       // is non-NULL, it's a definition of the tag declared by
16179       // PrevDecl. If it's NULL, we have a new definition.
16180 
16181     // Otherwise, PrevDecl is not a tag, but was found with tag
16182     // lookup.  This is only actually possible in C++, where a few
16183     // things like templates still live in the tag namespace.
16184     } else {
16185       // Use a better diagnostic if an elaborated-type-specifier
16186       // found the wrong kind of type on the first
16187       // (non-redeclaration) lookup.
16188       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16189           !Previous.isForRedeclaration()) {
16190         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16191         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16192                                                        << Kind;
16193         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16194         Invalid = true;
16195 
16196       // Otherwise, only diagnose if the declaration is in scope.
16197       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16198                                 SS.isNotEmpty() || isMemberSpecialization)) {
16199         // do nothing
16200 
16201       // Diagnose implicit declarations introduced by elaborated types.
16202       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16203         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16204         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16205         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16206         Invalid = true;
16207 
16208       // Otherwise it's a declaration.  Call out a particularly common
16209       // case here.
16210       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16211         unsigned Kind = 0;
16212         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16213         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16214           << Name << Kind << TND->getUnderlyingType();
16215         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16216         Invalid = true;
16217 
16218       // Otherwise, diagnose.
16219       } else {
16220         // The tag name clashes with something else in the target scope,
16221         // issue an error and recover by making this tag be anonymous.
16222         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16223         notePreviousDefinition(PrevDecl, NameLoc);
16224         Name = nullptr;
16225         Invalid = true;
16226       }
16227 
16228       // The existing declaration isn't relevant to us; we're in a
16229       // new scope, so clear out the previous declaration.
16230       Previous.clear();
16231     }
16232   }
16233 
16234 CreateNewDecl:
16235 
16236   TagDecl *PrevDecl = nullptr;
16237   if (Previous.isSingleResult())
16238     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16239 
16240   // If there is an identifier, use the location of the identifier as the
16241   // location of the decl, otherwise use the location of the struct/union
16242   // keyword.
16243   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16244 
16245   // Otherwise, create a new declaration. If there is a previous
16246   // declaration of the same entity, the two will be linked via
16247   // PrevDecl.
16248   TagDecl *New;
16249 
16250   if (Kind == TTK_Enum) {
16251     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16252     // enum X { A, B, C } D;    D should chain to X.
16253     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16254                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16255                            ScopedEnumUsesClassTag, IsFixed);
16256 
16257     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16258       StdAlignValT = cast<EnumDecl>(New);
16259 
16260     // If this is an undefined enum, warn.
16261     if (TUK != TUK_Definition && !Invalid) {
16262       TagDecl *Def;
16263       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16264         // C++0x: 7.2p2: opaque-enum-declaration.
16265         // Conflicts are diagnosed above. Do nothing.
16266       }
16267       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16268         Diag(Loc, diag::ext_forward_ref_enum_def)
16269           << New;
16270         Diag(Def->getLocation(), diag::note_previous_definition);
16271       } else {
16272         unsigned DiagID = diag::ext_forward_ref_enum;
16273         if (getLangOpts().MSVCCompat)
16274           DiagID = diag::ext_ms_forward_ref_enum;
16275         else if (getLangOpts().CPlusPlus)
16276           DiagID = diag::err_forward_ref_enum;
16277         Diag(Loc, DiagID);
16278       }
16279     }
16280 
16281     if (EnumUnderlying) {
16282       EnumDecl *ED = cast<EnumDecl>(New);
16283       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16284         ED->setIntegerTypeSourceInfo(TI);
16285       else
16286         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16287       ED->setPromotionType(ED->getIntegerType());
16288       assert(ED->isComplete() && "enum with type should be complete");
16289     }
16290   } else {
16291     // struct/union/class
16292 
16293     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16294     // struct X { int A; } D;    D should chain to X.
16295     if (getLangOpts().CPlusPlus) {
16296       // FIXME: Look for a way to use RecordDecl for simple structs.
16297       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16298                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16299 
16300       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16301         StdBadAlloc = cast<CXXRecordDecl>(New);
16302     } else
16303       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16304                                cast_or_null<RecordDecl>(PrevDecl));
16305   }
16306 
16307   // C++11 [dcl.type]p3:
16308   //   A type-specifier-seq shall not define a class or enumeration [...].
16309   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16310       TUK == TUK_Definition) {
16311     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16312       << Context.getTagDeclType(New);
16313     Invalid = true;
16314   }
16315 
16316   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16317       DC->getDeclKind() == Decl::Enum) {
16318     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16319       << Context.getTagDeclType(New);
16320     Invalid = true;
16321   }
16322 
16323   // Maybe add qualifier info.
16324   if (SS.isNotEmpty()) {
16325     if (SS.isSet()) {
16326       // If this is either a declaration or a definition, check the
16327       // nested-name-specifier against the current context.
16328       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16329           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16330                                        isMemberSpecialization))
16331         Invalid = true;
16332 
16333       New->setQualifierInfo(SS.getWithLocInContext(Context));
16334       if (TemplateParameterLists.size() > 0) {
16335         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16336       }
16337     }
16338     else
16339       Invalid = true;
16340   }
16341 
16342   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16343     // Add alignment attributes if necessary; these attributes are checked when
16344     // the ASTContext lays out the structure.
16345     //
16346     // It is important for implementing the correct semantics that this
16347     // happen here (in ActOnTag). The #pragma pack stack is
16348     // maintained as a result of parser callbacks which can occur at
16349     // many points during the parsing of a struct declaration (because
16350     // the #pragma tokens are effectively skipped over during the
16351     // parsing of the struct).
16352     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16353       AddAlignmentAttributesForRecord(RD);
16354       AddMsStructLayoutForRecord(RD);
16355     }
16356   }
16357 
16358   if (ModulePrivateLoc.isValid()) {
16359     if (isMemberSpecialization)
16360       Diag(New->getLocation(), diag::err_module_private_specialization)
16361         << 2
16362         << FixItHint::CreateRemoval(ModulePrivateLoc);
16363     // __module_private__ does not apply to local classes. However, we only
16364     // diagnose this as an error when the declaration specifiers are
16365     // freestanding. Here, we just ignore the __module_private__.
16366     else if (!SearchDC->isFunctionOrMethod())
16367       New->setModulePrivate();
16368   }
16369 
16370   // If this is a specialization of a member class (of a class template),
16371   // check the specialization.
16372   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16373     Invalid = true;
16374 
16375   // If we're declaring or defining a tag in function prototype scope in C,
16376   // note that this type can only be used within the function and add it to
16377   // the list of decls to inject into the function definition scope.
16378   if ((Name || Kind == TTK_Enum) &&
16379       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16380     if (getLangOpts().CPlusPlus) {
16381       // C++ [dcl.fct]p6:
16382       //   Types shall not be defined in return or parameter types.
16383       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16384         Diag(Loc, diag::err_type_defined_in_param_type)
16385             << Name;
16386         Invalid = true;
16387       }
16388     } else if (!PrevDecl) {
16389       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16390     }
16391   }
16392 
16393   if (Invalid)
16394     New->setInvalidDecl();
16395 
16396   // Set the lexical context. If the tag has a C++ scope specifier, the
16397   // lexical context will be different from the semantic context.
16398   New->setLexicalDeclContext(CurContext);
16399 
16400   // Mark this as a friend decl if applicable.
16401   // In Microsoft mode, a friend declaration also acts as a forward
16402   // declaration so we always pass true to setObjectOfFriendDecl to make
16403   // the tag name visible.
16404   if (TUK == TUK_Friend)
16405     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16406 
16407   // Set the access specifier.
16408   if (!Invalid && SearchDC->isRecord())
16409     SetMemberAccessSpecifier(New, PrevDecl, AS);
16410 
16411   if (PrevDecl)
16412     CheckRedeclarationModuleOwnership(New, PrevDecl);
16413 
16414   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16415     New->startDefinition();
16416 
16417   ProcessDeclAttributeList(S, New, Attrs);
16418   AddPragmaAttributes(S, New);
16419 
16420   // If this has an identifier, add it to the scope stack.
16421   if (TUK == TUK_Friend) {
16422     // We might be replacing an existing declaration in the lookup tables;
16423     // if so, borrow its access specifier.
16424     if (PrevDecl)
16425       New->setAccess(PrevDecl->getAccess());
16426 
16427     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16428     DC->makeDeclVisibleInContext(New);
16429     if (Name) // can be null along some error paths
16430       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16431         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16432   } else if (Name) {
16433     S = getNonFieldDeclScope(S);
16434     PushOnScopeChains(New, S, true);
16435   } else {
16436     CurContext->addDecl(New);
16437   }
16438 
16439   // If this is the C FILE type, notify the AST context.
16440   if (IdentifierInfo *II = New->getIdentifier())
16441     if (!New->isInvalidDecl() &&
16442         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16443         II->isStr("FILE"))
16444       Context.setFILEDecl(New);
16445 
16446   if (PrevDecl)
16447     mergeDeclAttributes(New, PrevDecl);
16448 
16449   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16450     inferGslOwnerPointerAttribute(CXXRD);
16451 
16452   // If there's a #pragma GCC visibility in scope, set the visibility of this
16453   // record.
16454   AddPushedVisibilityAttribute(New);
16455 
16456   if (isMemberSpecialization && !New->isInvalidDecl())
16457     CompleteMemberSpecialization(New, Previous);
16458 
16459   OwnedDecl = true;
16460   // In C++, don't return an invalid declaration. We can't recover well from
16461   // the cases where we make the type anonymous.
16462   if (Invalid && getLangOpts().CPlusPlus) {
16463     if (New->isBeingDefined())
16464       if (auto RD = dyn_cast<RecordDecl>(New))
16465         RD->completeDefinition();
16466     return nullptr;
16467   } else if (SkipBody && SkipBody->ShouldSkip) {
16468     return SkipBody->Previous;
16469   } else {
16470     return New;
16471   }
16472 }
16473 
16474 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16475   AdjustDeclIfTemplate(TagD);
16476   TagDecl *Tag = cast<TagDecl>(TagD);
16477 
16478   // Enter the tag context.
16479   PushDeclContext(S, Tag);
16480 
16481   ActOnDocumentableDecl(TagD);
16482 
16483   // If there's a #pragma GCC visibility in scope, set the visibility of this
16484   // record.
16485   AddPushedVisibilityAttribute(Tag);
16486 }
16487 
16488 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16489                                     SkipBodyInfo &SkipBody) {
16490   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16491     return false;
16492 
16493   // Make the previous decl visible.
16494   makeMergedDefinitionVisible(SkipBody.Previous);
16495   return true;
16496 }
16497 
16498 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16499   assert(isa<ObjCContainerDecl>(IDecl) &&
16500          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16501   DeclContext *OCD = cast<DeclContext>(IDecl);
16502   assert(OCD->getLexicalParent() == CurContext &&
16503       "The next DeclContext should be lexically contained in the current one.");
16504   CurContext = OCD;
16505   return IDecl;
16506 }
16507 
16508 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16509                                            SourceLocation FinalLoc,
16510                                            bool IsFinalSpelledSealed,
16511                                            bool IsAbstract,
16512                                            SourceLocation LBraceLoc) {
16513   AdjustDeclIfTemplate(TagD);
16514   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16515 
16516   FieldCollector->StartClass();
16517 
16518   if (!Record->getIdentifier())
16519     return;
16520 
16521   if (IsAbstract)
16522     Record->markAbstract();
16523 
16524   if (FinalLoc.isValid()) {
16525     Record->addAttr(FinalAttr::Create(
16526         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16527         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16528   }
16529   // C++ [class]p2:
16530   //   [...] The class-name is also inserted into the scope of the
16531   //   class itself; this is known as the injected-class-name. For
16532   //   purposes of access checking, the injected-class-name is treated
16533   //   as if it were a public member name.
16534   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16535       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16536       Record->getLocation(), Record->getIdentifier(),
16537       /*PrevDecl=*/nullptr,
16538       /*DelayTypeCreation=*/true);
16539   Context.getTypeDeclType(InjectedClassName, Record);
16540   InjectedClassName->setImplicit();
16541   InjectedClassName->setAccess(AS_public);
16542   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16543       InjectedClassName->setDescribedClassTemplate(Template);
16544   PushOnScopeChains(InjectedClassName, S);
16545   assert(InjectedClassName->isInjectedClassName() &&
16546          "Broken injected-class-name");
16547 }
16548 
16549 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16550                                     SourceRange BraceRange) {
16551   AdjustDeclIfTemplate(TagD);
16552   TagDecl *Tag = cast<TagDecl>(TagD);
16553   Tag->setBraceRange(BraceRange);
16554 
16555   // Make sure we "complete" the definition even it is invalid.
16556   if (Tag->isBeingDefined()) {
16557     assert(Tag->isInvalidDecl() && "We should already have completed it");
16558     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16559       RD->completeDefinition();
16560   }
16561 
16562   if (isa<CXXRecordDecl>(Tag)) {
16563     FieldCollector->FinishClass();
16564   }
16565 
16566   // Exit this scope of this tag's definition.
16567   PopDeclContext();
16568 
16569   if (getCurLexicalContext()->isObjCContainer() &&
16570       Tag->getDeclContext()->isFileContext())
16571     Tag->setTopLevelDeclInObjCContainer();
16572 
16573   // Notify the consumer that we've defined a tag.
16574   if (!Tag->isInvalidDecl())
16575     Consumer.HandleTagDeclDefinition(Tag);
16576 }
16577 
16578 void Sema::ActOnObjCContainerFinishDefinition() {
16579   // Exit this scope of this interface definition.
16580   PopDeclContext();
16581 }
16582 
16583 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16584   assert(DC == CurContext && "Mismatch of container contexts");
16585   OriginalLexicalContext = DC;
16586   ActOnObjCContainerFinishDefinition();
16587 }
16588 
16589 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16590   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16591   OriginalLexicalContext = nullptr;
16592 }
16593 
16594 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16595   AdjustDeclIfTemplate(TagD);
16596   TagDecl *Tag = cast<TagDecl>(TagD);
16597   Tag->setInvalidDecl();
16598 
16599   // Make sure we "complete" the definition even it is invalid.
16600   if (Tag->isBeingDefined()) {
16601     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16602       RD->completeDefinition();
16603   }
16604 
16605   // We're undoing ActOnTagStartDefinition here, not
16606   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16607   // the FieldCollector.
16608 
16609   PopDeclContext();
16610 }
16611 
16612 // Note that FieldName may be null for anonymous bitfields.
16613 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16614                                 IdentifierInfo *FieldName,
16615                                 QualType FieldTy, bool IsMsStruct,
16616                                 Expr *BitWidth, bool *ZeroWidth) {
16617   assert(BitWidth);
16618   if (BitWidth->containsErrors())
16619     return ExprError();
16620 
16621   // Default to true; that shouldn't confuse checks for emptiness
16622   if (ZeroWidth)
16623     *ZeroWidth = true;
16624 
16625   // C99 6.7.2.1p4 - verify the field type.
16626   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16627   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16628     // Handle incomplete and sizeless types with a specific error.
16629     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16630                                  diag::err_field_incomplete_or_sizeless))
16631       return ExprError();
16632     if (FieldName)
16633       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16634         << FieldName << FieldTy << BitWidth->getSourceRange();
16635     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16636       << FieldTy << BitWidth->getSourceRange();
16637   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16638                                              UPPC_BitFieldWidth))
16639     return ExprError();
16640 
16641   // If the bit-width is type- or value-dependent, don't try to check
16642   // it now.
16643   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16644     return BitWidth;
16645 
16646   llvm::APSInt Value;
16647   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16648   if (ICE.isInvalid())
16649     return ICE;
16650   BitWidth = ICE.get();
16651 
16652   if (Value != 0 && ZeroWidth)
16653     *ZeroWidth = false;
16654 
16655   // Zero-width bitfield is ok for anonymous field.
16656   if (Value == 0 && FieldName)
16657     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16658 
16659   if (Value.isSigned() && Value.isNegative()) {
16660     if (FieldName)
16661       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16662                << FieldName << toString(Value, 10);
16663     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16664       << toString(Value, 10);
16665   }
16666 
16667   // The size of the bit-field must not exceed our maximum permitted object
16668   // size.
16669   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16670     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16671            << !FieldName << FieldName << toString(Value, 10);
16672   }
16673 
16674   if (!FieldTy->isDependentType()) {
16675     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16676     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16677     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16678 
16679     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16680     // ABI.
16681     bool CStdConstraintViolation =
16682         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16683     bool MSBitfieldViolation =
16684         Value.ugt(TypeStorageSize) &&
16685         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16686     if (CStdConstraintViolation || MSBitfieldViolation) {
16687       unsigned DiagWidth =
16688           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16689       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16690              << (bool)FieldName << FieldName << toString(Value, 10)
16691              << !CStdConstraintViolation << DiagWidth;
16692     }
16693 
16694     // Warn on types where the user might conceivably expect to get all
16695     // specified bits as value bits: that's all integral types other than
16696     // 'bool'.
16697     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16698       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16699           << FieldName << toString(Value, 10)
16700           << (unsigned)TypeWidth;
16701     }
16702   }
16703 
16704   return BitWidth;
16705 }
16706 
16707 /// ActOnField - Each field of a C struct/union is passed into this in order
16708 /// to create a FieldDecl object for it.
16709 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16710                        Declarator &D, Expr *BitfieldWidth) {
16711   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16712                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16713                                /*InitStyle=*/ICIS_NoInit, AS_public);
16714   return Res;
16715 }
16716 
16717 /// HandleField - Analyze a field of a C struct or a C++ data member.
16718 ///
16719 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16720                              SourceLocation DeclStart,
16721                              Declarator &D, Expr *BitWidth,
16722                              InClassInitStyle InitStyle,
16723                              AccessSpecifier AS) {
16724   if (D.isDecompositionDeclarator()) {
16725     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16726     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16727       << Decomp.getSourceRange();
16728     return nullptr;
16729   }
16730 
16731   IdentifierInfo *II = D.getIdentifier();
16732   SourceLocation Loc = DeclStart;
16733   if (II) Loc = D.getIdentifierLoc();
16734 
16735   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16736   QualType T = TInfo->getType();
16737   if (getLangOpts().CPlusPlus) {
16738     CheckExtraCXXDefaultArguments(D);
16739 
16740     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16741                                         UPPC_DataMemberType)) {
16742       D.setInvalidType();
16743       T = Context.IntTy;
16744       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16745     }
16746   }
16747 
16748   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16749 
16750   if (D.getDeclSpec().isInlineSpecified())
16751     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16752         << getLangOpts().CPlusPlus17;
16753   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16754     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16755          diag::err_invalid_thread)
16756       << DeclSpec::getSpecifierName(TSCS);
16757 
16758   // Check to see if this name was declared as a member previously
16759   NamedDecl *PrevDecl = nullptr;
16760   LookupResult Previous(*this, II, Loc, LookupMemberName,
16761                         ForVisibleRedeclaration);
16762   LookupName(Previous, S);
16763   switch (Previous.getResultKind()) {
16764     case LookupResult::Found:
16765     case LookupResult::FoundUnresolvedValue:
16766       PrevDecl = Previous.getAsSingle<NamedDecl>();
16767       break;
16768 
16769     case LookupResult::FoundOverloaded:
16770       PrevDecl = Previous.getRepresentativeDecl();
16771       break;
16772 
16773     case LookupResult::NotFound:
16774     case LookupResult::NotFoundInCurrentInstantiation:
16775     case LookupResult::Ambiguous:
16776       break;
16777   }
16778   Previous.suppressDiagnostics();
16779 
16780   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16781     // Maybe we will complain about the shadowed template parameter.
16782     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16783     // Just pretend that we didn't see the previous declaration.
16784     PrevDecl = nullptr;
16785   }
16786 
16787   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16788     PrevDecl = nullptr;
16789 
16790   bool Mutable
16791     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16792   SourceLocation TSSL = D.getBeginLoc();
16793   FieldDecl *NewFD
16794     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16795                      TSSL, AS, PrevDecl, &D);
16796 
16797   if (NewFD->isInvalidDecl())
16798     Record->setInvalidDecl();
16799 
16800   if (D.getDeclSpec().isModulePrivateSpecified())
16801     NewFD->setModulePrivate();
16802 
16803   if (NewFD->isInvalidDecl() && PrevDecl) {
16804     // Don't introduce NewFD into scope; there's already something
16805     // with the same name in the same scope.
16806   } else if (II) {
16807     PushOnScopeChains(NewFD, S);
16808   } else
16809     Record->addDecl(NewFD);
16810 
16811   return NewFD;
16812 }
16813 
16814 /// Build a new FieldDecl and check its well-formedness.
16815 ///
16816 /// This routine builds a new FieldDecl given the fields name, type,
16817 /// record, etc. \p PrevDecl should refer to any previous declaration
16818 /// with the same name and in the same scope as the field to be
16819 /// created.
16820 ///
16821 /// \returns a new FieldDecl.
16822 ///
16823 /// \todo The Declarator argument is a hack. It will be removed once
16824 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16825                                 TypeSourceInfo *TInfo,
16826                                 RecordDecl *Record, SourceLocation Loc,
16827                                 bool Mutable, Expr *BitWidth,
16828                                 InClassInitStyle InitStyle,
16829                                 SourceLocation TSSL,
16830                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16831                                 Declarator *D) {
16832   IdentifierInfo *II = Name.getAsIdentifierInfo();
16833   bool InvalidDecl = false;
16834   if (D) InvalidDecl = D->isInvalidType();
16835 
16836   // If we receive a broken type, recover by assuming 'int' and
16837   // marking this declaration as invalid.
16838   if (T.isNull() || T->containsErrors()) {
16839     InvalidDecl = true;
16840     T = Context.IntTy;
16841   }
16842 
16843   QualType EltTy = Context.getBaseElementType(T);
16844   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16845     if (RequireCompleteSizedType(Loc, EltTy,
16846                                  diag::err_field_incomplete_or_sizeless)) {
16847       // Fields of incomplete type force their record to be invalid.
16848       Record->setInvalidDecl();
16849       InvalidDecl = true;
16850     } else {
16851       NamedDecl *Def;
16852       EltTy->isIncompleteType(&Def);
16853       if (Def && Def->isInvalidDecl()) {
16854         Record->setInvalidDecl();
16855         InvalidDecl = true;
16856       }
16857     }
16858   }
16859 
16860   // TR 18037 does not allow fields to be declared with address space
16861   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16862       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16863     Diag(Loc, diag::err_field_with_address_space);
16864     Record->setInvalidDecl();
16865     InvalidDecl = true;
16866   }
16867 
16868   if (LangOpts.OpenCL) {
16869     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16870     // used as structure or union field: image, sampler, event or block types.
16871     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16872         T->isBlockPointerType()) {
16873       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16874       Record->setInvalidDecl();
16875       InvalidDecl = true;
16876     }
16877     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16878     // is enabled.
16879     if (BitWidth && !getOpenCLOptions().isAvailableOption(
16880                         "__cl_clang_bitfields", LangOpts)) {
16881       Diag(Loc, diag::err_opencl_bitfields);
16882       InvalidDecl = true;
16883     }
16884   }
16885 
16886   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16887   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16888       T.hasQualifiers()) {
16889     InvalidDecl = true;
16890     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16891   }
16892 
16893   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16894   // than a variably modified type.
16895   if (!InvalidDecl && T->isVariablyModifiedType()) {
16896     if (!tryToFixVariablyModifiedVarType(
16897             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16898       InvalidDecl = true;
16899   }
16900 
16901   // Fields can not have abstract class types
16902   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16903                                              diag::err_abstract_type_in_decl,
16904                                              AbstractFieldType))
16905     InvalidDecl = true;
16906 
16907   bool ZeroWidth = false;
16908   if (InvalidDecl)
16909     BitWidth = nullptr;
16910   // If this is declared as a bit-field, check the bit-field.
16911   if (BitWidth) {
16912     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16913                               &ZeroWidth).get();
16914     if (!BitWidth) {
16915       InvalidDecl = true;
16916       BitWidth = nullptr;
16917       ZeroWidth = false;
16918     }
16919   }
16920 
16921   // Check that 'mutable' is consistent with the type of the declaration.
16922   if (!InvalidDecl && Mutable) {
16923     unsigned DiagID = 0;
16924     if (T->isReferenceType())
16925       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16926                                         : diag::err_mutable_reference;
16927     else if (T.isConstQualified())
16928       DiagID = diag::err_mutable_const;
16929 
16930     if (DiagID) {
16931       SourceLocation ErrLoc = Loc;
16932       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16933         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16934       Diag(ErrLoc, DiagID);
16935       if (DiagID != diag::ext_mutable_reference) {
16936         Mutable = false;
16937         InvalidDecl = true;
16938       }
16939     }
16940   }
16941 
16942   // C++11 [class.union]p8 (DR1460):
16943   //   At most one variant member of a union may have a
16944   //   brace-or-equal-initializer.
16945   if (InitStyle != ICIS_NoInit)
16946     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16947 
16948   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16949                                        BitWidth, Mutable, InitStyle);
16950   if (InvalidDecl)
16951     NewFD->setInvalidDecl();
16952 
16953   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16954     Diag(Loc, diag::err_duplicate_member) << II;
16955     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16956     NewFD->setInvalidDecl();
16957   }
16958 
16959   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16960     if (Record->isUnion()) {
16961       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16962         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16963         if (RDecl->getDefinition()) {
16964           // C++ [class.union]p1: An object of a class with a non-trivial
16965           // constructor, a non-trivial copy constructor, a non-trivial
16966           // destructor, or a non-trivial copy assignment operator
16967           // cannot be a member of a union, nor can an array of such
16968           // objects.
16969           if (CheckNontrivialField(NewFD))
16970             NewFD->setInvalidDecl();
16971         }
16972       }
16973 
16974       // C++ [class.union]p1: If a union contains a member of reference type,
16975       // the program is ill-formed, except when compiling with MSVC extensions
16976       // enabled.
16977       if (EltTy->isReferenceType()) {
16978         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16979                                     diag::ext_union_member_of_reference_type :
16980                                     diag::err_union_member_of_reference_type)
16981           << NewFD->getDeclName() << EltTy;
16982         if (!getLangOpts().MicrosoftExt)
16983           NewFD->setInvalidDecl();
16984       }
16985     }
16986   }
16987 
16988   // FIXME: We need to pass in the attributes given an AST
16989   // representation, not a parser representation.
16990   if (D) {
16991     // FIXME: The current scope is almost... but not entirely... correct here.
16992     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16993 
16994     if (NewFD->hasAttrs())
16995       CheckAlignasUnderalignment(NewFD);
16996   }
16997 
16998   // In auto-retain/release, infer strong retension for fields of
16999   // retainable type.
17000   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17001     NewFD->setInvalidDecl();
17002 
17003   if (T.isObjCGCWeak())
17004     Diag(Loc, diag::warn_attribute_weak_on_field);
17005 
17006   // PPC MMA non-pointer types are not allowed as field types.
17007   if (Context.getTargetInfo().getTriple().isPPC64() &&
17008       CheckPPCMMAType(T, NewFD->getLocation()))
17009     NewFD->setInvalidDecl();
17010 
17011   NewFD->setAccess(AS);
17012   return NewFD;
17013 }
17014 
17015 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17016   assert(FD);
17017   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17018 
17019   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17020     return false;
17021 
17022   QualType EltTy = Context.getBaseElementType(FD->getType());
17023   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17024     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17025     if (RDecl->getDefinition()) {
17026       // We check for copy constructors before constructors
17027       // because otherwise we'll never get complaints about
17028       // copy constructors.
17029 
17030       CXXSpecialMember member = CXXInvalid;
17031       // We're required to check for any non-trivial constructors. Since the
17032       // implicit default constructor is suppressed if there are any
17033       // user-declared constructors, we just need to check that there is a
17034       // trivial default constructor and a trivial copy constructor. (We don't
17035       // worry about move constructors here, since this is a C++98 check.)
17036       if (RDecl->hasNonTrivialCopyConstructor())
17037         member = CXXCopyConstructor;
17038       else if (!RDecl->hasTrivialDefaultConstructor())
17039         member = CXXDefaultConstructor;
17040       else if (RDecl->hasNonTrivialCopyAssignment())
17041         member = CXXCopyAssignment;
17042       else if (RDecl->hasNonTrivialDestructor())
17043         member = CXXDestructor;
17044 
17045       if (member != CXXInvalid) {
17046         if (!getLangOpts().CPlusPlus11 &&
17047             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17048           // Objective-C++ ARC: it is an error to have a non-trivial field of
17049           // a union. However, system headers in Objective-C programs
17050           // occasionally have Objective-C lifetime objects within unions,
17051           // and rather than cause the program to fail, we make those
17052           // members unavailable.
17053           SourceLocation Loc = FD->getLocation();
17054           if (getSourceManager().isInSystemHeader(Loc)) {
17055             if (!FD->hasAttr<UnavailableAttr>())
17056               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17057                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17058             return false;
17059           }
17060         }
17061 
17062         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17063                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17064                diag::err_illegal_union_or_anon_struct_member)
17065           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17066         DiagnoseNontrivial(RDecl, member);
17067         return !getLangOpts().CPlusPlus11;
17068       }
17069     }
17070   }
17071 
17072   return false;
17073 }
17074 
17075 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17076 ///  AST enum value.
17077 static ObjCIvarDecl::AccessControl
17078 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17079   switch (ivarVisibility) {
17080   default: llvm_unreachable("Unknown visitibility kind");
17081   case tok::objc_private: return ObjCIvarDecl::Private;
17082   case tok::objc_public: return ObjCIvarDecl::Public;
17083   case tok::objc_protected: return ObjCIvarDecl::Protected;
17084   case tok::objc_package: return ObjCIvarDecl::Package;
17085   }
17086 }
17087 
17088 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17089 /// in order to create an IvarDecl object for it.
17090 Decl *Sema::ActOnIvar(Scope *S,
17091                                 SourceLocation DeclStart,
17092                                 Declarator &D, Expr *BitfieldWidth,
17093                                 tok::ObjCKeywordKind Visibility) {
17094 
17095   IdentifierInfo *II = D.getIdentifier();
17096   Expr *BitWidth = (Expr*)BitfieldWidth;
17097   SourceLocation Loc = DeclStart;
17098   if (II) Loc = D.getIdentifierLoc();
17099 
17100   // FIXME: Unnamed fields can be handled in various different ways, for
17101   // example, unnamed unions inject all members into the struct namespace!
17102 
17103   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17104   QualType T = TInfo->getType();
17105 
17106   if (BitWidth) {
17107     // 6.7.2.1p3, 6.7.2.1p4
17108     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17109     if (!BitWidth)
17110       D.setInvalidType();
17111   } else {
17112     // Not a bitfield.
17113 
17114     // validate II.
17115 
17116   }
17117   if (T->isReferenceType()) {
17118     Diag(Loc, diag::err_ivar_reference_type);
17119     D.setInvalidType();
17120   }
17121   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17122   // than a variably modified type.
17123   else if (T->isVariablyModifiedType()) {
17124     if (!tryToFixVariablyModifiedVarType(
17125             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17126       D.setInvalidType();
17127   }
17128 
17129   // Get the visibility (access control) for this ivar.
17130   ObjCIvarDecl::AccessControl ac =
17131     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17132                                         : ObjCIvarDecl::None;
17133   // Must set ivar's DeclContext to its enclosing interface.
17134   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17135   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17136     return nullptr;
17137   ObjCContainerDecl *EnclosingContext;
17138   if (ObjCImplementationDecl *IMPDecl =
17139       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17140     if (LangOpts.ObjCRuntime.isFragile()) {
17141     // Case of ivar declared in an implementation. Context is that of its class.
17142       EnclosingContext = IMPDecl->getClassInterface();
17143       assert(EnclosingContext && "Implementation has no class interface!");
17144     }
17145     else
17146       EnclosingContext = EnclosingDecl;
17147   } else {
17148     if (ObjCCategoryDecl *CDecl =
17149         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17150       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17151         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17152         return nullptr;
17153       }
17154     }
17155     EnclosingContext = EnclosingDecl;
17156   }
17157 
17158   // Construct the decl.
17159   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17160                                              DeclStart, Loc, II, T,
17161                                              TInfo, ac, (Expr *)BitfieldWidth);
17162 
17163   if (II) {
17164     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17165                                            ForVisibleRedeclaration);
17166     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17167         && !isa<TagDecl>(PrevDecl)) {
17168       Diag(Loc, diag::err_duplicate_member) << II;
17169       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17170       NewID->setInvalidDecl();
17171     }
17172   }
17173 
17174   // Process attributes attached to the ivar.
17175   ProcessDeclAttributes(S, NewID, D);
17176 
17177   if (D.isInvalidType())
17178     NewID->setInvalidDecl();
17179 
17180   // In ARC, infer 'retaining' for ivars of retainable type.
17181   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17182     NewID->setInvalidDecl();
17183 
17184   if (D.getDeclSpec().isModulePrivateSpecified())
17185     NewID->setModulePrivate();
17186 
17187   if (II) {
17188     // FIXME: When interfaces are DeclContexts, we'll need to add
17189     // these to the interface.
17190     S->AddDecl(NewID);
17191     IdResolver.AddDecl(NewID);
17192   }
17193 
17194   if (LangOpts.ObjCRuntime.isNonFragile() &&
17195       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17196     Diag(Loc, diag::warn_ivars_in_interface);
17197 
17198   return NewID;
17199 }
17200 
17201 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17202 /// class and class extensions. For every class \@interface and class
17203 /// extension \@interface, if the last ivar is a bitfield of any type,
17204 /// then add an implicit `char :0` ivar to the end of that interface.
17205 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17206                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17207   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17208     return;
17209 
17210   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17211   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17212 
17213   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17214     return;
17215   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17216   if (!ID) {
17217     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17218       if (!CD->IsClassExtension())
17219         return;
17220     }
17221     // No need to add this to end of @implementation.
17222     else
17223       return;
17224   }
17225   // All conditions are met. Add a new bitfield to the tail end of ivars.
17226   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17227   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17228 
17229   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17230                               DeclLoc, DeclLoc, nullptr,
17231                               Context.CharTy,
17232                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17233                                                                DeclLoc),
17234                               ObjCIvarDecl::Private, BW,
17235                               true);
17236   AllIvarDecls.push_back(Ivar);
17237 }
17238 
17239 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17240                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17241                        SourceLocation RBrac,
17242                        const ParsedAttributesView &Attrs) {
17243   assert(EnclosingDecl && "missing record or interface decl");
17244 
17245   // If this is an Objective-C @implementation or category and we have
17246   // new fields here we should reset the layout of the interface since
17247   // it will now change.
17248   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17249     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17250     switch (DC->getKind()) {
17251     default: break;
17252     case Decl::ObjCCategory:
17253       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17254       break;
17255     case Decl::ObjCImplementation:
17256       Context.
17257         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17258       break;
17259     }
17260   }
17261 
17262   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17263   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17264 
17265   // Start counting up the number of named members; make sure to include
17266   // members of anonymous structs and unions in the total.
17267   unsigned NumNamedMembers = 0;
17268   if (Record) {
17269     for (const auto *I : Record->decls()) {
17270       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17271         if (IFD->getDeclName())
17272           ++NumNamedMembers;
17273     }
17274   }
17275 
17276   // Verify that all the fields are okay.
17277   SmallVector<FieldDecl*, 32> RecFields;
17278 
17279   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17280        i != end; ++i) {
17281     FieldDecl *FD = cast<FieldDecl>(*i);
17282 
17283     // Get the type for the field.
17284     const Type *FDTy = FD->getType().getTypePtr();
17285 
17286     if (!FD->isAnonymousStructOrUnion()) {
17287       // Remember all fields written by the user.
17288       RecFields.push_back(FD);
17289     }
17290 
17291     // If the field is already invalid for some reason, don't emit more
17292     // diagnostics about it.
17293     if (FD->isInvalidDecl()) {
17294       EnclosingDecl->setInvalidDecl();
17295       continue;
17296     }
17297 
17298     // C99 6.7.2.1p2:
17299     //   A structure or union shall not contain a member with
17300     //   incomplete or function type (hence, a structure shall not
17301     //   contain an instance of itself, but may contain a pointer to
17302     //   an instance of itself), except that the last member of a
17303     //   structure with more than one named member may have incomplete
17304     //   array type; such a structure (and any union containing,
17305     //   possibly recursively, a member that is such a structure)
17306     //   shall not be a member of a structure or an element of an
17307     //   array.
17308     bool IsLastField = (i + 1 == Fields.end());
17309     if (FDTy->isFunctionType()) {
17310       // Field declared as a function.
17311       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17312         << FD->getDeclName();
17313       FD->setInvalidDecl();
17314       EnclosingDecl->setInvalidDecl();
17315       continue;
17316     } else if (FDTy->isIncompleteArrayType() &&
17317                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17318       if (Record) {
17319         // Flexible array member.
17320         // Microsoft and g++ is more permissive regarding flexible array.
17321         // It will accept flexible array in union and also
17322         // as the sole element of a struct/class.
17323         unsigned DiagID = 0;
17324         if (!Record->isUnion() && !IsLastField) {
17325           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17326             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17327           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17328           FD->setInvalidDecl();
17329           EnclosingDecl->setInvalidDecl();
17330           continue;
17331         } else if (Record->isUnion())
17332           DiagID = getLangOpts().MicrosoftExt
17333                        ? diag::ext_flexible_array_union_ms
17334                        : getLangOpts().CPlusPlus
17335                              ? diag::ext_flexible_array_union_gnu
17336                              : diag::err_flexible_array_union;
17337         else if (NumNamedMembers < 1)
17338           DiagID = getLangOpts().MicrosoftExt
17339                        ? diag::ext_flexible_array_empty_aggregate_ms
17340                        : getLangOpts().CPlusPlus
17341                              ? diag::ext_flexible_array_empty_aggregate_gnu
17342                              : diag::err_flexible_array_empty_aggregate;
17343 
17344         if (DiagID)
17345           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17346                                           << Record->getTagKind();
17347         // While the layout of types that contain virtual bases is not specified
17348         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17349         // virtual bases after the derived members.  This would make a flexible
17350         // array member declared at the end of an object not adjacent to the end
17351         // of the type.
17352         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17353           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17354               << FD->getDeclName() << Record->getTagKind();
17355         if (!getLangOpts().C99)
17356           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17357             << FD->getDeclName() << Record->getTagKind();
17358 
17359         // If the element type has a non-trivial destructor, we would not
17360         // implicitly destroy the elements, so disallow it for now.
17361         //
17362         // FIXME: GCC allows this. We should probably either implicitly delete
17363         // the destructor of the containing class, or just allow this.
17364         QualType BaseElem = Context.getBaseElementType(FD->getType());
17365         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17366           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17367             << FD->getDeclName() << FD->getType();
17368           FD->setInvalidDecl();
17369           EnclosingDecl->setInvalidDecl();
17370           continue;
17371         }
17372         // Okay, we have a legal flexible array member at the end of the struct.
17373         Record->setHasFlexibleArrayMember(true);
17374       } else {
17375         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17376         // unless they are followed by another ivar. That check is done
17377         // elsewhere, after synthesized ivars are known.
17378       }
17379     } else if (!FDTy->isDependentType() &&
17380                RequireCompleteSizedType(
17381                    FD->getLocation(), FD->getType(),
17382                    diag::err_field_incomplete_or_sizeless)) {
17383       // Incomplete type
17384       FD->setInvalidDecl();
17385       EnclosingDecl->setInvalidDecl();
17386       continue;
17387     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17388       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17389         // A type which contains a flexible array member is considered to be a
17390         // flexible array member.
17391         Record->setHasFlexibleArrayMember(true);
17392         if (!Record->isUnion()) {
17393           // If this is a struct/class and this is not the last element, reject
17394           // it.  Note that GCC supports variable sized arrays in the middle of
17395           // structures.
17396           if (!IsLastField)
17397             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17398               << FD->getDeclName() << FD->getType();
17399           else {
17400             // We support flexible arrays at the end of structs in
17401             // other structs as an extension.
17402             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17403               << FD->getDeclName();
17404           }
17405         }
17406       }
17407       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17408           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17409                                  diag::err_abstract_type_in_decl,
17410                                  AbstractIvarType)) {
17411         // Ivars can not have abstract class types
17412         FD->setInvalidDecl();
17413       }
17414       if (Record && FDTTy->getDecl()->hasObjectMember())
17415         Record->setHasObjectMember(true);
17416       if (Record && FDTTy->getDecl()->hasVolatileMember())
17417         Record->setHasVolatileMember(true);
17418     } else if (FDTy->isObjCObjectType()) {
17419       /// A field cannot be an Objective-c object
17420       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17421         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17422       QualType T = Context.getObjCObjectPointerType(FD->getType());
17423       FD->setType(T);
17424     } else if (Record && Record->isUnion() &&
17425                FD->getType().hasNonTrivialObjCLifetime() &&
17426                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17427                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17428                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17429                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17430       // For backward compatibility, fields of C unions declared in system
17431       // headers that have non-trivial ObjC ownership qualifications are marked
17432       // as unavailable unless the qualifier is explicit and __strong. This can
17433       // break ABI compatibility between programs compiled with ARC and MRR, but
17434       // is a better option than rejecting programs using those unions under
17435       // ARC.
17436       FD->addAttr(UnavailableAttr::CreateImplicit(
17437           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17438           FD->getLocation()));
17439     } else if (getLangOpts().ObjC &&
17440                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17441                !Record->hasObjectMember()) {
17442       if (FD->getType()->isObjCObjectPointerType() ||
17443           FD->getType().isObjCGCStrong())
17444         Record->setHasObjectMember(true);
17445       else if (Context.getAsArrayType(FD->getType())) {
17446         QualType BaseType = Context.getBaseElementType(FD->getType());
17447         if (BaseType->isRecordType() &&
17448             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17449           Record->setHasObjectMember(true);
17450         else if (BaseType->isObjCObjectPointerType() ||
17451                  BaseType.isObjCGCStrong())
17452                Record->setHasObjectMember(true);
17453       }
17454     }
17455 
17456     if (Record && !getLangOpts().CPlusPlus &&
17457         !shouldIgnoreForRecordTriviality(FD)) {
17458       QualType FT = FD->getType();
17459       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17460         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17461         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17462             Record->isUnion())
17463           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17464       }
17465       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17466       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17467         Record->setNonTrivialToPrimitiveCopy(true);
17468         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17469           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17470       }
17471       if (FT.isDestructedType()) {
17472         Record->setNonTrivialToPrimitiveDestroy(true);
17473         Record->setParamDestroyedInCallee(true);
17474         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17475           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17476       }
17477 
17478       if (const auto *RT = FT->getAs<RecordType>()) {
17479         if (RT->getDecl()->getArgPassingRestrictions() ==
17480             RecordDecl::APK_CanNeverPassInRegs)
17481           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17482       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17483         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17484     }
17485 
17486     if (Record && FD->getType().isVolatileQualified())
17487       Record->setHasVolatileMember(true);
17488     // Keep track of the number of named members.
17489     if (FD->getIdentifier())
17490       ++NumNamedMembers;
17491   }
17492 
17493   // Okay, we successfully defined 'Record'.
17494   if (Record) {
17495     bool Completed = false;
17496     if (CXXRecord) {
17497       if (!CXXRecord->isInvalidDecl()) {
17498         // Set access bits correctly on the directly-declared conversions.
17499         for (CXXRecordDecl::conversion_iterator
17500                I = CXXRecord->conversion_begin(),
17501                E = CXXRecord->conversion_end(); I != E; ++I)
17502           I.setAccess((*I)->getAccess());
17503       }
17504 
17505       // Add any implicitly-declared members to this class.
17506       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17507 
17508       if (!CXXRecord->isDependentType()) {
17509         if (!CXXRecord->isInvalidDecl()) {
17510           // If we have virtual base classes, we may end up finding multiple
17511           // final overriders for a given virtual function. Check for this
17512           // problem now.
17513           if (CXXRecord->getNumVBases()) {
17514             CXXFinalOverriderMap FinalOverriders;
17515             CXXRecord->getFinalOverriders(FinalOverriders);
17516 
17517             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17518                                              MEnd = FinalOverriders.end();
17519                  M != MEnd; ++M) {
17520               for (OverridingMethods::iterator SO = M->second.begin(),
17521                                             SOEnd = M->second.end();
17522                    SO != SOEnd; ++SO) {
17523                 assert(SO->second.size() > 0 &&
17524                        "Virtual function without overriding functions?");
17525                 if (SO->second.size() == 1)
17526                   continue;
17527 
17528                 // C++ [class.virtual]p2:
17529                 //   In a derived class, if a virtual member function of a base
17530                 //   class subobject has more than one final overrider the
17531                 //   program is ill-formed.
17532                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17533                   << (const NamedDecl *)M->first << Record;
17534                 Diag(M->first->getLocation(),
17535                      diag::note_overridden_virtual_function);
17536                 for (OverridingMethods::overriding_iterator
17537                           OM = SO->second.begin(),
17538                        OMEnd = SO->second.end();
17539                      OM != OMEnd; ++OM)
17540                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17541                     << (const NamedDecl *)M->first << OM->Method->getParent();
17542 
17543                 Record->setInvalidDecl();
17544               }
17545             }
17546             CXXRecord->completeDefinition(&FinalOverriders);
17547             Completed = true;
17548           }
17549         }
17550       }
17551     }
17552 
17553     if (!Completed)
17554       Record->completeDefinition();
17555 
17556     // Handle attributes before checking the layout.
17557     ProcessDeclAttributeList(S, Record, Attrs);
17558 
17559     // We may have deferred checking for a deleted destructor. Check now.
17560     if (CXXRecord) {
17561       auto *Dtor = CXXRecord->getDestructor();
17562       if (Dtor && Dtor->isImplicit() &&
17563           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17564         CXXRecord->setImplicitDestructorIsDeleted();
17565         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17566       }
17567     }
17568 
17569     if (Record->hasAttrs()) {
17570       CheckAlignasUnderalignment(Record);
17571 
17572       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17573         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17574                                            IA->getRange(), IA->getBestCase(),
17575                                            IA->getInheritanceModel());
17576     }
17577 
17578     // Check if the structure/union declaration is a type that can have zero
17579     // size in C. For C this is a language extension, for C++ it may cause
17580     // compatibility problems.
17581     bool CheckForZeroSize;
17582     if (!getLangOpts().CPlusPlus) {
17583       CheckForZeroSize = true;
17584     } else {
17585       // For C++ filter out types that cannot be referenced in C code.
17586       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17587       CheckForZeroSize =
17588           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17589           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17590           CXXRecord->isCLike();
17591     }
17592     if (CheckForZeroSize) {
17593       bool ZeroSize = true;
17594       bool IsEmpty = true;
17595       unsigned NonBitFields = 0;
17596       for (RecordDecl::field_iterator I = Record->field_begin(),
17597                                       E = Record->field_end();
17598            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17599         IsEmpty = false;
17600         if (I->isUnnamedBitfield()) {
17601           if (!I->isZeroLengthBitField(Context))
17602             ZeroSize = false;
17603         } else {
17604           ++NonBitFields;
17605           QualType FieldType = I->getType();
17606           if (FieldType->isIncompleteType() ||
17607               !Context.getTypeSizeInChars(FieldType).isZero())
17608             ZeroSize = false;
17609         }
17610       }
17611 
17612       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17613       // allowed in C++, but warn if its declaration is inside
17614       // extern "C" block.
17615       if (ZeroSize) {
17616         Diag(RecLoc, getLangOpts().CPlusPlus ?
17617                          diag::warn_zero_size_struct_union_in_extern_c :
17618                          diag::warn_zero_size_struct_union_compat)
17619           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17620       }
17621 
17622       // Structs without named members are extension in C (C99 6.7.2.1p7),
17623       // but are accepted by GCC.
17624       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17625         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17626                                diag::ext_no_named_members_in_struct_union)
17627           << Record->isUnion();
17628       }
17629     }
17630   } else {
17631     ObjCIvarDecl **ClsFields =
17632       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17633     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17634       ID->setEndOfDefinitionLoc(RBrac);
17635       // Add ivar's to class's DeclContext.
17636       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17637         ClsFields[i]->setLexicalDeclContext(ID);
17638         ID->addDecl(ClsFields[i]);
17639       }
17640       // Must enforce the rule that ivars in the base classes may not be
17641       // duplicates.
17642       if (ID->getSuperClass())
17643         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17644     } else if (ObjCImplementationDecl *IMPDecl =
17645                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17646       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17647       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17648         // Ivar declared in @implementation never belongs to the implementation.
17649         // Only it is in implementation's lexical context.
17650         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17651       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17652       IMPDecl->setIvarLBraceLoc(LBrac);
17653       IMPDecl->setIvarRBraceLoc(RBrac);
17654     } else if (ObjCCategoryDecl *CDecl =
17655                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17656       // case of ivars in class extension; all other cases have been
17657       // reported as errors elsewhere.
17658       // FIXME. Class extension does not have a LocEnd field.
17659       // CDecl->setLocEnd(RBrac);
17660       // Add ivar's to class extension's DeclContext.
17661       // Diagnose redeclaration of private ivars.
17662       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17663       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17664         if (IDecl) {
17665           if (const ObjCIvarDecl *ClsIvar =
17666               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17667             Diag(ClsFields[i]->getLocation(),
17668                  diag::err_duplicate_ivar_declaration);
17669             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17670             continue;
17671           }
17672           for (const auto *Ext : IDecl->known_extensions()) {
17673             if (const ObjCIvarDecl *ClsExtIvar
17674                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17675               Diag(ClsFields[i]->getLocation(),
17676                    diag::err_duplicate_ivar_declaration);
17677               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17678               continue;
17679             }
17680           }
17681         }
17682         ClsFields[i]->setLexicalDeclContext(CDecl);
17683         CDecl->addDecl(ClsFields[i]);
17684       }
17685       CDecl->setIvarLBraceLoc(LBrac);
17686       CDecl->setIvarRBraceLoc(RBrac);
17687     }
17688   }
17689 }
17690 
17691 /// Determine whether the given integral value is representable within
17692 /// the given type T.
17693 static bool isRepresentableIntegerValue(ASTContext &Context,
17694                                         llvm::APSInt &Value,
17695                                         QualType T) {
17696   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17697          "Integral type required!");
17698   unsigned BitWidth = Context.getIntWidth(T);
17699 
17700   if (Value.isUnsigned() || Value.isNonNegative()) {
17701     if (T->isSignedIntegerOrEnumerationType())
17702       --BitWidth;
17703     return Value.getActiveBits() <= BitWidth;
17704   }
17705   return Value.getMinSignedBits() <= BitWidth;
17706 }
17707 
17708 // Given an integral type, return the next larger integral type
17709 // (or a NULL type of no such type exists).
17710 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17711   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17712   // enum checking below.
17713   assert((T->isIntegralType(Context) ||
17714          T->isEnumeralType()) && "Integral type required!");
17715   const unsigned NumTypes = 4;
17716   QualType SignedIntegralTypes[NumTypes] = {
17717     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17718   };
17719   QualType UnsignedIntegralTypes[NumTypes] = {
17720     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17721     Context.UnsignedLongLongTy
17722   };
17723 
17724   unsigned BitWidth = Context.getTypeSize(T);
17725   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17726                                                         : UnsignedIntegralTypes;
17727   for (unsigned I = 0; I != NumTypes; ++I)
17728     if (Context.getTypeSize(Types[I]) > BitWidth)
17729       return Types[I];
17730 
17731   return QualType();
17732 }
17733 
17734 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17735                                           EnumConstantDecl *LastEnumConst,
17736                                           SourceLocation IdLoc,
17737                                           IdentifierInfo *Id,
17738                                           Expr *Val) {
17739   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17740   llvm::APSInt EnumVal(IntWidth);
17741   QualType EltTy;
17742 
17743   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17744     Val = nullptr;
17745 
17746   if (Val)
17747     Val = DefaultLvalueConversion(Val).get();
17748 
17749   if (Val) {
17750     if (Enum->isDependentType() || Val->isTypeDependent())
17751       EltTy = Context.DependentTy;
17752     else {
17753       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17754       // underlying type, but do allow it in all other contexts.
17755       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17756         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17757         // constant-expression in the enumerator-definition shall be a converted
17758         // constant expression of the underlying type.
17759         EltTy = Enum->getIntegerType();
17760         ExprResult Converted =
17761           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17762                                            CCEK_Enumerator);
17763         if (Converted.isInvalid())
17764           Val = nullptr;
17765         else
17766           Val = Converted.get();
17767       } else if (!Val->isValueDependent() &&
17768                  !(Val =
17769                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17770                            .get())) {
17771         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17772       } else {
17773         if (Enum->isComplete()) {
17774           EltTy = Enum->getIntegerType();
17775 
17776           // In Obj-C and Microsoft mode, require the enumeration value to be
17777           // representable in the underlying type of the enumeration. In C++11,
17778           // we perform a non-narrowing conversion as part of converted constant
17779           // expression checking.
17780           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17781             if (Context.getTargetInfo()
17782                     .getTriple()
17783                     .isWindowsMSVCEnvironment()) {
17784               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17785             } else {
17786               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17787             }
17788           }
17789 
17790           // Cast to the underlying type.
17791           Val = ImpCastExprToType(Val, EltTy,
17792                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17793                                                          : CK_IntegralCast)
17794                     .get();
17795         } else if (getLangOpts().CPlusPlus) {
17796           // C++11 [dcl.enum]p5:
17797           //   If the underlying type is not fixed, the type of each enumerator
17798           //   is the type of its initializing value:
17799           //     - If an initializer is specified for an enumerator, the
17800           //       initializing value has the same type as the expression.
17801           EltTy = Val->getType();
17802         } else {
17803           // C99 6.7.2.2p2:
17804           //   The expression that defines the value of an enumeration constant
17805           //   shall be an integer constant expression that has a value
17806           //   representable as an int.
17807 
17808           // Complain if the value is not representable in an int.
17809           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17810             Diag(IdLoc, diag::ext_enum_value_not_int)
17811               << toString(EnumVal, 10) << Val->getSourceRange()
17812               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17813           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17814             // Force the type of the expression to 'int'.
17815             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17816           }
17817           EltTy = Val->getType();
17818         }
17819       }
17820     }
17821   }
17822 
17823   if (!Val) {
17824     if (Enum->isDependentType())
17825       EltTy = Context.DependentTy;
17826     else if (!LastEnumConst) {
17827       // C++0x [dcl.enum]p5:
17828       //   If the underlying type is not fixed, the type of each enumerator
17829       //   is the type of its initializing value:
17830       //     - If no initializer is specified for the first enumerator, the
17831       //       initializing value has an unspecified integral type.
17832       //
17833       // GCC uses 'int' for its unspecified integral type, as does
17834       // C99 6.7.2.2p3.
17835       if (Enum->isFixed()) {
17836         EltTy = Enum->getIntegerType();
17837       }
17838       else {
17839         EltTy = Context.IntTy;
17840       }
17841     } else {
17842       // Assign the last value + 1.
17843       EnumVal = LastEnumConst->getInitVal();
17844       ++EnumVal;
17845       EltTy = LastEnumConst->getType();
17846 
17847       // Check for overflow on increment.
17848       if (EnumVal < LastEnumConst->getInitVal()) {
17849         // C++0x [dcl.enum]p5:
17850         //   If the underlying type is not fixed, the type of each enumerator
17851         //   is the type of its initializing value:
17852         //
17853         //     - Otherwise the type of the initializing value is the same as
17854         //       the type of the initializing value of the preceding enumerator
17855         //       unless the incremented value is not representable in that type,
17856         //       in which case the type is an unspecified integral type
17857         //       sufficient to contain the incremented value. If no such type
17858         //       exists, the program is ill-formed.
17859         QualType T = getNextLargerIntegralType(Context, EltTy);
17860         if (T.isNull() || Enum->isFixed()) {
17861           // There is no integral type larger enough to represent this
17862           // value. Complain, then allow the value to wrap around.
17863           EnumVal = LastEnumConst->getInitVal();
17864           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17865           ++EnumVal;
17866           if (Enum->isFixed())
17867             // When the underlying type is fixed, this is ill-formed.
17868             Diag(IdLoc, diag::err_enumerator_wrapped)
17869               << toString(EnumVal, 10)
17870               << EltTy;
17871           else
17872             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17873               << toString(EnumVal, 10);
17874         } else {
17875           EltTy = T;
17876         }
17877 
17878         // Retrieve the last enumerator's value, extent that type to the
17879         // type that is supposed to be large enough to represent the incremented
17880         // value, then increment.
17881         EnumVal = LastEnumConst->getInitVal();
17882         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17883         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17884         ++EnumVal;
17885 
17886         // If we're not in C++, diagnose the overflow of enumerator values,
17887         // which in C99 means that the enumerator value is not representable in
17888         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17889         // permits enumerator values that are representable in some larger
17890         // integral type.
17891         if (!getLangOpts().CPlusPlus && !T.isNull())
17892           Diag(IdLoc, diag::warn_enum_value_overflow);
17893       } else if (!getLangOpts().CPlusPlus &&
17894                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17895         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17896         Diag(IdLoc, diag::ext_enum_value_not_int)
17897           << toString(EnumVal, 10) << 1;
17898       }
17899     }
17900   }
17901 
17902   if (!EltTy->isDependentType()) {
17903     // Make the enumerator value match the signedness and size of the
17904     // enumerator's type.
17905     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17906     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17907   }
17908 
17909   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17910                                   Val, EnumVal);
17911 }
17912 
17913 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17914                                                 SourceLocation IILoc) {
17915   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17916       !getLangOpts().CPlusPlus)
17917     return SkipBodyInfo();
17918 
17919   // We have an anonymous enum definition. Look up the first enumerator to
17920   // determine if we should merge the definition with an existing one and
17921   // skip the body.
17922   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17923                                          forRedeclarationInCurContext());
17924   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17925   if (!PrevECD)
17926     return SkipBodyInfo();
17927 
17928   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17929   NamedDecl *Hidden;
17930   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17931     SkipBodyInfo Skip;
17932     Skip.Previous = Hidden;
17933     return Skip;
17934   }
17935 
17936   return SkipBodyInfo();
17937 }
17938 
17939 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17940                               SourceLocation IdLoc, IdentifierInfo *Id,
17941                               const ParsedAttributesView &Attrs,
17942                               SourceLocation EqualLoc, Expr *Val) {
17943   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17944   EnumConstantDecl *LastEnumConst =
17945     cast_or_null<EnumConstantDecl>(lastEnumConst);
17946 
17947   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17948   // we find one that is.
17949   S = getNonFieldDeclScope(S);
17950 
17951   // Verify that there isn't already something declared with this name in this
17952   // scope.
17953   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17954   LookupName(R, S);
17955   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17956 
17957   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17958     // Maybe we will complain about the shadowed template parameter.
17959     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17960     // Just pretend that we didn't see the previous declaration.
17961     PrevDecl = nullptr;
17962   }
17963 
17964   // C++ [class.mem]p15:
17965   // If T is the name of a class, then each of the following shall have a name
17966   // different from T:
17967   // - every enumerator of every member of class T that is an unscoped
17968   // enumerated type
17969   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17970     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17971                             DeclarationNameInfo(Id, IdLoc));
17972 
17973   EnumConstantDecl *New =
17974     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17975   if (!New)
17976     return nullptr;
17977 
17978   if (PrevDecl) {
17979     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17980       // Check for other kinds of shadowing not already handled.
17981       CheckShadow(New, PrevDecl, R);
17982     }
17983 
17984     // When in C++, we may get a TagDecl with the same name; in this case the
17985     // enum constant will 'hide' the tag.
17986     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17987            "Received TagDecl when not in C++!");
17988     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17989       if (isa<EnumConstantDecl>(PrevDecl))
17990         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17991       else
17992         Diag(IdLoc, diag::err_redefinition) << Id;
17993       notePreviousDefinition(PrevDecl, IdLoc);
17994       return nullptr;
17995     }
17996   }
17997 
17998   // Process attributes.
17999   ProcessDeclAttributeList(S, New, Attrs);
18000   AddPragmaAttributes(S, New);
18001 
18002   // Register this decl in the current scope stack.
18003   New->setAccess(TheEnumDecl->getAccess());
18004   PushOnScopeChains(New, S);
18005 
18006   ActOnDocumentableDecl(New);
18007 
18008   return New;
18009 }
18010 
18011 // Returns true when the enum initial expression does not trigger the
18012 // duplicate enum warning.  A few common cases are exempted as follows:
18013 // Element2 = Element1
18014 // Element2 = Element1 + 1
18015 // Element2 = Element1 - 1
18016 // Where Element2 and Element1 are from the same enum.
18017 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18018   Expr *InitExpr = ECD->getInitExpr();
18019   if (!InitExpr)
18020     return true;
18021   InitExpr = InitExpr->IgnoreImpCasts();
18022 
18023   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18024     if (!BO->isAdditiveOp())
18025       return true;
18026     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18027     if (!IL)
18028       return true;
18029     if (IL->getValue() != 1)
18030       return true;
18031 
18032     InitExpr = BO->getLHS();
18033   }
18034 
18035   // This checks if the elements are from the same enum.
18036   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18037   if (!DRE)
18038     return true;
18039 
18040   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18041   if (!EnumConstant)
18042     return true;
18043 
18044   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18045       Enum)
18046     return true;
18047 
18048   return false;
18049 }
18050 
18051 // Emits a warning when an element is implicitly set a value that
18052 // a previous element has already been set to.
18053 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18054                                         EnumDecl *Enum, QualType EnumType) {
18055   // Avoid anonymous enums
18056   if (!Enum->getIdentifier())
18057     return;
18058 
18059   // Only check for small enums.
18060   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18061     return;
18062 
18063   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18064     return;
18065 
18066   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18067   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18068 
18069   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18070 
18071   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18072   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18073 
18074   // Use int64_t as a key to avoid needing special handling for map keys.
18075   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18076     llvm::APSInt Val = D->getInitVal();
18077     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18078   };
18079 
18080   DuplicatesVector DupVector;
18081   ValueToVectorMap EnumMap;
18082 
18083   // Populate the EnumMap with all values represented by enum constants without
18084   // an initializer.
18085   for (auto *Element : Elements) {
18086     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18087 
18088     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18089     // this constant.  Skip this enum since it may be ill-formed.
18090     if (!ECD) {
18091       return;
18092     }
18093 
18094     // Constants with initalizers are handled in the next loop.
18095     if (ECD->getInitExpr())
18096       continue;
18097 
18098     // Duplicate values are handled in the next loop.
18099     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18100   }
18101 
18102   if (EnumMap.size() == 0)
18103     return;
18104 
18105   // Create vectors for any values that has duplicates.
18106   for (auto *Element : Elements) {
18107     // The last loop returned if any constant was null.
18108     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18109     if (!ValidDuplicateEnum(ECD, Enum))
18110       continue;
18111 
18112     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18113     if (Iter == EnumMap.end())
18114       continue;
18115 
18116     DeclOrVector& Entry = Iter->second;
18117     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18118       // Ensure constants are different.
18119       if (D == ECD)
18120         continue;
18121 
18122       // Create new vector and push values onto it.
18123       auto Vec = std::make_unique<ECDVector>();
18124       Vec->push_back(D);
18125       Vec->push_back(ECD);
18126 
18127       // Update entry to point to the duplicates vector.
18128       Entry = Vec.get();
18129 
18130       // Store the vector somewhere we can consult later for quick emission of
18131       // diagnostics.
18132       DupVector.emplace_back(std::move(Vec));
18133       continue;
18134     }
18135 
18136     ECDVector *Vec = Entry.get<ECDVector*>();
18137     // Make sure constants are not added more than once.
18138     if (*Vec->begin() == ECD)
18139       continue;
18140 
18141     Vec->push_back(ECD);
18142   }
18143 
18144   // Emit diagnostics.
18145   for (const auto &Vec : DupVector) {
18146     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18147 
18148     // Emit warning for one enum constant.
18149     auto *FirstECD = Vec->front();
18150     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18151       << FirstECD << toString(FirstECD->getInitVal(), 10)
18152       << FirstECD->getSourceRange();
18153 
18154     // Emit one note for each of the remaining enum constants with
18155     // the same value.
18156     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18157       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18158         << ECD << toString(ECD->getInitVal(), 10)
18159         << ECD->getSourceRange();
18160   }
18161 }
18162 
18163 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18164                              bool AllowMask) const {
18165   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18166   assert(ED->isCompleteDefinition() && "expected enum definition");
18167 
18168   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18169   llvm::APInt &FlagBits = R.first->second;
18170 
18171   if (R.second) {
18172     for (auto *E : ED->enumerators()) {
18173       const auto &EVal = E->getInitVal();
18174       // Only single-bit enumerators introduce new flag values.
18175       if (EVal.isPowerOf2())
18176         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18177     }
18178   }
18179 
18180   // A value is in a flag enum if either its bits are a subset of the enum's
18181   // flag bits (the first condition) or we are allowing masks and the same is
18182   // true of its complement (the second condition). When masks are allowed, we
18183   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18184   //
18185   // While it's true that any value could be used as a mask, the assumption is
18186   // that a mask will have all of the insignificant bits set. Anything else is
18187   // likely a logic error.
18188   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18189   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18190 }
18191 
18192 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18193                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18194                          const ParsedAttributesView &Attrs) {
18195   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18196   QualType EnumType = Context.getTypeDeclType(Enum);
18197 
18198   ProcessDeclAttributeList(S, Enum, Attrs);
18199 
18200   if (Enum->isDependentType()) {
18201     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18202       EnumConstantDecl *ECD =
18203         cast_or_null<EnumConstantDecl>(Elements[i]);
18204       if (!ECD) continue;
18205 
18206       ECD->setType(EnumType);
18207     }
18208 
18209     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18210     return;
18211   }
18212 
18213   // TODO: If the result value doesn't fit in an int, it must be a long or long
18214   // long value.  ISO C does not support this, but GCC does as an extension,
18215   // emit a warning.
18216   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18217   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18218   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18219 
18220   // Verify that all the values are okay, compute the size of the values, and
18221   // reverse the list.
18222   unsigned NumNegativeBits = 0;
18223   unsigned NumPositiveBits = 0;
18224 
18225   // Keep track of whether all elements have type int.
18226   bool AllElementsInt = true;
18227 
18228   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18229     EnumConstantDecl *ECD =
18230       cast_or_null<EnumConstantDecl>(Elements[i]);
18231     if (!ECD) continue;  // Already issued a diagnostic.
18232 
18233     const llvm::APSInt &InitVal = ECD->getInitVal();
18234 
18235     // Keep track of the size of positive and negative values.
18236     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18237       NumPositiveBits = std::max(NumPositiveBits,
18238                                  (unsigned)InitVal.getActiveBits());
18239     else
18240       NumNegativeBits = std::max(NumNegativeBits,
18241                                  (unsigned)InitVal.getMinSignedBits());
18242 
18243     // Keep track of whether every enum element has type int (very common).
18244     if (AllElementsInt)
18245       AllElementsInt = ECD->getType() == Context.IntTy;
18246   }
18247 
18248   // Figure out the type that should be used for this enum.
18249   QualType BestType;
18250   unsigned BestWidth;
18251 
18252   // C++0x N3000 [conv.prom]p3:
18253   //   An rvalue of an unscoped enumeration type whose underlying
18254   //   type is not fixed can be converted to an rvalue of the first
18255   //   of the following types that can represent all the values of
18256   //   the enumeration: int, unsigned int, long int, unsigned long
18257   //   int, long long int, or unsigned long long int.
18258   // C99 6.4.4.3p2:
18259   //   An identifier declared as an enumeration constant has type int.
18260   // The C99 rule is modified by a gcc extension
18261   QualType BestPromotionType;
18262 
18263   bool Packed = Enum->hasAttr<PackedAttr>();
18264   // -fshort-enums is the equivalent to specifying the packed attribute on all
18265   // enum definitions.
18266   if (LangOpts.ShortEnums)
18267     Packed = true;
18268 
18269   // If the enum already has a type because it is fixed or dictated by the
18270   // target, promote that type instead of analyzing the enumerators.
18271   if (Enum->isComplete()) {
18272     BestType = Enum->getIntegerType();
18273     if (BestType->isPromotableIntegerType())
18274       BestPromotionType = Context.getPromotedIntegerType(BestType);
18275     else
18276       BestPromotionType = BestType;
18277 
18278     BestWidth = Context.getIntWidth(BestType);
18279   }
18280   else if (NumNegativeBits) {
18281     // If there is a negative value, figure out the smallest integer type (of
18282     // int/long/longlong) that fits.
18283     // If it's packed, check also if it fits a char or a short.
18284     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18285       BestType = Context.SignedCharTy;
18286       BestWidth = CharWidth;
18287     } else if (Packed && NumNegativeBits <= ShortWidth &&
18288                NumPositiveBits < ShortWidth) {
18289       BestType = Context.ShortTy;
18290       BestWidth = ShortWidth;
18291     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18292       BestType = Context.IntTy;
18293       BestWidth = IntWidth;
18294     } else {
18295       BestWidth = Context.getTargetInfo().getLongWidth();
18296 
18297       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18298         BestType = Context.LongTy;
18299       } else {
18300         BestWidth = Context.getTargetInfo().getLongLongWidth();
18301 
18302         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18303           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18304         BestType = Context.LongLongTy;
18305       }
18306     }
18307     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18308   } else {
18309     // If there is no negative value, figure out the smallest type that fits
18310     // all of the enumerator values.
18311     // If it's packed, check also if it fits a char or a short.
18312     if (Packed && NumPositiveBits <= CharWidth) {
18313       BestType = Context.UnsignedCharTy;
18314       BestPromotionType = Context.IntTy;
18315       BestWidth = CharWidth;
18316     } else if (Packed && NumPositiveBits <= ShortWidth) {
18317       BestType = Context.UnsignedShortTy;
18318       BestPromotionType = Context.IntTy;
18319       BestWidth = ShortWidth;
18320     } else if (NumPositiveBits <= IntWidth) {
18321       BestType = Context.UnsignedIntTy;
18322       BestWidth = IntWidth;
18323       BestPromotionType
18324         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18325                            ? Context.UnsignedIntTy : Context.IntTy;
18326     } else if (NumPositiveBits <=
18327                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18328       BestType = Context.UnsignedLongTy;
18329       BestPromotionType
18330         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18331                            ? Context.UnsignedLongTy : Context.LongTy;
18332     } else {
18333       BestWidth = Context.getTargetInfo().getLongLongWidth();
18334       assert(NumPositiveBits <= BestWidth &&
18335              "How could an initializer get larger than ULL?");
18336       BestType = Context.UnsignedLongLongTy;
18337       BestPromotionType
18338         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18339                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18340     }
18341   }
18342 
18343   // Loop over all of the enumerator constants, changing their types to match
18344   // the type of the enum if needed.
18345   for (auto *D : Elements) {
18346     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18347     if (!ECD) continue;  // Already issued a diagnostic.
18348 
18349     // Standard C says the enumerators have int type, but we allow, as an
18350     // extension, the enumerators to be larger than int size.  If each
18351     // enumerator value fits in an int, type it as an int, otherwise type it the
18352     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18353     // that X has type 'int', not 'unsigned'.
18354 
18355     // Determine whether the value fits into an int.
18356     llvm::APSInt InitVal = ECD->getInitVal();
18357 
18358     // If it fits into an integer type, force it.  Otherwise force it to match
18359     // the enum decl type.
18360     QualType NewTy;
18361     unsigned NewWidth;
18362     bool NewSign;
18363     if (!getLangOpts().CPlusPlus &&
18364         !Enum->isFixed() &&
18365         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18366       NewTy = Context.IntTy;
18367       NewWidth = IntWidth;
18368       NewSign = true;
18369     } else if (ECD->getType() == BestType) {
18370       // Already the right type!
18371       if (getLangOpts().CPlusPlus)
18372         // C++ [dcl.enum]p4: Following the closing brace of an
18373         // enum-specifier, each enumerator has the type of its
18374         // enumeration.
18375         ECD->setType(EnumType);
18376       continue;
18377     } else {
18378       NewTy = BestType;
18379       NewWidth = BestWidth;
18380       NewSign = BestType->isSignedIntegerOrEnumerationType();
18381     }
18382 
18383     // Adjust the APSInt value.
18384     InitVal = InitVal.extOrTrunc(NewWidth);
18385     InitVal.setIsSigned(NewSign);
18386     ECD->setInitVal(InitVal);
18387 
18388     // Adjust the Expr initializer and type.
18389     if (ECD->getInitExpr() &&
18390         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18391       ECD->setInitExpr(ImplicitCastExpr::Create(
18392           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18393           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18394     if (getLangOpts().CPlusPlus)
18395       // C++ [dcl.enum]p4: Following the closing brace of an
18396       // enum-specifier, each enumerator has the type of its
18397       // enumeration.
18398       ECD->setType(EnumType);
18399     else
18400       ECD->setType(NewTy);
18401   }
18402 
18403   Enum->completeDefinition(BestType, BestPromotionType,
18404                            NumPositiveBits, NumNegativeBits);
18405 
18406   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18407 
18408   if (Enum->isClosedFlag()) {
18409     for (Decl *D : Elements) {
18410       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18411       if (!ECD) continue;  // Already issued a diagnostic.
18412 
18413       llvm::APSInt InitVal = ECD->getInitVal();
18414       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18415           !IsValueInFlagEnum(Enum, InitVal, true))
18416         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18417           << ECD << Enum;
18418     }
18419   }
18420 
18421   // Now that the enum type is defined, ensure it's not been underaligned.
18422   if (Enum->hasAttrs())
18423     CheckAlignasUnderalignment(Enum);
18424 }
18425 
18426 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18427                                   SourceLocation StartLoc,
18428                                   SourceLocation EndLoc) {
18429   StringLiteral *AsmString = cast<StringLiteral>(expr);
18430 
18431   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18432                                                    AsmString, StartLoc,
18433                                                    EndLoc);
18434   CurContext->addDecl(New);
18435   return New;
18436 }
18437 
18438 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18439                                       IdentifierInfo* AliasName,
18440                                       SourceLocation PragmaLoc,
18441                                       SourceLocation NameLoc,
18442                                       SourceLocation AliasNameLoc) {
18443   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18444                                          LookupOrdinaryName);
18445   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18446                            AttributeCommonInfo::AS_Pragma);
18447   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18448       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18449 
18450   // If a declaration that:
18451   // 1) declares a function or a variable
18452   // 2) has external linkage
18453   // already exists, add a label attribute to it.
18454   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18455     if (isDeclExternC(PrevDecl))
18456       PrevDecl->addAttr(Attr);
18457     else
18458       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18459           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18460   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18461   } else
18462     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18463 }
18464 
18465 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18466                              SourceLocation PragmaLoc,
18467                              SourceLocation NameLoc) {
18468   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18469 
18470   if (PrevDecl) {
18471     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18472   } else {
18473     (void)WeakUndeclaredIdentifiers.insert(
18474       std::pair<IdentifierInfo*,WeakInfo>
18475         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18476   }
18477 }
18478 
18479 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18480                                 IdentifierInfo* AliasName,
18481                                 SourceLocation PragmaLoc,
18482                                 SourceLocation NameLoc,
18483                                 SourceLocation AliasNameLoc) {
18484   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18485                                     LookupOrdinaryName);
18486   WeakInfo W = WeakInfo(Name, NameLoc);
18487 
18488   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18489     if (!PrevDecl->hasAttr<AliasAttr>())
18490       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18491         DeclApplyPragmaWeak(TUScope, ND, W);
18492   } else {
18493     (void)WeakUndeclaredIdentifiers.insert(
18494       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18495   }
18496 }
18497 
18498 Decl *Sema::getObjCDeclContext() const {
18499   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18500 }
18501 
18502 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18503                                                      bool Final) {
18504   assert(FD && "Expected non-null FunctionDecl");
18505 
18506   // SYCL functions can be template, so we check if they have appropriate
18507   // attribute prior to checking if it is a template.
18508   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18509     return FunctionEmissionStatus::Emitted;
18510 
18511   // Templates are emitted when they're instantiated.
18512   if (FD->isDependentContext())
18513     return FunctionEmissionStatus::TemplateDiscarded;
18514 
18515   // Check whether this function is an externally visible definition.
18516   auto IsEmittedForExternalSymbol = [this, FD]() {
18517     // We have to check the GVA linkage of the function's *definition* -- if we
18518     // only have a declaration, we don't know whether or not the function will
18519     // be emitted, because (say) the definition could include "inline".
18520     FunctionDecl *Def = FD->getDefinition();
18521 
18522     return Def && !isDiscardableGVALinkage(
18523                       getASTContext().GetGVALinkageForFunction(Def));
18524   };
18525 
18526   if (LangOpts.OpenMPIsDevice) {
18527     // In OpenMP device mode we will not emit host only functions, or functions
18528     // we don't need due to their linkage.
18529     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18530         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18531     // DevTy may be changed later by
18532     //  #pragma omp declare target to(*) device_type(*).
18533     // Therefore DevTy having no value does not imply host. The emission status
18534     // will be checked again at the end of compilation unit with Final = true.
18535     if (DevTy.hasValue())
18536       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18537         return FunctionEmissionStatus::OMPDiscarded;
18538     // If we have an explicit value for the device type, or we are in a target
18539     // declare context, we need to emit all extern and used symbols.
18540     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18541       if (IsEmittedForExternalSymbol())
18542         return FunctionEmissionStatus::Emitted;
18543     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18544     // we'll omit it.
18545     if (Final)
18546       return FunctionEmissionStatus::OMPDiscarded;
18547   } else if (LangOpts.OpenMP > 45) {
18548     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18549     // function. In 5.0, no_host was introduced which might cause a function to
18550     // be ommitted.
18551     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18552         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18553     if (DevTy.hasValue())
18554       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18555         return FunctionEmissionStatus::OMPDiscarded;
18556   }
18557 
18558   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18559     return FunctionEmissionStatus::Emitted;
18560 
18561   if (LangOpts.CUDA) {
18562     // When compiling for device, host functions are never emitted.  Similarly,
18563     // when compiling for host, device and global functions are never emitted.
18564     // (Technically, we do emit a host-side stub for global functions, but this
18565     // doesn't count for our purposes here.)
18566     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18567     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18568       return FunctionEmissionStatus::CUDADiscarded;
18569     if (!LangOpts.CUDAIsDevice &&
18570         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18571       return FunctionEmissionStatus::CUDADiscarded;
18572 
18573     if (IsEmittedForExternalSymbol())
18574       return FunctionEmissionStatus::Emitted;
18575   }
18576 
18577   // Otherwise, the function is known-emitted if it's in our set of
18578   // known-emitted functions.
18579   return FunctionEmissionStatus::Unknown;
18580 }
18581 
18582 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18583   // Host-side references to a __global__ function refer to the stub, so the
18584   // function itself is never emitted and therefore should not be marked.
18585   // If we have host fn calls kernel fn calls host+device, the HD function
18586   // does not get instantiated on the host. We model this by omitting at the
18587   // call to the kernel from the callgraph. This ensures that, when compiling
18588   // for host, only HD functions actually called from the host get marked as
18589   // known-emitted.
18590   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18591          IdentifyCUDATarget(Callee) == CFT_Global;
18592 }
18593