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, false,
2117                                            Type->isFunctionProtoType());
2118   New->setImplicit();
2119   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2120 
2121   // Create Decl objects for each parameter, adding them to the
2122   // FunctionDecl.
2123   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2124     SmallVector<ParmVarDecl *, 16> Params;
2125     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2126       ParmVarDecl *parm = ParmVarDecl::Create(
2127           Context, New, SourceLocation(), SourceLocation(), nullptr,
2128           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2129       parm->setScopeInfo(0, i);
2130       Params.push_back(parm);
2131     }
2132     New->setParams(Params);
2133   }
2134 
2135   AddKnownFunctionAttributes(New);
2136   return New;
2137 }
2138 
2139 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2140 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2141 /// if we're creating this built-in in anticipation of redeclaring the
2142 /// built-in.
2143 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2144                                      Scope *S, bool ForRedeclaration,
2145                                      SourceLocation Loc) {
2146   LookupNecessaryTypesForBuiltin(S, ID);
2147 
2148   ASTContext::GetBuiltinTypeError Error;
2149   QualType R = Context.GetBuiltinType(ID, Error);
2150   if (Error) {
2151     if (!ForRedeclaration)
2152       return nullptr;
2153 
2154     // If we have a builtin without an associated type we should not emit a
2155     // warning when we were not able to find a type for it.
2156     if (Error == ASTContext::GE_Missing_type ||
2157         Context.BuiltinInfo.allowTypeMismatch(ID))
2158       return nullptr;
2159 
2160     // If we could not find a type for setjmp it is because the jmp_buf type was
2161     // not defined prior to the setjmp declaration.
2162     if (Error == ASTContext::GE_Missing_setjmp) {
2163       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2164           << Context.BuiltinInfo.getName(ID);
2165       return nullptr;
2166     }
2167 
2168     // Generally, we emit a warning that the declaration requires the
2169     // appropriate header.
2170     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2171         << getHeaderName(Context.BuiltinInfo, ID, Error)
2172         << Context.BuiltinInfo.getName(ID);
2173     return nullptr;
2174   }
2175 
2176   if (!ForRedeclaration &&
2177       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2178        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2179     Diag(Loc, diag::ext_implicit_lib_function_decl)
2180         << Context.BuiltinInfo.getName(ID) << R;
2181     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2182       Diag(Loc, diag::note_include_header_or_declare)
2183           << Header << Context.BuiltinInfo.getName(ID);
2184   }
2185 
2186   if (R.isNull())
2187     return nullptr;
2188 
2189   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2190   RegisterLocallyScopedExternCDecl(New, S);
2191 
2192   // TUScope is the translation-unit scope to insert this function into.
2193   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2194   // relate Scopes to DeclContexts, and probably eliminate CurContext
2195   // entirely, but we're not there yet.
2196   DeclContext *SavedContext = CurContext;
2197   CurContext = New->getDeclContext();
2198   PushOnScopeChains(New, TUScope);
2199   CurContext = SavedContext;
2200   return New;
2201 }
2202 
2203 /// Typedef declarations don't have linkage, but they still denote the same
2204 /// entity if their types are the same.
2205 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2206 /// isSameEntity.
2207 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2208                                                      TypedefNameDecl *Decl,
2209                                                      LookupResult &Previous) {
2210   // This is only interesting when modules are enabled.
2211   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2212     return;
2213 
2214   // Empty sets are uninteresting.
2215   if (Previous.empty())
2216     return;
2217 
2218   LookupResult::Filter Filter = Previous.makeFilter();
2219   while (Filter.hasNext()) {
2220     NamedDecl *Old = Filter.next();
2221 
2222     // Non-hidden declarations are never ignored.
2223     if (S.isVisible(Old))
2224       continue;
2225 
2226     // Declarations of the same entity are not ignored, even if they have
2227     // different linkages.
2228     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2229       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2230                                 Decl->getUnderlyingType()))
2231         continue;
2232 
2233       // If both declarations give a tag declaration a typedef name for linkage
2234       // purposes, then they declare the same entity.
2235       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2236           Decl->getAnonDeclWithTypedefName())
2237         continue;
2238     }
2239 
2240     Filter.erase();
2241   }
2242 
2243   Filter.done();
2244 }
2245 
2246 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2247   QualType OldType;
2248   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2249     OldType = OldTypedef->getUnderlyingType();
2250   else
2251     OldType = Context.getTypeDeclType(Old);
2252   QualType NewType = New->getUnderlyingType();
2253 
2254   if (NewType->isVariablyModifiedType()) {
2255     // Must not redefine a typedef with a variably-modified type.
2256     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2257     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2258       << Kind << NewType;
2259     if (Old->getLocation().isValid())
2260       notePreviousDefinition(Old, New->getLocation());
2261     New->setInvalidDecl();
2262     return true;
2263   }
2264 
2265   if (OldType != NewType &&
2266       !OldType->isDependentType() &&
2267       !NewType->isDependentType() &&
2268       !Context.hasSameType(OldType, NewType)) {
2269     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2270     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2271       << Kind << NewType << OldType;
2272     if (Old->getLocation().isValid())
2273       notePreviousDefinition(Old, New->getLocation());
2274     New->setInvalidDecl();
2275     return true;
2276   }
2277   return false;
2278 }
2279 
2280 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2281 /// same name and scope as a previous declaration 'Old'.  Figure out
2282 /// how to resolve this situation, merging decls or emitting
2283 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2284 ///
2285 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2286                                 LookupResult &OldDecls) {
2287   // If the new decl is known invalid already, don't bother doing any
2288   // merging checks.
2289   if (New->isInvalidDecl()) return;
2290 
2291   // Allow multiple definitions for ObjC built-in typedefs.
2292   // FIXME: Verify the underlying types are equivalent!
2293   if (getLangOpts().ObjC) {
2294     const IdentifierInfo *TypeID = New->getIdentifier();
2295     switch (TypeID->getLength()) {
2296     default: break;
2297     case 2:
2298       {
2299         if (!TypeID->isStr("id"))
2300           break;
2301         QualType T = New->getUnderlyingType();
2302         if (!T->isPointerType())
2303           break;
2304         if (!T->isVoidPointerType()) {
2305           QualType PT = T->castAs<PointerType>()->getPointeeType();
2306           if (!PT->isStructureType())
2307             break;
2308         }
2309         Context.setObjCIdRedefinitionType(T);
2310         // Install the built-in type for 'id', ignoring the current definition.
2311         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2312         return;
2313       }
2314     case 5:
2315       if (!TypeID->isStr("Class"))
2316         break;
2317       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2318       // Install the built-in type for 'Class', ignoring the current definition.
2319       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2320       return;
2321     case 3:
2322       if (!TypeID->isStr("SEL"))
2323         break;
2324       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2325       // Install the built-in type for 'SEL', ignoring the current definition.
2326       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2327       return;
2328     }
2329     // Fall through - the typedef name was not a builtin type.
2330   }
2331 
2332   // Verify the old decl was also a type.
2333   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2334   if (!Old) {
2335     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2336       << New->getDeclName();
2337 
2338     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2339     if (OldD->getLocation().isValid())
2340       notePreviousDefinition(OldD, New->getLocation());
2341 
2342     return New->setInvalidDecl();
2343   }
2344 
2345   // If the old declaration is invalid, just give up here.
2346   if (Old->isInvalidDecl())
2347     return New->setInvalidDecl();
2348 
2349   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2350     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2351     auto *NewTag = New->getAnonDeclWithTypedefName();
2352     NamedDecl *Hidden = nullptr;
2353     if (OldTag && NewTag &&
2354         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2355         !hasVisibleDefinition(OldTag, &Hidden)) {
2356       // There is a definition of this tag, but it is not visible. Use it
2357       // instead of our tag.
2358       New->setTypeForDecl(OldTD->getTypeForDecl());
2359       if (OldTD->isModed())
2360         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2361                                     OldTD->getUnderlyingType());
2362       else
2363         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2364 
2365       // Make the old tag definition visible.
2366       makeMergedDefinitionVisible(Hidden);
2367 
2368       // If this was an unscoped enumeration, yank all of its enumerators
2369       // out of the scope.
2370       if (isa<EnumDecl>(NewTag)) {
2371         Scope *EnumScope = getNonFieldDeclScope(S);
2372         for (auto *D : NewTag->decls()) {
2373           auto *ED = cast<EnumConstantDecl>(D);
2374           assert(EnumScope->isDeclScope(ED));
2375           EnumScope->RemoveDecl(ED);
2376           IdResolver.RemoveDecl(ED);
2377           ED->getLexicalDeclContext()->removeDecl(ED);
2378         }
2379       }
2380     }
2381   }
2382 
2383   // If the typedef types are not identical, reject them in all languages and
2384   // with any extensions enabled.
2385   if (isIncompatibleTypedef(Old, New))
2386     return;
2387 
2388   // The types match.  Link up the redeclaration chain and merge attributes if
2389   // the old declaration was a typedef.
2390   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2391     New->setPreviousDecl(Typedef);
2392     mergeDeclAttributes(New, Old);
2393   }
2394 
2395   if (getLangOpts().MicrosoftExt)
2396     return;
2397 
2398   if (getLangOpts().CPlusPlus) {
2399     // C++ [dcl.typedef]p2:
2400     //   In a given non-class scope, a typedef specifier can be used to
2401     //   redefine the name of any type declared in that scope to refer
2402     //   to the type to which it already refers.
2403     if (!isa<CXXRecordDecl>(CurContext))
2404       return;
2405 
2406     // C++0x [dcl.typedef]p4:
2407     //   In a given class scope, a typedef specifier can be used to redefine
2408     //   any class-name declared in that scope that is not also a typedef-name
2409     //   to refer to the type to which it already refers.
2410     //
2411     // This wording came in via DR424, which was a correction to the
2412     // wording in DR56, which accidentally banned code like:
2413     //
2414     //   struct S {
2415     //     typedef struct A { } A;
2416     //   };
2417     //
2418     // in the C++03 standard. We implement the C++0x semantics, which
2419     // allow the above but disallow
2420     //
2421     //   struct S {
2422     //     typedef int I;
2423     //     typedef int I;
2424     //   };
2425     //
2426     // since that was the intent of DR56.
2427     if (!isa<TypedefNameDecl>(Old))
2428       return;
2429 
2430     Diag(New->getLocation(), diag::err_redefinition)
2431       << New->getDeclName();
2432     notePreviousDefinition(Old, New->getLocation());
2433     return New->setInvalidDecl();
2434   }
2435 
2436   // Modules always permit redefinition of typedefs, as does C11.
2437   if (getLangOpts().Modules || getLangOpts().C11)
2438     return;
2439 
2440   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2441   // is normally mapped to an error, but can be controlled with
2442   // -Wtypedef-redefinition.  If either the original or the redefinition is
2443   // in a system header, don't emit this for compatibility with GCC.
2444   if (getDiagnostics().getSuppressSystemWarnings() &&
2445       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2446       (Old->isImplicit() ||
2447        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2448        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2449     return;
2450 
2451   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2452     << New->getDeclName();
2453   notePreviousDefinition(Old, New->getLocation());
2454 }
2455 
2456 /// DeclhasAttr - returns true if decl Declaration already has the target
2457 /// attribute.
2458 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2459   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2460   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2461   for (const auto *i : D->attrs())
2462     if (i->getKind() == A->getKind()) {
2463       if (Ann) {
2464         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2465           return true;
2466         continue;
2467       }
2468       // FIXME: Don't hardcode this check
2469       if (OA && isa<OwnershipAttr>(i))
2470         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2471       return true;
2472     }
2473 
2474   return false;
2475 }
2476 
2477 static bool isAttributeTargetADefinition(Decl *D) {
2478   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2479     return VD->isThisDeclarationADefinition();
2480   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2481     return TD->isCompleteDefinition() || TD->isBeingDefined();
2482   return true;
2483 }
2484 
2485 /// Merge alignment attributes from \p Old to \p New, taking into account the
2486 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2487 ///
2488 /// \return \c true if any attributes were added to \p New.
2489 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2490   // Look for alignas attributes on Old, and pick out whichever attribute
2491   // specifies the strictest alignment requirement.
2492   AlignedAttr *OldAlignasAttr = nullptr;
2493   AlignedAttr *OldStrictestAlignAttr = nullptr;
2494   unsigned OldAlign = 0;
2495   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2496     // FIXME: We have no way of representing inherited dependent alignments
2497     // in a case like:
2498     //   template<int A, int B> struct alignas(A) X;
2499     //   template<int A, int B> struct alignas(B) X {};
2500     // For now, we just ignore any alignas attributes which are not on the
2501     // definition in such a case.
2502     if (I->isAlignmentDependent())
2503       return false;
2504 
2505     if (I->isAlignas())
2506       OldAlignasAttr = I;
2507 
2508     unsigned Align = I->getAlignment(S.Context);
2509     if (Align > OldAlign) {
2510       OldAlign = Align;
2511       OldStrictestAlignAttr = I;
2512     }
2513   }
2514 
2515   // Look for alignas attributes on New.
2516   AlignedAttr *NewAlignasAttr = nullptr;
2517   unsigned NewAlign = 0;
2518   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2519     if (I->isAlignmentDependent())
2520       return false;
2521 
2522     if (I->isAlignas())
2523       NewAlignasAttr = I;
2524 
2525     unsigned Align = I->getAlignment(S.Context);
2526     if (Align > NewAlign)
2527       NewAlign = Align;
2528   }
2529 
2530   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2531     // Both declarations have 'alignas' attributes. We require them to match.
2532     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2533     // fall short. (If two declarations both have alignas, they must both match
2534     // every definition, and so must match each other if there is a definition.)
2535 
2536     // If either declaration only contains 'alignas(0)' specifiers, then it
2537     // specifies the natural alignment for the type.
2538     if (OldAlign == 0 || NewAlign == 0) {
2539       QualType Ty;
2540       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2541         Ty = VD->getType();
2542       else
2543         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2544 
2545       if (OldAlign == 0)
2546         OldAlign = S.Context.getTypeAlign(Ty);
2547       if (NewAlign == 0)
2548         NewAlign = S.Context.getTypeAlign(Ty);
2549     }
2550 
2551     if (OldAlign != NewAlign) {
2552       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2553         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2554         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2555       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2556     }
2557   }
2558 
2559   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2560     // C++11 [dcl.align]p6:
2561     //   if any declaration of an entity has an alignment-specifier,
2562     //   every defining declaration of that entity shall specify an
2563     //   equivalent alignment.
2564     // C11 6.7.5/7:
2565     //   If the definition of an object does not have an alignment
2566     //   specifier, any other declaration of that object shall also
2567     //   have no alignment specifier.
2568     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2569       << OldAlignasAttr;
2570     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2571       << OldAlignasAttr;
2572   }
2573 
2574   bool AnyAdded = false;
2575 
2576   // Ensure we have an attribute representing the strictest alignment.
2577   if (OldAlign > NewAlign) {
2578     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2579     Clone->setInherited(true);
2580     New->addAttr(Clone);
2581     AnyAdded = true;
2582   }
2583 
2584   // Ensure we have an alignas attribute if the old declaration had one.
2585   if (OldAlignasAttr && !NewAlignasAttr &&
2586       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2587     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2588     Clone->setInherited(true);
2589     New->addAttr(Clone);
2590     AnyAdded = true;
2591   }
2592 
2593   return AnyAdded;
2594 }
2595 
2596 #define WANT_DECL_MERGE_LOGIC
2597 #include "clang/Sema/AttrParsedAttrImpl.inc"
2598 #undef WANT_DECL_MERGE_LOGIC
2599 
2600 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2601                                const InheritableAttr *Attr,
2602                                Sema::AvailabilityMergeKind AMK) {
2603   // Diagnose any mutual exclusions between the attribute that we want to add
2604   // and attributes that already exist on the declaration.
2605   if (!DiagnoseMutualExclusions(S, D, Attr))
2606     return false;
2607 
2608   // This function copies an attribute Attr from a previous declaration to the
2609   // new declaration D if the new declaration doesn't itself have that attribute
2610   // yet or if that attribute allows duplicates.
2611   // If you're adding a new attribute that requires logic different from
2612   // "use explicit attribute on decl if present, else use attribute from
2613   // previous decl", for example if the attribute needs to be consistent
2614   // between redeclarations, you need to call a custom merge function here.
2615   InheritableAttr *NewAttr = nullptr;
2616   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2617     NewAttr = S.mergeAvailabilityAttr(
2618         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2619         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2620         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2621         AA->getPriority());
2622   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2623     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2624   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2625     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2626   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2627     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2628   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2629     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2630   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2631     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2632                                 FA->getFirstArg());
2633   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2634     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2635   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2636     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2637   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2638     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2639                                        IA->getInheritanceModel());
2640   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2641     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2642                                       &S.Context.Idents.get(AA->getSpelling()));
2643   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2644            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2645             isa<CUDAGlobalAttr>(Attr))) {
2646     // CUDA target attributes are part of function signature for
2647     // overloading purposes and must not be merged.
2648     return false;
2649   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2650     NewAttr = S.mergeMinSizeAttr(D, *MA);
2651   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2652     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2653   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2654     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2655   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2656     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2657   else if (isa<AlignedAttr>(Attr))
2658     // AlignedAttrs are handled separately, because we need to handle all
2659     // such attributes on a declaration at the same time.
2660     NewAttr = nullptr;
2661   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2662            (AMK == Sema::AMK_Override ||
2663             AMK == Sema::AMK_ProtocolImplementation ||
2664             AMK == Sema::AMK_OptionalProtocolImplementation))
2665     NewAttr = nullptr;
2666   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2667     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2668   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2669     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2670   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2671     NewAttr = S.mergeImportNameAttr(D, *INA);
2672   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2673     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2674   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2675     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2676   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2677     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2678 
2679   if (NewAttr) {
2680     NewAttr->setInherited(true);
2681     D->addAttr(NewAttr);
2682     if (isa<MSInheritanceAttr>(NewAttr))
2683       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2684     return true;
2685   }
2686 
2687   return false;
2688 }
2689 
2690 static const NamedDecl *getDefinition(const Decl *D) {
2691   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2692     return TD->getDefinition();
2693   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2694     const VarDecl *Def = VD->getDefinition();
2695     if (Def)
2696       return Def;
2697     return VD->getActingDefinition();
2698   }
2699   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2700     const FunctionDecl *Def = nullptr;
2701     if (FD->isDefined(Def, true))
2702       return Def;
2703   }
2704   return nullptr;
2705 }
2706 
2707 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2708   for (const auto *Attribute : D->attrs())
2709     if (Attribute->getKind() == Kind)
2710       return true;
2711   return false;
2712 }
2713 
2714 /// checkNewAttributesAfterDef - If we already have a definition, check that
2715 /// there are no new attributes in this declaration.
2716 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2717   if (!New->hasAttrs())
2718     return;
2719 
2720   const NamedDecl *Def = getDefinition(Old);
2721   if (!Def || Def == New)
2722     return;
2723 
2724   AttrVec &NewAttributes = New->getAttrs();
2725   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2726     const Attr *NewAttribute = NewAttributes[I];
2727 
2728     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2729       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2730         Sema::SkipBodyInfo SkipBody;
2731         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2732 
2733         // If we're skipping this definition, drop the "alias" attribute.
2734         if (SkipBody.ShouldSkip) {
2735           NewAttributes.erase(NewAttributes.begin() + I);
2736           --E;
2737           continue;
2738         }
2739       } else {
2740         VarDecl *VD = cast<VarDecl>(New);
2741         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2742                                 VarDecl::TentativeDefinition
2743                             ? diag::err_alias_after_tentative
2744                             : diag::err_redefinition;
2745         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2746         if (Diag == diag::err_redefinition)
2747           S.notePreviousDefinition(Def, VD->getLocation());
2748         else
2749           S.Diag(Def->getLocation(), diag::note_previous_definition);
2750         VD->setInvalidDecl();
2751       }
2752       ++I;
2753       continue;
2754     }
2755 
2756     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2757       // Tentative definitions are only interesting for the alias check above.
2758       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2759         ++I;
2760         continue;
2761       }
2762     }
2763 
2764     if (hasAttribute(Def, NewAttribute->getKind())) {
2765       ++I;
2766       continue; // regular attr merging will take care of validating this.
2767     }
2768 
2769     if (isa<C11NoReturnAttr>(NewAttribute)) {
2770       // C's _Noreturn is allowed to be added to a function after it is defined.
2771       ++I;
2772       continue;
2773     } else if (isa<UuidAttr>(NewAttribute)) {
2774       // msvc will allow a subsequent definition to add an uuid to a class
2775       ++I;
2776       continue;
2777     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2778       if (AA->isAlignas()) {
2779         // C++11 [dcl.align]p6:
2780         //   if any declaration of an entity has an alignment-specifier,
2781         //   every defining declaration of that entity shall specify an
2782         //   equivalent alignment.
2783         // C11 6.7.5/7:
2784         //   If the definition of an object does not have an alignment
2785         //   specifier, any other declaration of that object shall also
2786         //   have no alignment specifier.
2787         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2788           << AA;
2789         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2790           << AA;
2791         NewAttributes.erase(NewAttributes.begin() + I);
2792         --E;
2793         continue;
2794       }
2795     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2796       // If there is a C definition followed by a redeclaration with this
2797       // attribute then there are two different definitions. In C++, prefer the
2798       // standard diagnostics.
2799       if (!S.getLangOpts().CPlusPlus) {
2800         S.Diag(NewAttribute->getLocation(),
2801                diag::err_loader_uninitialized_redeclaration);
2802         S.Diag(Def->getLocation(), diag::note_previous_definition);
2803         NewAttributes.erase(NewAttributes.begin() + I);
2804         --E;
2805         continue;
2806       }
2807     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2808                cast<VarDecl>(New)->isInline() &&
2809                !cast<VarDecl>(New)->isInlineSpecified()) {
2810       // Don't warn about applying selectany to implicitly inline variables.
2811       // Older compilers and language modes would require the use of selectany
2812       // to make such variables inline, and it would have no effect if we
2813       // honored it.
2814       ++I;
2815       continue;
2816     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2817       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2818       // declarations after defintions.
2819       ++I;
2820       continue;
2821     }
2822 
2823     S.Diag(NewAttribute->getLocation(),
2824            diag::warn_attribute_precede_definition);
2825     S.Diag(Def->getLocation(), diag::note_previous_definition);
2826     NewAttributes.erase(NewAttributes.begin() + I);
2827     --E;
2828   }
2829 }
2830 
2831 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2832                                      const ConstInitAttr *CIAttr,
2833                                      bool AttrBeforeInit) {
2834   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2835 
2836   // Figure out a good way to write this specifier on the old declaration.
2837   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2838   // enough of the attribute list spelling information to extract that without
2839   // heroics.
2840   std::string SuitableSpelling;
2841   if (S.getLangOpts().CPlusPlus20)
2842     SuitableSpelling = std::string(
2843         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2844   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2845     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2846         InsertLoc, {tok::l_square, tok::l_square,
2847                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2848                     S.PP.getIdentifierInfo("require_constant_initialization"),
2849                     tok::r_square, tok::r_square}));
2850   if (SuitableSpelling.empty())
2851     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2852         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2853                     S.PP.getIdentifierInfo("require_constant_initialization"),
2854                     tok::r_paren, tok::r_paren}));
2855   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2856     SuitableSpelling = "constinit";
2857   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2858     SuitableSpelling = "[[clang::require_constant_initialization]]";
2859   if (SuitableSpelling.empty())
2860     SuitableSpelling = "__attribute__((require_constant_initialization))";
2861   SuitableSpelling += " ";
2862 
2863   if (AttrBeforeInit) {
2864     // extern constinit int a;
2865     // int a = 0; // error (missing 'constinit'), accepted as extension
2866     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2867     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2868         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2869     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2870   } else {
2871     // int a = 0;
2872     // constinit extern int a; // error (missing 'constinit')
2873     S.Diag(CIAttr->getLocation(),
2874            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2875                                  : diag::warn_require_const_init_added_too_late)
2876         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2877     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2878         << CIAttr->isConstinit()
2879         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2880   }
2881 }
2882 
2883 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2884 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2885                                AvailabilityMergeKind AMK) {
2886   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2887     UsedAttr *NewAttr = OldAttr->clone(Context);
2888     NewAttr->setInherited(true);
2889     New->addAttr(NewAttr);
2890   }
2891   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2892     RetainAttr *NewAttr = OldAttr->clone(Context);
2893     NewAttr->setInherited(true);
2894     New->addAttr(NewAttr);
2895   }
2896 
2897   if (!Old->hasAttrs() && !New->hasAttrs())
2898     return;
2899 
2900   // [dcl.constinit]p1:
2901   //   If the [constinit] specifier is applied to any declaration of a
2902   //   variable, it shall be applied to the initializing declaration.
2903   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2904   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2905   if (bool(OldConstInit) != bool(NewConstInit)) {
2906     const auto *OldVD = cast<VarDecl>(Old);
2907     auto *NewVD = cast<VarDecl>(New);
2908 
2909     // Find the initializing declaration. Note that we might not have linked
2910     // the new declaration into the redeclaration chain yet.
2911     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2912     if (!InitDecl &&
2913         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2914       InitDecl = NewVD;
2915 
2916     if (InitDecl == NewVD) {
2917       // This is the initializing declaration. If it would inherit 'constinit',
2918       // that's ill-formed. (Note that we do not apply this to the attribute
2919       // form).
2920       if (OldConstInit && OldConstInit->isConstinit())
2921         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2922                                  /*AttrBeforeInit=*/true);
2923     } else if (NewConstInit) {
2924       // This is the first time we've been told that this declaration should
2925       // have a constant initializer. If we already saw the initializing
2926       // declaration, this is too late.
2927       if (InitDecl && InitDecl != NewVD) {
2928         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2929                                  /*AttrBeforeInit=*/false);
2930         NewVD->dropAttr<ConstInitAttr>();
2931       }
2932     }
2933   }
2934 
2935   // Attributes declared post-definition are currently ignored.
2936   checkNewAttributesAfterDef(*this, New, Old);
2937 
2938   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2939     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2940       if (!OldA->isEquivalent(NewA)) {
2941         // This redeclaration changes __asm__ label.
2942         Diag(New->getLocation(), diag::err_different_asm_label);
2943         Diag(OldA->getLocation(), diag::note_previous_declaration);
2944       }
2945     } else if (Old->isUsed()) {
2946       // This redeclaration adds an __asm__ label to a declaration that has
2947       // already been ODR-used.
2948       Diag(New->getLocation(), diag::err_late_asm_label_name)
2949         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2950     }
2951   }
2952 
2953   // Re-declaration cannot add abi_tag's.
2954   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2955     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2956       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2957         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2958                       NewTag) == OldAbiTagAttr->tags_end()) {
2959           Diag(NewAbiTagAttr->getLocation(),
2960                diag::err_new_abi_tag_on_redeclaration)
2961               << NewTag;
2962           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2963         }
2964       }
2965     } else {
2966       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2967       Diag(Old->getLocation(), diag::note_previous_declaration);
2968     }
2969   }
2970 
2971   // This redeclaration adds a section attribute.
2972   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2973     if (auto *VD = dyn_cast<VarDecl>(New)) {
2974       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2975         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2976         Diag(Old->getLocation(), diag::note_previous_declaration);
2977       }
2978     }
2979   }
2980 
2981   // Redeclaration adds code-seg attribute.
2982   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2983   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2984       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2985     Diag(New->getLocation(), diag::warn_mismatched_section)
2986          << 0 /*codeseg*/;
2987     Diag(Old->getLocation(), diag::note_previous_declaration);
2988   }
2989 
2990   if (!Old->hasAttrs())
2991     return;
2992 
2993   bool foundAny = New->hasAttrs();
2994 
2995   // Ensure that any moving of objects within the allocated map is done before
2996   // we process them.
2997   if (!foundAny) New->setAttrs(AttrVec());
2998 
2999   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3000     // Ignore deprecated/unavailable/availability attributes if requested.
3001     AvailabilityMergeKind LocalAMK = AMK_None;
3002     if (isa<DeprecatedAttr>(I) ||
3003         isa<UnavailableAttr>(I) ||
3004         isa<AvailabilityAttr>(I)) {
3005       switch (AMK) {
3006       case AMK_None:
3007         continue;
3008 
3009       case AMK_Redeclaration:
3010       case AMK_Override:
3011       case AMK_ProtocolImplementation:
3012       case AMK_OptionalProtocolImplementation:
3013         LocalAMK = AMK;
3014         break;
3015       }
3016     }
3017 
3018     // Already handled.
3019     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3020       continue;
3021 
3022     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3023       foundAny = true;
3024   }
3025 
3026   if (mergeAlignedAttrs(*this, New, Old))
3027     foundAny = true;
3028 
3029   if (!foundAny) New->dropAttrs();
3030 }
3031 
3032 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3033 /// to the new one.
3034 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3035                                      const ParmVarDecl *oldDecl,
3036                                      Sema &S) {
3037   // C++11 [dcl.attr.depend]p2:
3038   //   The first declaration of a function shall specify the
3039   //   carries_dependency attribute for its declarator-id if any declaration
3040   //   of the function specifies the carries_dependency attribute.
3041   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3042   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3043     S.Diag(CDA->getLocation(),
3044            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3045     // Find the first declaration of the parameter.
3046     // FIXME: Should we build redeclaration chains for function parameters?
3047     const FunctionDecl *FirstFD =
3048       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3049     const ParmVarDecl *FirstVD =
3050       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3051     S.Diag(FirstVD->getLocation(),
3052            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3053   }
3054 
3055   if (!oldDecl->hasAttrs())
3056     return;
3057 
3058   bool foundAny = newDecl->hasAttrs();
3059 
3060   // Ensure that any moving of objects within the allocated map is
3061   // done before we process them.
3062   if (!foundAny) newDecl->setAttrs(AttrVec());
3063 
3064   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3065     if (!DeclHasAttr(newDecl, I)) {
3066       InheritableAttr *newAttr =
3067         cast<InheritableParamAttr>(I->clone(S.Context));
3068       newAttr->setInherited(true);
3069       newDecl->addAttr(newAttr);
3070       foundAny = true;
3071     }
3072   }
3073 
3074   if (!foundAny) newDecl->dropAttrs();
3075 }
3076 
3077 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3078                                 const ParmVarDecl *OldParam,
3079                                 Sema &S) {
3080   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3081     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3082       if (*Oldnullability != *Newnullability) {
3083         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3084           << DiagNullabilityKind(
3085                *Newnullability,
3086                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3087                 != 0))
3088           << DiagNullabilityKind(
3089                *Oldnullability,
3090                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3091                 != 0));
3092         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3093       }
3094     } else {
3095       QualType NewT = NewParam->getType();
3096       NewT = S.Context.getAttributedType(
3097                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3098                          NewT, NewT);
3099       NewParam->setType(NewT);
3100     }
3101   }
3102 }
3103 
3104 namespace {
3105 
3106 /// Used in MergeFunctionDecl to keep track of function parameters in
3107 /// C.
3108 struct GNUCompatibleParamWarning {
3109   ParmVarDecl *OldParm;
3110   ParmVarDecl *NewParm;
3111   QualType PromotedType;
3112 };
3113 
3114 } // end anonymous namespace
3115 
3116 // Determine whether the previous declaration was a definition, implicit
3117 // declaration, or a declaration.
3118 template <typename T>
3119 static std::pair<diag::kind, SourceLocation>
3120 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3121   diag::kind PrevDiag;
3122   SourceLocation OldLocation = Old->getLocation();
3123   if (Old->isThisDeclarationADefinition())
3124     PrevDiag = diag::note_previous_definition;
3125   else if (Old->isImplicit()) {
3126     PrevDiag = diag::note_previous_implicit_declaration;
3127     if (OldLocation.isInvalid())
3128       OldLocation = New->getLocation();
3129   } else
3130     PrevDiag = diag::note_previous_declaration;
3131   return std::make_pair(PrevDiag, OldLocation);
3132 }
3133 
3134 /// canRedefineFunction - checks if a function can be redefined. Currently,
3135 /// only extern inline functions can be redefined, and even then only in
3136 /// GNU89 mode.
3137 static bool canRedefineFunction(const FunctionDecl *FD,
3138                                 const LangOptions& LangOpts) {
3139   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3140           !LangOpts.CPlusPlus &&
3141           FD->isInlineSpecified() &&
3142           FD->getStorageClass() == SC_Extern);
3143 }
3144 
3145 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3146   const AttributedType *AT = T->getAs<AttributedType>();
3147   while (AT && !AT->isCallingConv())
3148     AT = AT->getModifiedType()->getAs<AttributedType>();
3149   return AT;
3150 }
3151 
3152 template <typename T>
3153 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3154   const DeclContext *DC = Old->getDeclContext();
3155   if (DC->isRecord())
3156     return false;
3157 
3158   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3159   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3160     return true;
3161   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3162     return true;
3163   return false;
3164 }
3165 
3166 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3167 static bool isExternC(VarTemplateDecl *) { return false; }
3168 static bool isExternC(FunctionTemplateDecl *) { return false; }
3169 
3170 /// Check whether a redeclaration of an entity introduced by a
3171 /// using-declaration is valid, given that we know it's not an overload
3172 /// (nor a hidden tag declaration).
3173 template<typename ExpectedDecl>
3174 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3175                                    ExpectedDecl *New) {
3176   // C++11 [basic.scope.declarative]p4:
3177   //   Given a set of declarations in a single declarative region, each of
3178   //   which specifies the same unqualified name,
3179   //   -- they shall all refer to the same entity, or all refer to functions
3180   //      and function templates; or
3181   //   -- exactly one declaration shall declare a class name or enumeration
3182   //      name that is not a typedef name and the other declarations shall all
3183   //      refer to the same variable or enumerator, or all refer to functions
3184   //      and function templates; in this case the class name or enumeration
3185   //      name is hidden (3.3.10).
3186 
3187   // C++11 [namespace.udecl]p14:
3188   //   If a function declaration in namespace scope or block scope has the
3189   //   same name and the same parameter-type-list as a function introduced
3190   //   by a using-declaration, and the declarations do not declare the same
3191   //   function, the program is ill-formed.
3192 
3193   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3194   if (Old &&
3195       !Old->getDeclContext()->getRedeclContext()->Equals(
3196           New->getDeclContext()->getRedeclContext()) &&
3197       !(isExternC(Old) && isExternC(New)))
3198     Old = nullptr;
3199 
3200   if (!Old) {
3201     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3202     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3203     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3204     return true;
3205   }
3206   return false;
3207 }
3208 
3209 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3210                                             const FunctionDecl *B) {
3211   assert(A->getNumParams() == B->getNumParams());
3212 
3213   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3214     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3215     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3216     if (AttrA == AttrB)
3217       return true;
3218     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3219            AttrA->isDynamic() == AttrB->isDynamic();
3220   };
3221 
3222   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3223 }
3224 
3225 /// If necessary, adjust the semantic declaration context for a qualified
3226 /// declaration to name the correct inline namespace within the qualifier.
3227 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3228                                                DeclaratorDecl *OldD) {
3229   // The only case where we need to update the DeclContext is when
3230   // redeclaration lookup for a qualified name finds a declaration
3231   // in an inline namespace within the context named by the qualifier:
3232   //
3233   //   inline namespace N { int f(); }
3234   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3235   //
3236   // For unqualified declarations, the semantic context *can* change
3237   // along the redeclaration chain (for local extern declarations,
3238   // extern "C" declarations, and friend declarations in particular).
3239   if (!NewD->getQualifier())
3240     return;
3241 
3242   // NewD is probably already in the right context.
3243   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3244   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3245   if (NamedDC->Equals(SemaDC))
3246     return;
3247 
3248   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3249           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3250          "unexpected context for redeclaration");
3251 
3252   auto *LexDC = NewD->getLexicalDeclContext();
3253   auto FixSemaDC = [=](NamedDecl *D) {
3254     if (!D)
3255       return;
3256     D->setDeclContext(SemaDC);
3257     D->setLexicalDeclContext(LexDC);
3258   };
3259 
3260   FixSemaDC(NewD);
3261   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3262     FixSemaDC(FD->getDescribedFunctionTemplate());
3263   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3264     FixSemaDC(VD->getDescribedVarTemplate());
3265 }
3266 
3267 /// MergeFunctionDecl - We just parsed a function 'New' from
3268 /// declarator D which has the same name and scope as a previous
3269 /// declaration 'Old'.  Figure out how to resolve this situation,
3270 /// merging decls or emitting diagnostics as appropriate.
3271 ///
3272 /// In C++, New and Old must be declarations that are not
3273 /// overloaded. Use IsOverload to determine whether New and Old are
3274 /// overloaded, and to select the Old declaration that New should be
3275 /// merged with.
3276 ///
3277 /// Returns true if there was an error, false otherwise.
3278 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3279                              Scope *S, bool MergeTypeWithOld) {
3280   // Verify the old decl was also a function.
3281   FunctionDecl *Old = OldD->getAsFunction();
3282   if (!Old) {
3283     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3284       if (New->getFriendObjectKind()) {
3285         Diag(New->getLocation(), diag::err_using_decl_friend);
3286         Diag(Shadow->getTargetDecl()->getLocation(),
3287              diag::note_using_decl_target);
3288         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3289             << 0;
3290         return true;
3291       }
3292 
3293       // Check whether the two declarations might declare the same function or
3294       // function template.
3295       if (FunctionTemplateDecl *NewTemplate =
3296               New->getDescribedFunctionTemplate()) {
3297         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3298                                                          NewTemplate))
3299           return true;
3300         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3301                          ->getAsFunction();
3302       } else {
3303         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3304           return true;
3305         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3306       }
3307     } else {
3308       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3309         << New->getDeclName();
3310       notePreviousDefinition(OldD, New->getLocation());
3311       return true;
3312     }
3313   }
3314 
3315   // If the old declaration was found in an inline namespace and the new
3316   // declaration was qualified, update the DeclContext to match.
3317   adjustDeclContextForDeclaratorDecl(New, Old);
3318 
3319   // If the old declaration is invalid, just give up here.
3320   if (Old->isInvalidDecl())
3321     return true;
3322 
3323   // Disallow redeclaration of some builtins.
3324   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3325     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3326     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3327         << Old << Old->getType();
3328     return true;
3329   }
3330 
3331   diag::kind PrevDiag;
3332   SourceLocation OldLocation;
3333   std::tie(PrevDiag, OldLocation) =
3334       getNoteDiagForInvalidRedeclaration(Old, New);
3335 
3336   // Don't complain about this if we're in GNU89 mode and the old function
3337   // is an extern inline function.
3338   // Don't complain about specializations. They are not supposed to have
3339   // storage classes.
3340   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3341       New->getStorageClass() == SC_Static &&
3342       Old->hasExternalFormalLinkage() &&
3343       !New->getTemplateSpecializationInfo() &&
3344       !canRedefineFunction(Old, getLangOpts())) {
3345     if (getLangOpts().MicrosoftExt) {
3346       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3347       Diag(OldLocation, PrevDiag);
3348     } else {
3349       Diag(New->getLocation(), diag::err_static_non_static) << New;
3350       Diag(OldLocation, PrevDiag);
3351       return true;
3352     }
3353   }
3354 
3355   if (New->hasAttr<InternalLinkageAttr>() &&
3356       !Old->hasAttr<InternalLinkageAttr>()) {
3357     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3358         << New->getDeclName();
3359     notePreviousDefinition(Old, New->getLocation());
3360     New->dropAttr<InternalLinkageAttr>();
3361   }
3362 
3363   if (CheckRedeclarationModuleOwnership(New, Old))
3364     return true;
3365 
3366   if (!getLangOpts().CPlusPlus) {
3367     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3368     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3369       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3370         << New << OldOvl;
3371 
3372       // Try our best to find a decl that actually has the overloadable
3373       // attribute for the note. In most cases (e.g. programs with only one
3374       // broken declaration/definition), this won't matter.
3375       //
3376       // FIXME: We could do this if we juggled some extra state in
3377       // OverloadableAttr, rather than just removing it.
3378       const Decl *DiagOld = Old;
3379       if (OldOvl) {
3380         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3381           const auto *A = D->getAttr<OverloadableAttr>();
3382           return A && !A->isImplicit();
3383         });
3384         // If we've implicitly added *all* of the overloadable attrs to this
3385         // chain, emitting a "previous redecl" note is pointless.
3386         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3387       }
3388 
3389       if (DiagOld)
3390         Diag(DiagOld->getLocation(),
3391              diag::note_attribute_overloadable_prev_overload)
3392           << OldOvl;
3393 
3394       if (OldOvl)
3395         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3396       else
3397         New->dropAttr<OverloadableAttr>();
3398     }
3399   }
3400 
3401   // If a function is first declared with a calling convention, but is later
3402   // declared or defined without one, all following decls assume the calling
3403   // convention of the first.
3404   //
3405   // It's OK if a function is first declared without a calling convention,
3406   // but is later declared or defined with the default calling convention.
3407   //
3408   // To test if either decl has an explicit calling convention, we look for
3409   // AttributedType sugar nodes on the type as written.  If they are missing or
3410   // were canonicalized away, we assume the calling convention was implicit.
3411   //
3412   // Note also that we DO NOT return at this point, because we still have
3413   // other tests to run.
3414   QualType OldQType = Context.getCanonicalType(Old->getType());
3415   QualType NewQType = Context.getCanonicalType(New->getType());
3416   const FunctionType *OldType = cast<FunctionType>(OldQType);
3417   const FunctionType *NewType = cast<FunctionType>(NewQType);
3418   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3419   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3420   bool RequiresAdjustment = false;
3421 
3422   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3423     FunctionDecl *First = Old->getFirstDecl();
3424     const FunctionType *FT =
3425         First->getType().getCanonicalType()->castAs<FunctionType>();
3426     FunctionType::ExtInfo FI = FT->getExtInfo();
3427     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3428     if (!NewCCExplicit) {
3429       // Inherit the CC from the previous declaration if it was specified
3430       // there but not here.
3431       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3432       RequiresAdjustment = true;
3433     } else if (Old->getBuiltinID()) {
3434       // Builtin attribute isn't propagated to the new one yet at this point,
3435       // so we check if the old one is a builtin.
3436 
3437       // Calling Conventions on a Builtin aren't really useful and setting a
3438       // default calling convention and cdecl'ing some builtin redeclarations is
3439       // common, so warn and ignore the calling convention on the redeclaration.
3440       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3441           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3442           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3443       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3444       RequiresAdjustment = true;
3445     } else {
3446       // Calling conventions aren't compatible, so complain.
3447       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3448       Diag(New->getLocation(), diag::err_cconv_change)
3449         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3450         << !FirstCCExplicit
3451         << (!FirstCCExplicit ? "" :
3452             FunctionType::getNameForCallConv(FI.getCC()));
3453 
3454       // Put the note on the first decl, since it is the one that matters.
3455       Diag(First->getLocation(), diag::note_previous_declaration);
3456       return true;
3457     }
3458   }
3459 
3460   // FIXME: diagnose the other way around?
3461   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3462     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3463     RequiresAdjustment = true;
3464   }
3465 
3466   // Merge regparm attribute.
3467   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3468       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3469     if (NewTypeInfo.getHasRegParm()) {
3470       Diag(New->getLocation(), diag::err_regparm_mismatch)
3471         << NewType->getRegParmType()
3472         << OldType->getRegParmType();
3473       Diag(OldLocation, diag::note_previous_declaration);
3474       return true;
3475     }
3476 
3477     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3478     RequiresAdjustment = true;
3479   }
3480 
3481   // Merge ns_returns_retained attribute.
3482   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3483     if (NewTypeInfo.getProducesResult()) {
3484       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3485           << "'ns_returns_retained'";
3486       Diag(OldLocation, diag::note_previous_declaration);
3487       return true;
3488     }
3489 
3490     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3491     RequiresAdjustment = true;
3492   }
3493 
3494   if (OldTypeInfo.getNoCallerSavedRegs() !=
3495       NewTypeInfo.getNoCallerSavedRegs()) {
3496     if (NewTypeInfo.getNoCallerSavedRegs()) {
3497       AnyX86NoCallerSavedRegistersAttr *Attr =
3498         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3499       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3500       Diag(OldLocation, diag::note_previous_declaration);
3501       return true;
3502     }
3503 
3504     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3505     RequiresAdjustment = true;
3506   }
3507 
3508   if (RequiresAdjustment) {
3509     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3510     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3511     New->setType(QualType(AdjustedType, 0));
3512     NewQType = Context.getCanonicalType(New->getType());
3513   }
3514 
3515   // If this redeclaration makes the function inline, we may need to add it to
3516   // UndefinedButUsed.
3517   if (!Old->isInlined() && New->isInlined() &&
3518       !New->hasAttr<GNUInlineAttr>() &&
3519       !getLangOpts().GNUInline &&
3520       Old->isUsed(false) &&
3521       !Old->isDefined() && !New->isThisDeclarationADefinition())
3522     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3523                                            SourceLocation()));
3524 
3525   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3526   // about it.
3527   if (New->hasAttr<GNUInlineAttr>() &&
3528       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3529     UndefinedButUsed.erase(Old->getCanonicalDecl());
3530   }
3531 
3532   // If pass_object_size params don't match up perfectly, this isn't a valid
3533   // redeclaration.
3534   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3535       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3536     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3537         << New->getDeclName();
3538     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3539     return true;
3540   }
3541 
3542   if (getLangOpts().CPlusPlus) {
3543     // C++1z [over.load]p2
3544     //   Certain function declarations cannot be overloaded:
3545     //     -- Function declarations that differ only in the return type,
3546     //        the exception specification, or both cannot be overloaded.
3547 
3548     // Check the exception specifications match. This may recompute the type of
3549     // both Old and New if it resolved exception specifications, so grab the
3550     // types again after this. Because this updates the type, we do this before
3551     // any of the other checks below, which may update the "de facto" NewQType
3552     // but do not necessarily update the type of New.
3553     if (CheckEquivalentExceptionSpec(Old, New))
3554       return true;
3555     OldQType = Context.getCanonicalType(Old->getType());
3556     NewQType = Context.getCanonicalType(New->getType());
3557 
3558     // Go back to the type source info to compare the declared return types,
3559     // per C++1y [dcl.type.auto]p13:
3560     //   Redeclarations or specializations of a function or function template
3561     //   with a declared return type that uses a placeholder type shall also
3562     //   use that placeholder, not a deduced type.
3563     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3564     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3565     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3566         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3567                                        OldDeclaredReturnType)) {
3568       QualType ResQT;
3569       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3570           OldDeclaredReturnType->isObjCObjectPointerType())
3571         // FIXME: This does the wrong thing for a deduced return type.
3572         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3573       if (ResQT.isNull()) {
3574         if (New->isCXXClassMember() && New->isOutOfLine())
3575           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3576               << New << New->getReturnTypeSourceRange();
3577         else
3578           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3579               << New->getReturnTypeSourceRange();
3580         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3581                                     << Old->getReturnTypeSourceRange();
3582         return true;
3583       }
3584       else
3585         NewQType = ResQT;
3586     }
3587 
3588     QualType OldReturnType = OldType->getReturnType();
3589     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3590     if (OldReturnType != NewReturnType) {
3591       // If this function has a deduced return type and has already been
3592       // defined, copy the deduced value from the old declaration.
3593       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3594       if (OldAT && OldAT->isDeduced()) {
3595         New->setType(
3596             SubstAutoType(New->getType(),
3597                           OldAT->isDependentType() ? Context.DependentTy
3598                                                    : OldAT->getDeducedType()));
3599         NewQType = Context.getCanonicalType(
3600             SubstAutoType(NewQType,
3601                           OldAT->isDependentType() ? Context.DependentTy
3602                                                    : OldAT->getDeducedType()));
3603       }
3604     }
3605 
3606     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3607     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3608     if (OldMethod && NewMethod) {
3609       // Preserve triviality.
3610       NewMethod->setTrivial(OldMethod->isTrivial());
3611 
3612       // MSVC allows explicit template specialization at class scope:
3613       // 2 CXXMethodDecls referring to the same function will be injected.
3614       // We don't want a redeclaration error.
3615       bool IsClassScopeExplicitSpecialization =
3616                               OldMethod->isFunctionTemplateSpecialization() &&
3617                               NewMethod->isFunctionTemplateSpecialization();
3618       bool isFriend = NewMethod->getFriendObjectKind();
3619 
3620       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3621           !IsClassScopeExplicitSpecialization) {
3622         //    -- Member function declarations with the same name and the
3623         //       same parameter types cannot be overloaded if any of them
3624         //       is a static member function declaration.
3625         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3626           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3627           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3628           return true;
3629         }
3630 
3631         // C++ [class.mem]p1:
3632         //   [...] A member shall not be declared twice in the
3633         //   member-specification, except that a nested class or member
3634         //   class template can be declared and then later defined.
3635         if (!inTemplateInstantiation()) {
3636           unsigned NewDiag;
3637           if (isa<CXXConstructorDecl>(OldMethod))
3638             NewDiag = diag::err_constructor_redeclared;
3639           else if (isa<CXXDestructorDecl>(NewMethod))
3640             NewDiag = diag::err_destructor_redeclared;
3641           else if (isa<CXXConversionDecl>(NewMethod))
3642             NewDiag = diag::err_conv_function_redeclared;
3643           else
3644             NewDiag = diag::err_member_redeclared;
3645 
3646           Diag(New->getLocation(), NewDiag);
3647         } else {
3648           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3649             << New << New->getType();
3650         }
3651         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3652         return true;
3653 
3654       // Complain if this is an explicit declaration of a special
3655       // member that was initially declared implicitly.
3656       //
3657       // As an exception, it's okay to befriend such methods in order
3658       // to permit the implicit constructor/destructor/operator calls.
3659       } else if (OldMethod->isImplicit()) {
3660         if (isFriend) {
3661           NewMethod->setImplicit();
3662         } else {
3663           Diag(NewMethod->getLocation(),
3664                diag::err_definition_of_implicitly_declared_member)
3665             << New << getSpecialMember(OldMethod);
3666           return true;
3667         }
3668       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3669         Diag(NewMethod->getLocation(),
3670              diag::err_definition_of_explicitly_defaulted_member)
3671           << getSpecialMember(OldMethod);
3672         return true;
3673       }
3674     }
3675 
3676     // C++11 [dcl.attr.noreturn]p1:
3677     //   The first declaration of a function shall specify the noreturn
3678     //   attribute if any declaration of that function specifies the noreturn
3679     //   attribute.
3680     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3681     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3682       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3683       Diag(Old->getFirstDecl()->getLocation(),
3684            diag::note_noreturn_missing_first_decl);
3685     }
3686 
3687     // C++11 [dcl.attr.depend]p2:
3688     //   The first declaration of a function shall specify the
3689     //   carries_dependency attribute for its declarator-id if any declaration
3690     //   of the function specifies the carries_dependency attribute.
3691     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3692     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3693       Diag(CDA->getLocation(),
3694            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3695       Diag(Old->getFirstDecl()->getLocation(),
3696            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3697     }
3698 
3699     // (C++98 8.3.5p3):
3700     //   All declarations for a function shall agree exactly in both the
3701     //   return type and the parameter-type-list.
3702     // We also want to respect all the extended bits except noreturn.
3703 
3704     // noreturn should now match unless the old type info didn't have it.
3705     QualType OldQTypeForComparison = OldQType;
3706     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3707       auto *OldType = OldQType->castAs<FunctionProtoType>();
3708       const FunctionType *OldTypeForComparison
3709         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3710       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3711       assert(OldQTypeForComparison.isCanonical());
3712     }
3713 
3714     if (haveIncompatibleLanguageLinkages(Old, New)) {
3715       // As a special case, retain the language linkage from previous
3716       // declarations of a friend function as an extension.
3717       //
3718       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3719       // and is useful because there's otherwise no way to specify language
3720       // linkage within class scope.
3721       //
3722       // Check cautiously as the friend object kind isn't yet complete.
3723       if (New->getFriendObjectKind() != Decl::FOK_None) {
3724         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3725         Diag(OldLocation, PrevDiag);
3726       } else {
3727         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3728         Diag(OldLocation, PrevDiag);
3729         return true;
3730       }
3731     }
3732 
3733     // If the function types are compatible, merge the declarations. Ignore the
3734     // exception specifier because it was already checked above in
3735     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3736     // about incompatible types under -fms-compatibility.
3737     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3738                                                          NewQType))
3739       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3740 
3741     // If the types are imprecise (due to dependent constructs in friends or
3742     // local extern declarations), it's OK if they differ. We'll check again
3743     // during instantiation.
3744     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3745       return false;
3746 
3747     // Fall through for conflicting redeclarations and redefinitions.
3748   }
3749 
3750   // C: Function types need to be compatible, not identical. This handles
3751   // duplicate function decls like "void f(int); void f(enum X);" properly.
3752   if (!getLangOpts().CPlusPlus &&
3753       Context.typesAreCompatible(OldQType, NewQType)) {
3754     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3755     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3756     const FunctionProtoType *OldProto = nullptr;
3757     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3758         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3759       // The old declaration provided a function prototype, but the
3760       // new declaration does not. Merge in the prototype.
3761       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3762       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3763       NewQType =
3764           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3765                                   OldProto->getExtProtoInfo());
3766       New->setType(NewQType);
3767       New->setHasInheritedPrototype();
3768 
3769       // Synthesize parameters with the same types.
3770       SmallVector<ParmVarDecl*, 16> Params;
3771       for (const auto &ParamType : OldProto->param_types()) {
3772         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3773                                                  SourceLocation(), nullptr,
3774                                                  ParamType, /*TInfo=*/nullptr,
3775                                                  SC_None, nullptr);
3776         Param->setScopeInfo(0, Params.size());
3777         Param->setImplicit();
3778         Params.push_back(Param);
3779       }
3780 
3781       New->setParams(Params);
3782     }
3783 
3784     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3785   }
3786 
3787   // Check if the function types are compatible when pointer size address
3788   // spaces are ignored.
3789   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3790     return false;
3791 
3792   // GNU C permits a K&R definition to follow a prototype declaration
3793   // if the declared types of the parameters in the K&R definition
3794   // match the types in the prototype declaration, even when the
3795   // promoted types of the parameters from the K&R definition differ
3796   // from the types in the prototype. GCC then keeps the types from
3797   // the prototype.
3798   //
3799   // If a variadic prototype is followed by a non-variadic K&R definition,
3800   // the K&R definition becomes variadic.  This is sort of an edge case, but
3801   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3802   // C99 6.9.1p8.
3803   if (!getLangOpts().CPlusPlus &&
3804       Old->hasPrototype() && !New->hasPrototype() &&
3805       New->getType()->getAs<FunctionProtoType>() &&
3806       Old->getNumParams() == New->getNumParams()) {
3807     SmallVector<QualType, 16> ArgTypes;
3808     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3809     const FunctionProtoType *OldProto
3810       = Old->getType()->getAs<FunctionProtoType>();
3811     const FunctionProtoType *NewProto
3812       = New->getType()->getAs<FunctionProtoType>();
3813 
3814     // Determine whether this is the GNU C extension.
3815     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3816                                                NewProto->getReturnType());
3817     bool LooseCompatible = !MergedReturn.isNull();
3818     for (unsigned Idx = 0, End = Old->getNumParams();
3819          LooseCompatible && Idx != End; ++Idx) {
3820       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3821       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3822       if (Context.typesAreCompatible(OldParm->getType(),
3823                                      NewProto->getParamType(Idx))) {
3824         ArgTypes.push_back(NewParm->getType());
3825       } else if (Context.typesAreCompatible(OldParm->getType(),
3826                                             NewParm->getType(),
3827                                             /*CompareUnqualified=*/true)) {
3828         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3829                                            NewProto->getParamType(Idx) };
3830         Warnings.push_back(Warn);
3831         ArgTypes.push_back(NewParm->getType());
3832       } else
3833         LooseCompatible = false;
3834     }
3835 
3836     if (LooseCompatible) {
3837       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3838         Diag(Warnings[Warn].NewParm->getLocation(),
3839              diag::ext_param_promoted_not_compatible_with_prototype)
3840           << Warnings[Warn].PromotedType
3841           << Warnings[Warn].OldParm->getType();
3842         if (Warnings[Warn].OldParm->getLocation().isValid())
3843           Diag(Warnings[Warn].OldParm->getLocation(),
3844                diag::note_previous_declaration);
3845       }
3846 
3847       if (MergeTypeWithOld)
3848         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3849                                              OldProto->getExtProtoInfo()));
3850       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3851     }
3852 
3853     // Fall through to diagnose conflicting types.
3854   }
3855 
3856   // A function that has already been declared has been redeclared or
3857   // defined with a different type; show an appropriate diagnostic.
3858 
3859   // If the previous declaration was an implicitly-generated builtin
3860   // declaration, then at the very least we should use a specialized note.
3861   unsigned BuiltinID;
3862   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3863     // If it's actually a library-defined builtin function like 'malloc'
3864     // or 'printf', just warn about the incompatible redeclaration.
3865     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3866       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3867       Diag(OldLocation, diag::note_previous_builtin_declaration)
3868         << Old << Old->getType();
3869       return false;
3870     }
3871 
3872     PrevDiag = diag::note_previous_builtin_declaration;
3873   }
3874 
3875   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3876   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3877   return true;
3878 }
3879 
3880 /// Completes the merge of two function declarations that are
3881 /// known to be compatible.
3882 ///
3883 /// This routine handles the merging of attributes and other
3884 /// properties of function declarations from the old declaration to
3885 /// the new declaration, once we know that New is in fact a
3886 /// redeclaration of Old.
3887 ///
3888 /// \returns false
3889 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3890                                         Scope *S, bool MergeTypeWithOld) {
3891   // Merge the attributes
3892   mergeDeclAttributes(New, Old);
3893 
3894   // Merge "pure" flag.
3895   if (Old->isPure())
3896     New->setPure();
3897 
3898   // Merge "used" flag.
3899   if (Old->getMostRecentDecl()->isUsed(false))
3900     New->setIsUsed();
3901 
3902   // Merge attributes from the parameters.  These can mismatch with K&R
3903   // declarations.
3904   if (New->getNumParams() == Old->getNumParams())
3905       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3906         ParmVarDecl *NewParam = New->getParamDecl(i);
3907         ParmVarDecl *OldParam = Old->getParamDecl(i);
3908         mergeParamDeclAttributes(NewParam, OldParam, *this);
3909         mergeParamDeclTypes(NewParam, OldParam, *this);
3910       }
3911 
3912   if (getLangOpts().CPlusPlus)
3913     return MergeCXXFunctionDecl(New, Old, S);
3914 
3915   // Merge the function types so the we get the composite types for the return
3916   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3917   // was visible.
3918   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3919   if (!Merged.isNull() && MergeTypeWithOld)
3920     New->setType(Merged);
3921 
3922   return false;
3923 }
3924 
3925 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3926                                 ObjCMethodDecl *oldMethod) {
3927   // Merge the attributes, including deprecated/unavailable
3928   AvailabilityMergeKind MergeKind =
3929       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3930           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3931                                      : AMK_ProtocolImplementation)
3932           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3933                                                            : AMK_Override;
3934 
3935   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3936 
3937   // Merge attributes from the parameters.
3938   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3939                                        oe = oldMethod->param_end();
3940   for (ObjCMethodDecl::param_iterator
3941          ni = newMethod->param_begin(), ne = newMethod->param_end();
3942        ni != ne && oi != oe; ++ni, ++oi)
3943     mergeParamDeclAttributes(*ni, *oi, *this);
3944 
3945   CheckObjCMethodOverride(newMethod, oldMethod);
3946 }
3947 
3948 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3949   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3950 
3951   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3952          ? diag::err_redefinition_different_type
3953          : diag::err_redeclaration_different_type)
3954     << New->getDeclName() << New->getType() << Old->getType();
3955 
3956   diag::kind PrevDiag;
3957   SourceLocation OldLocation;
3958   std::tie(PrevDiag, OldLocation)
3959     = getNoteDiagForInvalidRedeclaration(Old, New);
3960   S.Diag(OldLocation, PrevDiag);
3961   New->setInvalidDecl();
3962 }
3963 
3964 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3965 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3966 /// emitting diagnostics as appropriate.
3967 ///
3968 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3969 /// to here in AddInitializerToDecl. We can't check them before the initializer
3970 /// is attached.
3971 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3972                              bool MergeTypeWithOld) {
3973   if (New->isInvalidDecl() || Old->isInvalidDecl())
3974     return;
3975 
3976   QualType MergedT;
3977   if (getLangOpts().CPlusPlus) {
3978     if (New->getType()->isUndeducedType()) {
3979       // We don't know what the new type is until the initializer is attached.
3980       return;
3981     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3982       // These could still be something that needs exception specs checked.
3983       return MergeVarDeclExceptionSpecs(New, Old);
3984     }
3985     // C++ [basic.link]p10:
3986     //   [...] the types specified by all declarations referring to a given
3987     //   object or function shall be identical, except that declarations for an
3988     //   array object can specify array types that differ by the presence or
3989     //   absence of a major array bound (8.3.4).
3990     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3991       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3992       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3993 
3994       // We are merging a variable declaration New into Old. If it has an array
3995       // bound, and that bound differs from Old's bound, we should diagnose the
3996       // mismatch.
3997       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3998         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3999              PrevVD = PrevVD->getPreviousDecl()) {
4000           QualType PrevVDTy = PrevVD->getType();
4001           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4002             continue;
4003 
4004           if (!Context.hasSameType(New->getType(), PrevVDTy))
4005             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4006         }
4007       }
4008 
4009       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4010         if (Context.hasSameType(OldArray->getElementType(),
4011                                 NewArray->getElementType()))
4012           MergedT = New->getType();
4013       }
4014       // FIXME: Check visibility. New is hidden but has a complete type. If New
4015       // has no array bound, it should not inherit one from Old, if Old is not
4016       // visible.
4017       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4018         if (Context.hasSameType(OldArray->getElementType(),
4019                                 NewArray->getElementType()))
4020           MergedT = Old->getType();
4021       }
4022     }
4023     else if (New->getType()->isObjCObjectPointerType() &&
4024                Old->getType()->isObjCObjectPointerType()) {
4025       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4026                                               Old->getType());
4027     }
4028   } else {
4029     // C 6.2.7p2:
4030     //   All declarations that refer to the same object or function shall have
4031     //   compatible type.
4032     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4033   }
4034   if (MergedT.isNull()) {
4035     // It's OK if we couldn't merge types if either type is dependent, for a
4036     // block-scope variable. In other cases (static data members of class
4037     // templates, variable templates, ...), we require the types to be
4038     // equivalent.
4039     // FIXME: The C++ standard doesn't say anything about this.
4040     if ((New->getType()->isDependentType() ||
4041          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4042       // If the old type was dependent, we can't merge with it, so the new type
4043       // becomes dependent for now. We'll reproduce the original type when we
4044       // instantiate the TypeSourceInfo for the variable.
4045       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4046         New->setType(Context.DependentTy);
4047       return;
4048     }
4049     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4050   }
4051 
4052   // Don't actually update the type on the new declaration if the old
4053   // declaration was an extern declaration in a different scope.
4054   if (MergeTypeWithOld)
4055     New->setType(MergedT);
4056 }
4057 
4058 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4059                                   LookupResult &Previous) {
4060   // C11 6.2.7p4:
4061   //   For an identifier with internal or external linkage declared
4062   //   in a scope in which a prior declaration of that identifier is
4063   //   visible, if the prior declaration specifies internal or
4064   //   external linkage, the type of the identifier at the later
4065   //   declaration becomes the composite type.
4066   //
4067   // If the variable isn't visible, we do not merge with its type.
4068   if (Previous.isShadowed())
4069     return false;
4070 
4071   if (S.getLangOpts().CPlusPlus) {
4072     // C++11 [dcl.array]p3:
4073     //   If there is a preceding declaration of the entity in the same
4074     //   scope in which the bound was specified, an omitted array bound
4075     //   is taken to be the same as in that earlier declaration.
4076     return NewVD->isPreviousDeclInSameBlockScope() ||
4077            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4078             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4079   } else {
4080     // If the old declaration was function-local, don't merge with its
4081     // type unless we're in the same function.
4082     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4083            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4084   }
4085 }
4086 
4087 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4088 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4089 /// situation, merging decls or emitting diagnostics as appropriate.
4090 ///
4091 /// Tentative definition rules (C99 6.9.2p2) are checked by
4092 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4093 /// definitions here, since the initializer hasn't been attached.
4094 ///
4095 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4096   // If the new decl is already invalid, don't do any other checking.
4097   if (New->isInvalidDecl())
4098     return;
4099 
4100   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4101     return;
4102 
4103   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4104 
4105   // Verify the old decl was also a variable or variable template.
4106   VarDecl *Old = nullptr;
4107   VarTemplateDecl *OldTemplate = nullptr;
4108   if (Previous.isSingleResult()) {
4109     if (NewTemplate) {
4110       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4111       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4112 
4113       if (auto *Shadow =
4114               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4115         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4116           return New->setInvalidDecl();
4117     } else {
4118       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4119 
4120       if (auto *Shadow =
4121               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4122         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4123           return New->setInvalidDecl();
4124     }
4125   }
4126   if (!Old) {
4127     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4128         << New->getDeclName();
4129     notePreviousDefinition(Previous.getRepresentativeDecl(),
4130                            New->getLocation());
4131     return New->setInvalidDecl();
4132   }
4133 
4134   // If the old declaration was found in an inline namespace and the new
4135   // declaration was qualified, update the DeclContext to match.
4136   adjustDeclContextForDeclaratorDecl(New, Old);
4137 
4138   // Ensure the template parameters are compatible.
4139   if (NewTemplate &&
4140       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4141                                       OldTemplate->getTemplateParameters(),
4142                                       /*Complain=*/true, TPL_TemplateMatch))
4143     return New->setInvalidDecl();
4144 
4145   // C++ [class.mem]p1:
4146   //   A member shall not be declared twice in the member-specification [...]
4147   //
4148   // Here, we need only consider static data members.
4149   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4150     Diag(New->getLocation(), diag::err_duplicate_member)
4151       << New->getIdentifier();
4152     Diag(Old->getLocation(), diag::note_previous_declaration);
4153     New->setInvalidDecl();
4154   }
4155 
4156   mergeDeclAttributes(New, Old);
4157   // Warn if an already-declared variable is made a weak_import in a subsequent
4158   // declaration
4159   if (New->hasAttr<WeakImportAttr>() &&
4160       Old->getStorageClass() == SC_None &&
4161       !Old->hasAttr<WeakImportAttr>()) {
4162     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4163     notePreviousDefinition(Old, New->getLocation());
4164     // Remove weak_import attribute on new declaration.
4165     New->dropAttr<WeakImportAttr>();
4166   }
4167 
4168   if (New->hasAttr<InternalLinkageAttr>() &&
4169       !Old->hasAttr<InternalLinkageAttr>()) {
4170     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4171         << New->getDeclName();
4172     notePreviousDefinition(Old, New->getLocation());
4173     New->dropAttr<InternalLinkageAttr>();
4174   }
4175 
4176   // Merge the types.
4177   VarDecl *MostRecent = Old->getMostRecentDecl();
4178   if (MostRecent != Old) {
4179     MergeVarDeclTypes(New, MostRecent,
4180                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4181     if (New->isInvalidDecl())
4182       return;
4183   }
4184 
4185   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4186   if (New->isInvalidDecl())
4187     return;
4188 
4189   diag::kind PrevDiag;
4190   SourceLocation OldLocation;
4191   std::tie(PrevDiag, OldLocation) =
4192       getNoteDiagForInvalidRedeclaration(Old, New);
4193 
4194   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4195   if (New->getStorageClass() == SC_Static &&
4196       !New->isStaticDataMember() &&
4197       Old->hasExternalFormalLinkage()) {
4198     if (getLangOpts().MicrosoftExt) {
4199       Diag(New->getLocation(), diag::ext_static_non_static)
4200           << New->getDeclName();
4201       Diag(OldLocation, PrevDiag);
4202     } else {
4203       Diag(New->getLocation(), diag::err_static_non_static)
4204           << New->getDeclName();
4205       Diag(OldLocation, PrevDiag);
4206       return New->setInvalidDecl();
4207     }
4208   }
4209   // C99 6.2.2p4:
4210   //   For an identifier declared with the storage-class specifier
4211   //   extern in a scope in which a prior declaration of that
4212   //   identifier is visible,23) if the prior declaration specifies
4213   //   internal or external linkage, the linkage of the identifier at
4214   //   the later declaration is the same as the linkage specified at
4215   //   the prior declaration. If no prior declaration is visible, or
4216   //   if the prior declaration specifies no linkage, then the
4217   //   identifier has external linkage.
4218   if (New->hasExternalStorage() && Old->hasLinkage())
4219     /* Okay */;
4220   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4221            !New->isStaticDataMember() &&
4222            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4223     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4224     Diag(OldLocation, PrevDiag);
4225     return New->setInvalidDecl();
4226   }
4227 
4228   // Check if extern is followed by non-extern and vice-versa.
4229   if (New->hasExternalStorage() &&
4230       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4231     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4232     Diag(OldLocation, PrevDiag);
4233     return New->setInvalidDecl();
4234   }
4235   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4236       !New->hasExternalStorage()) {
4237     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4238     Diag(OldLocation, PrevDiag);
4239     return New->setInvalidDecl();
4240   }
4241 
4242   if (CheckRedeclarationModuleOwnership(New, Old))
4243     return;
4244 
4245   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4246 
4247   // FIXME: The test for external storage here seems wrong? We still
4248   // need to check for mismatches.
4249   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4250       // Don't complain about out-of-line definitions of static members.
4251       !(Old->getLexicalDeclContext()->isRecord() &&
4252         !New->getLexicalDeclContext()->isRecord())) {
4253     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4254     Diag(OldLocation, PrevDiag);
4255     return New->setInvalidDecl();
4256   }
4257 
4258   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4259     if (VarDecl *Def = Old->getDefinition()) {
4260       // C++1z [dcl.fcn.spec]p4:
4261       //   If the definition of a variable appears in a translation unit before
4262       //   its first declaration as inline, the program is ill-formed.
4263       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4264       Diag(Def->getLocation(), diag::note_previous_definition);
4265     }
4266   }
4267 
4268   // If this redeclaration makes the variable inline, we may need to add it to
4269   // UndefinedButUsed.
4270   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4271       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4272     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4273                                            SourceLocation()));
4274 
4275   if (New->getTLSKind() != Old->getTLSKind()) {
4276     if (!Old->getTLSKind()) {
4277       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4278       Diag(OldLocation, PrevDiag);
4279     } else if (!New->getTLSKind()) {
4280       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4281       Diag(OldLocation, PrevDiag);
4282     } else {
4283       // Do not allow redeclaration to change the variable between requiring
4284       // static and dynamic initialization.
4285       // FIXME: GCC allows this, but uses the TLS keyword on the first
4286       // declaration to determine the kind. Do we need to be compatible here?
4287       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4288         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4289       Diag(OldLocation, PrevDiag);
4290     }
4291   }
4292 
4293   // C++ doesn't have tentative definitions, so go right ahead and check here.
4294   if (getLangOpts().CPlusPlus &&
4295       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4296     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4297         Old->getCanonicalDecl()->isConstexpr()) {
4298       // This definition won't be a definition any more once it's been merged.
4299       Diag(New->getLocation(),
4300            diag::warn_deprecated_redundant_constexpr_static_def);
4301     } else if (VarDecl *Def = Old->getDefinition()) {
4302       if (checkVarDeclRedefinition(Def, New))
4303         return;
4304     }
4305   }
4306 
4307   if (haveIncompatibleLanguageLinkages(Old, New)) {
4308     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4309     Diag(OldLocation, PrevDiag);
4310     New->setInvalidDecl();
4311     return;
4312   }
4313 
4314   // Merge "used" flag.
4315   if (Old->getMostRecentDecl()->isUsed(false))
4316     New->setIsUsed();
4317 
4318   // Keep a chain of previous declarations.
4319   New->setPreviousDecl(Old);
4320   if (NewTemplate)
4321     NewTemplate->setPreviousDecl(OldTemplate);
4322 
4323   // Inherit access appropriately.
4324   New->setAccess(Old->getAccess());
4325   if (NewTemplate)
4326     NewTemplate->setAccess(New->getAccess());
4327 
4328   if (Old->isInline())
4329     New->setImplicitlyInline();
4330 }
4331 
4332 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4333   SourceManager &SrcMgr = getSourceManager();
4334   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4335   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4336   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4337   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4338   auto &HSI = PP.getHeaderSearchInfo();
4339   StringRef HdrFilename =
4340       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4341 
4342   auto noteFromModuleOrInclude = [&](Module *Mod,
4343                                      SourceLocation IncLoc) -> bool {
4344     // Redefinition errors with modules are common with non modular mapped
4345     // headers, example: a non-modular header H in module A that also gets
4346     // included directly in a TU. Pointing twice to the same header/definition
4347     // is confusing, try to get better diagnostics when modules is on.
4348     if (IncLoc.isValid()) {
4349       if (Mod) {
4350         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4351             << HdrFilename.str() << Mod->getFullModuleName();
4352         if (!Mod->DefinitionLoc.isInvalid())
4353           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4354               << Mod->getFullModuleName();
4355       } else {
4356         Diag(IncLoc, diag::note_redefinition_include_same_file)
4357             << HdrFilename.str();
4358       }
4359       return true;
4360     }
4361 
4362     return false;
4363   };
4364 
4365   // Is it the same file and same offset? Provide more information on why
4366   // this leads to a redefinition error.
4367   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4368     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4369     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4370     bool EmittedDiag =
4371         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4372     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4373 
4374     // If the header has no guards, emit a note suggesting one.
4375     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4376       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4377 
4378     if (EmittedDiag)
4379       return;
4380   }
4381 
4382   // Redefinition coming from different files or couldn't do better above.
4383   if (Old->getLocation().isValid())
4384     Diag(Old->getLocation(), diag::note_previous_definition);
4385 }
4386 
4387 /// We've just determined that \p Old and \p New both appear to be definitions
4388 /// of the same variable. Either diagnose or fix the problem.
4389 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4390   if (!hasVisibleDefinition(Old) &&
4391       (New->getFormalLinkage() == InternalLinkage ||
4392        New->isInline() ||
4393        New->getDescribedVarTemplate() ||
4394        New->getNumTemplateParameterLists() ||
4395        New->getDeclContext()->isDependentContext())) {
4396     // The previous definition is hidden, and multiple definitions are
4397     // permitted (in separate TUs). Demote this to a declaration.
4398     New->demoteThisDefinitionToDeclaration();
4399 
4400     // Make the canonical definition visible.
4401     if (auto *OldTD = Old->getDescribedVarTemplate())
4402       makeMergedDefinitionVisible(OldTD);
4403     makeMergedDefinitionVisible(Old);
4404     return false;
4405   } else {
4406     Diag(New->getLocation(), diag::err_redefinition) << New;
4407     notePreviousDefinition(Old, New->getLocation());
4408     New->setInvalidDecl();
4409     return true;
4410   }
4411 }
4412 
4413 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4414 /// no declarator (e.g. "struct foo;") is parsed.
4415 Decl *
4416 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4417                                  RecordDecl *&AnonRecord) {
4418   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4419                                     AnonRecord);
4420 }
4421 
4422 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4423 // disambiguate entities defined in different scopes.
4424 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4425 // compatibility.
4426 // We will pick our mangling number depending on which version of MSVC is being
4427 // targeted.
4428 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4429   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4430              ? S->getMSCurManglingNumber()
4431              : S->getMSLastManglingNumber();
4432 }
4433 
4434 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4435   if (!Context.getLangOpts().CPlusPlus)
4436     return;
4437 
4438   if (isa<CXXRecordDecl>(Tag->getParent())) {
4439     // If this tag is the direct child of a class, number it if
4440     // it is anonymous.
4441     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4442       return;
4443     MangleNumberingContext &MCtx =
4444         Context.getManglingNumberContext(Tag->getParent());
4445     Context.setManglingNumber(
4446         Tag, MCtx.getManglingNumber(
4447                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4448     return;
4449   }
4450 
4451   // If this tag isn't a direct child of a class, number it if it is local.
4452   MangleNumberingContext *MCtx;
4453   Decl *ManglingContextDecl;
4454   std::tie(MCtx, ManglingContextDecl) =
4455       getCurrentMangleNumberContext(Tag->getDeclContext());
4456   if (MCtx) {
4457     Context.setManglingNumber(
4458         Tag, MCtx->getManglingNumber(
4459                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4460   }
4461 }
4462 
4463 namespace {
4464 struct NonCLikeKind {
4465   enum {
4466     None,
4467     BaseClass,
4468     DefaultMemberInit,
4469     Lambda,
4470     Friend,
4471     OtherMember,
4472     Invalid,
4473   } Kind = None;
4474   SourceRange Range;
4475 
4476   explicit operator bool() { return Kind != None; }
4477 };
4478 }
4479 
4480 /// Determine whether a class is C-like, according to the rules of C++
4481 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4482 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4483   if (RD->isInvalidDecl())
4484     return {NonCLikeKind::Invalid, {}};
4485 
4486   // C++ [dcl.typedef]p9: [P1766R1]
4487   //   An unnamed class with a typedef name for linkage purposes shall not
4488   //
4489   //    -- have any base classes
4490   if (RD->getNumBases())
4491     return {NonCLikeKind::BaseClass,
4492             SourceRange(RD->bases_begin()->getBeginLoc(),
4493                         RD->bases_end()[-1].getEndLoc())};
4494   bool Invalid = false;
4495   for (Decl *D : RD->decls()) {
4496     // Don't complain about things we already diagnosed.
4497     if (D->isInvalidDecl()) {
4498       Invalid = true;
4499       continue;
4500     }
4501 
4502     //  -- have any [...] default member initializers
4503     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4504       if (FD->hasInClassInitializer()) {
4505         auto *Init = FD->getInClassInitializer();
4506         return {NonCLikeKind::DefaultMemberInit,
4507                 Init ? Init->getSourceRange() : D->getSourceRange()};
4508       }
4509       continue;
4510     }
4511 
4512     // FIXME: We don't allow friend declarations. This violates the wording of
4513     // P1766, but not the intent.
4514     if (isa<FriendDecl>(D))
4515       return {NonCLikeKind::Friend, D->getSourceRange()};
4516 
4517     //  -- declare any members other than non-static data members, member
4518     //     enumerations, or member classes,
4519     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4520         isa<EnumDecl>(D))
4521       continue;
4522     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4523     if (!MemberRD) {
4524       if (D->isImplicit())
4525         continue;
4526       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4527     }
4528 
4529     //  -- contain a lambda-expression,
4530     if (MemberRD->isLambda())
4531       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4532 
4533     //  and all member classes shall also satisfy these requirements
4534     //  (recursively).
4535     if (MemberRD->isThisDeclarationADefinition()) {
4536       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4537         return Kind;
4538     }
4539   }
4540 
4541   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4542 }
4543 
4544 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4545                                         TypedefNameDecl *NewTD) {
4546   if (TagFromDeclSpec->isInvalidDecl())
4547     return;
4548 
4549   // Do nothing if the tag already has a name for linkage purposes.
4550   if (TagFromDeclSpec->hasNameForLinkage())
4551     return;
4552 
4553   // A well-formed anonymous tag must always be a TUK_Definition.
4554   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4555 
4556   // The type must match the tag exactly;  no qualifiers allowed.
4557   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4558                            Context.getTagDeclType(TagFromDeclSpec))) {
4559     if (getLangOpts().CPlusPlus)
4560       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4561     return;
4562   }
4563 
4564   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4565   //   An unnamed class with a typedef name for linkage purposes shall [be
4566   //   C-like].
4567   //
4568   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4569   // shouldn't happen, but there are constructs that the language rule doesn't
4570   // disallow for which we can't reasonably avoid computing linkage early.
4571   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4572   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4573                              : NonCLikeKind();
4574   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4575   if (NonCLike || ChangesLinkage) {
4576     if (NonCLike.Kind == NonCLikeKind::Invalid)
4577       return;
4578 
4579     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4580     if (ChangesLinkage) {
4581       // If the linkage changes, we can't accept this as an extension.
4582       if (NonCLike.Kind == NonCLikeKind::None)
4583         DiagID = diag::err_typedef_changes_linkage;
4584       else
4585         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4586     }
4587 
4588     SourceLocation FixitLoc =
4589         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4590     llvm::SmallString<40> TextToInsert;
4591     TextToInsert += ' ';
4592     TextToInsert += NewTD->getIdentifier()->getName();
4593 
4594     Diag(FixitLoc, DiagID)
4595       << isa<TypeAliasDecl>(NewTD)
4596       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4597     if (NonCLike.Kind != NonCLikeKind::None) {
4598       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4599         << NonCLike.Kind - 1 << NonCLike.Range;
4600     }
4601     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4602       << NewTD << isa<TypeAliasDecl>(NewTD);
4603 
4604     if (ChangesLinkage)
4605       return;
4606   }
4607 
4608   // Otherwise, set this as the anon-decl typedef for the tag.
4609   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4610 }
4611 
4612 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4613   switch (T) {
4614   case DeclSpec::TST_class:
4615     return 0;
4616   case DeclSpec::TST_struct:
4617     return 1;
4618   case DeclSpec::TST_interface:
4619     return 2;
4620   case DeclSpec::TST_union:
4621     return 3;
4622   case DeclSpec::TST_enum:
4623     return 4;
4624   default:
4625     llvm_unreachable("unexpected type specifier");
4626   }
4627 }
4628 
4629 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4630 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4631 /// parameters to cope with template friend declarations.
4632 Decl *
4633 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4634                                  MultiTemplateParamsArg TemplateParams,
4635                                  bool IsExplicitInstantiation,
4636                                  RecordDecl *&AnonRecord) {
4637   Decl *TagD = nullptr;
4638   TagDecl *Tag = nullptr;
4639   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4640       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4641       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4642       DS.getTypeSpecType() == DeclSpec::TST_union ||
4643       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4644     TagD = DS.getRepAsDecl();
4645 
4646     if (!TagD) // We probably had an error
4647       return nullptr;
4648 
4649     // Note that the above type specs guarantee that the
4650     // type rep is a Decl, whereas in many of the others
4651     // it's a Type.
4652     if (isa<TagDecl>(TagD))
4653       Tag = cast<TagDecl>(TagD);
4654     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4655       Tag = CTD->getTemplatedDecl();
4656   }
4657 
4658   if (Tag) {
4659     handleTagNumbering(Tag, S);
4660     Tag->setFreeStanding();
4661     if (Tag->isInvalidDecl())
4662       return Tag;
4663   }
4664 
4665   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4666     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4667     // or incomplete types shall not be restrict-qualified."
4668     if (TypeQuals & DeclSpec::TQ_restrict)
4669       Diag(DS.getRestrictSpecLoc(),
4670            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4671            << DS.getSourceRange();
4672   }
4673 
4674   if (DS.isInlineSpecified())
4675     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4676         << getLangOpts().CPlusPlus17;
4677 
4678   if (DS.hasConstexprSpecifier()) {
4679     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4680     // and definitions of functions and variables.
4681     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4682     // the declaration of a function or function template
4683     if (Tag)
4684       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4685           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4686           << static_cast<int>(DS.getConstexprSpecifier());
4687     else
4688       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4689           << static_cast<int>(DS.getConstexprSpecifier());
4690     // Don't emit warnings after this error.
4691     return TagD;
4692   }
4693 
4694   DiagnoseFunctionSpecifiers(DS);
4695 
4696   if (DS.isFriendSpecified()) {
4697     // If we're dealing with a decl but not a TagDecl, assume that
4698     // whatever routines created it handled the friendship aspect.
4699     if (TagD && !Tag)
4700       return nullptr;
4701     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4702   }
4703 
4704   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4705   bool IsExplicitSpecialization =
4706     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4707   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4708       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4709       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4710     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4711     // nested-name-specifier unless it is an explicit instantiation
4712     // or an explicit specialization.
4713     //
4714     // FIXME: We allow class template partial specializations here too, per the
4715     // obvious intent of DR1819.
4716     //
4717     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4718     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4719         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4720     return nullptr;
4721   }
4722 
4723   // Track whether this decl-specifier declares anything.
4724   bool DeclaresAnything = true;
4725 
4726   // Handle anonymous struct definitions.
4727   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4728     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4729         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4730       if (getLangOpts().CPlusPlus ||
4731           Record->getDeclContext()->isRecord()) {
4732         // If CurContext is a DeclContext that can contain statements,
4733         // RecursiveASTVisitor won't visit the decls that
4734         // BuildAnonymousStructOrUnion() will put into CurContext.
4735         // Also store them here so that they can be part of the
4736         // DeclStmt that gets created in this case.
4737         // FIXME: Also return the IndirectFieldDecls created by
4738         // BuildAnonymousStructOr union, for the same reason?
4739         if (CurContext->isFunctionOrMethod())
4740           AnonRecord = Record;
4741         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4742                                            Context.getPrintingPolicy());
4743       }
4744 
4745       DeclaresAnything = false;
4746     }
4747   }
4748 
4749   // C11 6.7.2.1p2:
4750   //   A struct-declaration that does not declare an anonymous structure or
4751   //   anonymous union shall contain a struct-declarator-list.
4752   //
4753   // This rule also existed in C89 and C99; the grammar for struct-declaration
4754   // did not permit a struct-declaration without a struct-declarator-list.
4755   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4756       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4757     // Check for Microsoft C extension: anonymous struct/union member.
4758     // Handle 2 kinds of anonymous struct/union:
4759     //   struct STRUCT;
4760     //   union UNION;
4761     // and
4762     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4763     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4764     if ((Tag && Tag->getDeclName()) ||
4765         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4766       RecordDecl *Record = nullptr;
4767       if (Tag)
4768         Record = dyn_cast<RecordDecl>(Tag);
4769       else if (const RecordType *RT =
4770                    DS.getRepAsType().get()->getAsStructureType())
4771         Record = RT->getDecl();
4772       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4773         Record = UT->getDecl();
4774 
4775       if (Record && getLangOpts().MicrosoftExt) {
4776         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4777             << Record->isUnion() << DS.getSourceRange();
4778         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4779       }
4780 
4781       DeclaresAnything = false;
4782     }
4783   }
4784 
4785   // Skip all the checks below if we have a type error.
4786   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4787       (TagD && TagD->isInvalidDecl()))
4788     return TagD;
4789 
4790   if (getLangOpts().CPlusPlus &&
4791       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4792     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4793       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4794           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4795         DeclaresAnything = false;
4796 
4797   if (!DS.isMissingDeclaratorOk()) {
4798     // Customize diagnostic for a typedef missing a name.
4799     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4800       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4801           << DS.getSourceRange();
4802     else
4803       DeclaresAnything = false;
4804   }
4805 
4806   if (DS.isModulePrivateSpecified() &&
4807       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4808     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4809       << Tag->getTagKind()
4810       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4811 
4812   ActOnDocumentableDecl(TagD);
4813 
4814   // C 6.7/2:
4815   //   A declaration [...] shall declare at least a declarator [...], a tag,
4816   //   or the members of an enumeration.
4817   // C++ [dcl.dcl]p3:
4818   //   [If there are no declarators], and except for the declaration of an
4819   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4820   //   names into the program, or shall redeclare a name introduced by a
4821   //   previous declaration.
4822   if (!DeclaresAnything) {
4823     // In C, we allow this as a (popular) extension / bug. Don't bother
4824     // producing further diagnostics for redundant qualifiers after this.
4825     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4826                                ? diag::err_no_declarators
4827                                : diag::ext_no_declarators)
4828         << DS.getSourceRange();
4829     return TagD;
4830   }
4831 
4832   // C++ [dcl.stc]p1:
4833   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4834   //   init-declarator-list of the declaration shall not be empty.
4835   // C++ [dcl.fct.spec]p1:
4836   //   If a cv-qualifier appears in a decl-specifier-seq, the
4837   //   init-declarator-list of the declaration shall not be empty.
4838   //
4839   // Spurious qualifiers here appear to be valid in C.
4840   unsigned DiagID = diag::warn_standalone_specifier;
4841   if (getLangOpts().CPlusPlus)
4842     DiagID = diag::ext_standalone_specifier;
4843 
4844   // Note that a linkage-specification sets a storage class, but
4845   // 'extern "C" struct foo;' is actually valid and not theoretically
4846   // useless.
4847   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4848     if (SCS == DeclSpec::SCS_mutable)
4849       // Since mutable is not a viable storage class specifier in C, there is
4850       // no reason to treat it as an extension. Instead, diagnose as an error.
4851       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4852     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4853       Diag(DS.getStorageClassSpecLoc(), DiagID)
4854         << DeclSpec::getSpecifierName(SCS);
4855   }
4856 
4857   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4858     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4859       << DeclSpec::getSpecifierName(TSCS);
4860   if (DS.getTypeQualifiers()) {
4861     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4862       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4863     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4864       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4865     // Restrict is covered above.
4866     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4867       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4868     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4869       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4870   }
4871 
4872   // Warn about ignored type attributes, for example:
4873   // __attribute__((aligned)) struct A;
4874   // Attributes should be placed after tag to apply to type declaration.
4875   if (!DS.getAttributes().empty()) {
4876     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4877     if (TypeSpecType == DeclSpec::TST_class ||
4878         TypeSpecType == DeclSpec::TST_struct ||
4879         TypeSpecType == DeclSpec::TST_interface ||
4880         TypeSpecType == DeclSpec::TST_union ||
4881         TypeSpecType == DeclSpec::TST_enum) {
4882       for (const ParsedAttr &AL : DS.getAttributes())
4883         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4884             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4885     }
4886   }
4887 
4888   return TagD;
4889 }
4890 
4891 /// We are trying to inject an anonymous member into the given scope;
4892 /// check if there's an existing declaration that can't be overloaded.
4893 ///
4894 /// \return true if this is a forbidden redeclaration
4895 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4896                                          Scope *S,
4897                                          DeclContext *Owner,
4898                                          DeclarationName Name,
4899                                          SourceLocation NameLoc,
4900                                          bool IsUnion) {
4901   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4902                  Sema::ForVisibleRedeclaration);
4903   if (!SemaRef.LookupName(R, S)) return false;
4904 
4905   // Pick a representative declaration.
4906   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4907   assert(PrevDecl && "Expected a non-null Decl");
4908 
4909   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4910     return false;
4911 
4912   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4913     << IsUnion << Name;
4914   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4915 
4916   return true;
4917 }
4918 
4919 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4920 /// anonymous struct or union AnonRecord into the owning context Owner
4921 /// and scope S. This routine will be invoked just after we realize
4922 /// that an unnamed union or struct is actually an anonymous union or
4923 /// struct, e.g.,
4924 ///
4925 /// @code
4926 /// union {
4927 ///   int i;
4928 ///   float f;
4929 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4930 ///    // f into the surrounding scope.x
4931 /// @endcode
4932 ///
4933 /// This routine is recursive, injecting the names of nested anonymous
4934 /// structs/unions into the owning context and scope as well.
4935 static bool
4936 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4937                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4938                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4939   bool Invalid = false;
4940 
4941   // Look every FieldDecl and IndirectFieldDecl with a name.
4942   for (auto *D : AnonRecord->decls()) {
4943     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4944         cast<NamedDecl>(D)->getDeclName()) {
4945       ValueDecl *VD = cast<ValueDecl>(D);
4946       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4947                                        VD->getLocation(),
4948                                        AnonRecord->isUnion())) {
4949         // C++ [class.union]p2:
4950         //   The names of the members of an anonymous union shall be
4951         //   distinct from the names of any other entity in the
4952         //   scope in which the anonymous union is declared.
4953         Invalid = true;
4954       } else {
4955         // C++ [class.union]p2:
4956         //   For the purpose of name lookup, after the anonymous union
4957         //   definition, the members of the anonymous union are
4958         //   considered to have been defined in the scope in which the
4959         //   anonymous union is declared.
4960         unsigned OldChainingSize = Chaining.size();
4961         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4962           Chaining.append(IF->chain_begin(), IF->chain_end());
4963         else
4964           Chaining.push_back(VD);
4965 
4966         assert(Chaining.size() >= 2);
4967         NamedDecl **NamedChain =
4968           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4969         for (unsigned i = 0; i < Chaining.size(); i++)
4970           NamedChain[i] = Chaining[i];
4971 
4972         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4973             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4974             VD->getType(), {NamedChain, Chaining.size()});
4975 
4976         for (const auto *Attr : VD->attrs())
4977           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4978 
4979         IndirectField->setAccess(AS);
4980         IndirectField->setImplicit();
4981         SemaRef.PushOnScopeChains(IndirectField, S);
4982 
4983         // That includes picking up the appropriate access specifier.
4984         if (AS != AS_none) IndirectField->setAccess(AS);
4985 
4986         Chaining.resize(OldChainingSize);
4987       }
4988     }
4989   }
4990 
4991   return Invalid;
4992 }
4993 
4994 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4995 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4996 /// illegal input values are mapped to SC_None.
4997 static StorageClass
4998 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4999   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5000   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5001          "Parser allowed 'typedef' as storage class VarDecl.");
5002   switch (StorageClassSpec) {
5003   case DeclSpec::SCS_unspecified:    return SC_None;
5004   case DeclSpec::SCS_extern:
5005     if (DS.isExternInLinkageSpec())
5006       return SC_None;
5007     return SC_Extern;
5008   case DeclSpec::SCS_static:         return SC_Static;
5009   case DeclSpec::SCS_auto:           return SC_Auto;
5010   case DeclSpec::SCS_register:       return SC_Register;
5011   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5012     // Illegal SCSs map to None: error reporting is up to the caller.
5013   case DeclSpec::SCS_mutable:        // Fall through.
5014   case DeclSpec::SCS_typedef:        return SC_None;
5015   }
5016   llvm_unreachable("unknown storage class specifier");
5017 }
5018 
5019 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5020   assert(Record->hasInClassInitializer());
5021 
5022   for (const auto *I : Record->decls()) {
5023     const auto *FD = dyn_cast<FieldDecl>(I);
5024     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5025       FD = IFD->getAnonField();
5026     if (FD && FD->hasInClassInitializer())
5027       return FD->getLocation();
5028   }
5029 
5030   llvm_unreachable("couldn't find in-class initializer");
5031 }
5032 
5033 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5034                                       SourceLocation DefaultInitLoc) {
5035   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5036     return;
5037 
5038   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5039   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5040 }
5041 
5042 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5043                                       CXXRecordDecl *AnonUnion) {
5044   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5045     return;
5046 
5047   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5048 }
5049 
5050 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5051 /// anonymous structure or union. Anonymous unions are a C++ feature
5052 /// (C++ [class.union]) and a C11 feature; anonymous structures
5053 /// are a C11 feature and GNU C++ extension.
5054 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5055                                         AccessSpecifier AS,
5056                                         RecordDecl *Record,
5057                                         const PrintingPolicy &Policy) {
5058   DeclContext *Owner = Record->getDeclContext();
5059 
5060   // Diagnose whether this anonymous struct/union is an extension.
5061   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5062     Diag(Record->getLocation(), diag::ext_anonymous_union);
5063   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5064     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5065   else if (!Record->isUnion() && !getLangOpts().C11)
5066     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5067 
5068   // C and C++ require different kinds of checks for anonymous
5069   // structs/unions.
5070   bool Invalid = false;
5071   if (getLangOpts().CPlusPlus) {
5072     const char *PrevSpec = nullptr;
5073     if (Record->isUnion()) {
5074       // C++ [class.union]p6:
5075       // C++17 [class.union.anon]p2:
5076       //   Anonymous unions declared in a named namespace or in the
5077       //   global namespace shall be declared static.
5078       unsigned DiagID;
5079       DeclContext *OwnerScope = Owner->getRedeclContext();
5080       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5081           (OwnerScope->isTranslationUnit() ||
5082            (OwnerScope->isNamespace() &&
5083             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5084         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5085           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5086 
5087         // Recover by adding 'static'.
5088         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5089                                PrevSpec, DiagID, Policy);
5090       }
5091       // C++ [class.union]p6:
5092       //   A storage class is not allowed in a declaration of an
5093       //   anonymous union in a class scope.
5094       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5095                isa<RecordDecl>(Owner)) {
5096         Diag(DS.getStorageClassSpecLoc(),
5097              diag::err_anonymous_union_with_storage_spec)
5098           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5099 
5100         // Recover by removing the storage specifier.
5101         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5102                                SourceLocation(),
5103                                PrevSpec, DiagID, Context.getPrintingPolicy());
5104       }
5105     }
5106 
5107     // Ignore const/volatile/restrict qualifiers.
5108     if (DS.getTypeQualifiers()) {
5109       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5110         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5111           << Record->isUnion() << "const"
5112           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5113       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5114         Diag(DS.getVolatileSpecLoc(),
5115              diag::ext_anonymous_struct_union_qualified)
5116           << Record->isUnion() << "volatile"
5117           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5118       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5119         Diag(DS.getRestrictSpecLoc(),
5120              diag::ext_anonymous_struct_union_qualified)
5121           << Record->isUnion() << "restrict"
5122           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5123       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5124         Diag(DS.getAtomicSpecLoc(),
5125              diag::ext_anonymous_struct_union_qualified)
5126           << Record->isUnion() << "_Atomic"
5127           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5128       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5129         Diag(DS.getUnalignedSpecLoc(),
5130              diag::ext_anonymous_struct_union_qualified)
5131           << Record->isUnion() << "__unaligned"
5132           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5133 
5134       DS.ClearTypeQualifiers();
5135     }
5136 
5137     // C++ [class.union]p2:
5138     //   The member-specification of an anonymous union shall only
5139     //   define non-static data members. [Note: nested types and
5140     //   functions cannot be declared within an anonymous union. ]
5141     for (auto *Mem : Record->decls()) {
5142       // Ignore invalid declarations; we already diagnosed them.
5143       if (Mem->isInvalidDecl())
5144         continue;
5145 
5146       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5147         // C++ [class.union]p3:
5148         //   An anonymous union shall not have private or protected
5149         //   members (clause 11).
5150         assert(FD->getAccess() != AS_none);
5151         if (FD->getAccess() != AS_public) {
5152           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5153             << Record->isUnion() << (FD->getAccess() == AS_protected);
5154           Invalid = true;
5155         }
5156 
5157         // C++ [class.union]p1
5158         //   An object of a class with a non-trivial constructor, a non-trivial
5159         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5160         //   assignment operator cannot be a member of a union, nor can an
5161         //   array of such objects.
5162         if (CheckNontrivialField(FD))
5163           Invalid = true;
5164       } else if (Mem->isImplicit()) {
5165         // Any implicit members are fine.
5166       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5167         // This is a type that showed up in an
5168         // elaborated-type-specifier inside the anonymous struct or
5169         // union, but which actually declares a type outside of the
5170         // anonymous struct or union. It's okay.
5171       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5172         if (!MemRecord->isAnonymousStructOrUnion() &&
5173             MemRecord->getDeclName()) {
5174           // Visual C++ allows type definition in anonymous struct or union.
5175           if (getLangOpts().MicrosoftExt)
5176             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5177               << Record->isUnion();
5178           else {
5179             // This is a nested type declaration.
5180             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5181               << Record->isUnion();
5182             Invalid = true;
5183           }
5184         } else {
5185           // This is an anonymous type definition within another anonymous type.
5186           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5187           // not part of standard C++.
5188           Diag(MemRecord->getLocation(),
5189                diag::ext_anonymous_record_with_anonymous_type)
5190             << Record->isUnion();
5191         }
5192       } else if (isa<AccessSpecDecl>(Mem)) {
5193         // Any access specifier is fine.
5194       } else if (isa<StaticAssertDecl>(Mem)) {
5195         // In C++1z, static_assert declarations are also fine.
5196       } else {
5197         // We have something that isn't a non-static data
5198         // member. Complain about it.
5199         unsigned DK = diag::err_anonymous_record_bad_member;
5200         if (isa<TypeDecl>(Mem))
5201           DK = diag::err_anonymous_record_with_type;
5202         else if (isa<FunctionDecl>(Mem))
5203           DK = diag::err_anonymous_record_with_function;
5204         else if (isa<VarDecl>(Mem))
5205           DK = diag::err_anonymous_record_with_static;
5206 
5207         // Visual C++ allows type definition in anonymous struct or union.
5208         if (getLangOpts().MicrosoftExt &&
5209             DK == diag::err_anonymous_record_with_type)
5210           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5211             << Record->isUnion();
5212         else {
5213           Diag(Mem->getLocation(), DK) << Record->isUnion();
5214           Invalid = true;
5215         }
5216       }
5217     }
5218 
5219     // C++11 [class.union]p8 (DR1460):
5220     //   At most one variant member of a union may have a
5221     //   brace-or-equal-initializer.
5222     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5223         Owner->isRecord())
5224       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5225                                 cast<CXXRecordDecl>(Record));
5226   }
5227 
5228   if (!Record->isUnion() && !Owner->isRecord()) {
5229     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5230       << getLangOpts().CPlusPlus;
5231     Invalid = true;
5232   }
5233 
5234   // C++ [dcl.dcl]p3:
5235   //   [If there are no declarators], and except for the declaration of an
5236   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5237   //   names into the program
5238   // C++ [class.mem]p2:
5239   //   each such member-declaration shall either declare at least one member
5240   //   name of the class or declare at least one unnamed bit-field
5241   //
5242   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5243   if (getLangOpts().CPlusPlus && Record->field_empty())
5244     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5245 
5246   // Mock up a declarator.
5247   Declarator Dc(DS, DeclaratorContext::Member);
5248   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5249   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5250 
5251   // Create a declaration for this anonymous struct/union.
5252   NamedDecl *Anon = nullptr;
5253   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5254     Anon = FieldDecl::Create(
5255         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5256         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5257         /*BitWidth=*/nullptr, /*Mutable=*/false,
5258         /*InitStyle=*/ICIS_NoInit);
5259     Anon->setAccess(AS);
5260     ProcessDeclAttributes(S, Anon, Dc);
5261 
5262     if (getLangOpts().CPlusPlus)
5263       FieldCollector->Add(cast<FieldDecl>(Anon));
5264   } else {
5265     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5266     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5267     if (SCSpec == DeclSpec::SCS_mutable) {
5268       // mutable can only appear on non-static class members, so it's always
5269       // an error here
5270       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5271       Invalid = true;
5272       SC = SC_None;
5273     }
5274 
5275     assert(DS.getAttributes().empty() && "No attribute expected");
5276     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5277                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5278                            Context.getTypeDeclType(Record), TInfo, SC);
5279 
5280     // Default-initialize the implicit variable. This initialization will be
5281     // trivial in almost all cases, except if a union member has an in-class
5282     // initializer:
5283     //   union { int n = 0; };
5284     if (!Invalid)
5285       ActOnUninitializedDecl(Anon);
5286   }
5287   Anon->setImplicit();
5288 
5289   // Mark this as an anonymous struct/union type.
5290   Record->setAnonymousStructOrUnion(true);
5291 
5292   // Add the anonymous struct/union object to the current
5293   // context. We'll be referencing this object when we refer to one of
5294   // its members.
5295   Owner->addDecl(Anon);
5296 
5297   // Inject the members of the anonymous struct/union into the owning
5298   // context and into the identifier resolver chain for name lookup
5299   // purposes.
5300   SmallVector<NamedDecl*, 2> Chain;
5301   Chain.push_back(Anon);
5302 
5303   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5304     Invalid = true;
5305 
5306   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5307     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5308       MangleNumberingContext *MCtx;
5309       Decl *ManglingContextDecl;
5310       std::tie(MCtx, ManglingContextDecl) =
5311           getCurrentMangleNumberContext(NewVD->getDeclContext());
5312       if (MCtx) {
5313         Context.setManglingNumber(
5314             NewVD, MCtx->getManglingNumber(
5315                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5316         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5317       }
5318     }
5319   }
5320 
5321   if (Invalid)
5322     Anon->setInvalidDecl();
5323 
5324   return Anon;
5325 }
5326 
5327 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5328 /// Microsoft C anonymous structure.
5329 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5330 /// Example:
5331 ///
5332 /// struct A { int a; };
5333 /// struct B { struct A; int b; };
5334 ///
5335 /// void foo() {
5336 ///   B var;
5337 ///   var.a = 3;
5338 /// }
5339 ///
5340 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5341                                            RecordDecl *Record) {
5342   assert(Record && "expected a record!");
5343 
5344   // Mock up a declarator.
5345   Declarator Dc(DS, DeclaratorContext::TypeName);
5346   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5347   assert(TInfo && "couldn't build declarator info for anonymous struct");
5348 
5349   auto *ParentDecl = cast<RecordDecl>(CurContext);
5350   QualType RecTy = Context.getTypeDeclType(Record);
5351 
5352   // Create a declaration for this anonymous struct.
5353   NamedDecl *Anon =
5354       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5355                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5356                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5357                         /*InitStyle=*/ICIS_NoInit);
5358   Anon->setImplicit();
5359 
5360   // Add the anonymous struct object to the current context.
5361   CurContext->addDecl(Anon);
5362 
5363   // Inject the members of the anonymous struct into the current
5364   // context and into the identifier resolver chain for name lookup
5365   // purposes.
5366   SmallVector<NamedDecl*, 2> Chain;
5367   Chain.push_back(Anon);
5368 
5369   RecordDecl *RecordDef = Record->getDefinition();
5370   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5371                                diag::err_field_incomplete_or_sizeless) ||
5372       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5373                                           AS_none, Chain)) {
5374     Anon->setInvalidDecl();
5375     ParentDecl->setInvalidDecl();
5376   }
5377 
5378   return Anon;
5379 }
5380 
5381 /// GetNameForDeclarator - Determine the full declaration name for the
5382 /// given Declarator.
5383 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5384   return GetNameFromUnqualifiedId(D.getName());
5385 }
5386 
5387 /// Retrieves the declaration name from a parsed unqualified-id.
5388 DeclarationNameInfo
5389 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5390   DeclarationNameInfo NameInfo;
5391   NameInfo.setLoc(Name.StartLocation);
5392 
5393   switch (Name.getKind()) {
5394 
5395   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5396   case UnqualifiedIdKind::IK_Identifier:
5397     NameInfo.setName(Name.Identifier);
5398     return NameInfo;
5399 
5400   case UnqualifiedIdKind::IK_DeductionGuideName: {
5401     // C++ [temp.deduct.guide]p3:
5402     //   The simple-template-id shall name a class template specialization.
5403     //   The template-name shall be the same identifier as the template-name
5404     //   of the simple-template-id.
5405     // These together intend to imply that the template-name shall name a
5406     // class template.
5407     // FIXME: template<typename T> struct X {};
5408     //        template<typename T> using Y = X<T>;
5409     //        Y(int) -> Y<int>;
5410     //   satisfies these rules but does not name a class template.
5411     TemplateName TN = Name.TemplateName.get().get();
5412     auto *Template = TN.getAsTemplateDecl();
5413     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5414       Diag(Name.StartLocation,
5415            diag::err_deduction_guide_name_not_class_template)
5416         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5417       if (Template)
5418         Diag(Template->getLocation(), diag::note_template_decl_here);
5419       return DeclarationNameInfo();
5420     }
5421 
5422     NameInfo.setName(
5423         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5424     return NameInfo;
5425   }
5426 
5427   case UnqualifiedIdKind::IK_OperatorFunctionId:
5428     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5429                                            Name.OperatorFunctionId.Operator));
5430     NameInfo.setCXXOperatorNameRange(SourceRange(
5431         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5432     return NameInfo;
5433 
5434   case UnqualifiedIdKind::IK_LiteralOperatorId:
5435     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5436                                                            Name.Identifier));
5437     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5438     return NameInfo;
5439 
5440   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5441     TypeSourceInfo *TInfo;
5442     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5443     if (Ty.isNull())
5444       return DeclarationNameInfo();
5445     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5446                                                Context.getCanonicalType(Ty)));
5447     NameInfo.setNamedTypeInfo(TInfo);
5448     return NameInfo;
5449   }
5450 
5451   case UnqualifiedIdKind::IK_ConstructorName: {
5452     TypeSourceInfo *TInfo;
5453     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5454     if (Ty.isNull())
5455       return DeclarationNameInfo();
5456     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5457                                               Context.getCanonicalType(Ty)));
5458     NameInfo.setNamedTypeInfo(TInfo);
5459     return NameInfo;
5460   }
5461 
5462   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5463     // In well-formed code, we can only have a constructor
5464     // template-id that refers to the current context, so go there
5465     // to find the actual type being constructed.
5466     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5467     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5468       return DeclarationNameInfo();
5469 
5470     // Determine the type of the class being constructed.
5471     QualType CurClassType = Context.getTypeDeclType(CurClass);
5472 
5473     // FIXME: Check two things: that the template-id names the same type as
5474     // CurClassType, and that the template-id does not occur when the name
5475     // was qualified.
5476 
5477     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5478                                     Context.getCanonicalType(CurClassType)));
5479     // FIXME: should we retrieve TypeSourceInfo?
5480     NameInfo.setNamedTypeInfo(nullptr);
5481     return NameInfo;
5482   }
5483 
5484   case UnqualifiedIdKind::IK_DestructorName: {
5485     TypeSourceInfo *TInfo;
5486     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5487     if (Ty.isNull())
5488       return DeclarationNameInfo();
5489     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5490                                               Context.getCanonicalType(Ty)));
5491     NameInfo.setNamedTypeInfo(TInfo);
5492     return NameInfo;
5493   }
5494 
5495   case UnqualifiedIdKind::IK_TemplateId: {
5496     TemplateName TName = Name.TemplateId->Template.get();
5497     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5498     return Context.getNameForTemplate(TName, TNameLoc);
5499   }
5500 
5501   } // switch (Name.getKind())
5502 
5503   llvm_unreachable("Unknown name kind");
5504 }
5505 
5506 static QualType getCoreType(QualType Ty) {
5507   do {
5508     if (Ty->isPointerType() || Ty->isReferenceType())
5509       Ty = Ty->getPointeeType();
5510     else if (Ty->isArrayType())
5511       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5512     else
5513       return Ty.withoutLocalFastQualifiers();
5514   } while (true);
5515 }
5516 
5517 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5518 /// and Definition have "nearly" matching parameters. This heuristic is
5519 /// used to improve diagnostics in the case where an out-of-line function
5520 /// definition doesn't match any declaration within the class or namespace.
5521 /// Also sets Params to the list of indices to the parameters that differ
5522 /// between the declaration and the definition. If hasSimilarParameters
5523 /// returns true and Params is empty, then all of the parameters match.
5524 static bool hasSimilarParameters(ASTContext &Context,
5525                                      FunctionDecl *Declaration,
5526                                      FunctionDecl *Definition,
5527                                      SmallVectorImpl<unsigned> &Params) {
5528   Params.clear();
5529   if (Declaration->param_size() != Definition->param_size())
5530     return false;
5531   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5532     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5533     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5534 
5535     // The parameter types are identical
5536     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5537       continue;
5538 
5539     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5540     QualType DefParamBaseTy = getCoreType(DefParamTy);
5541     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5542     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5543 
5544     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5545         (DeclTyName && DeclTyName == DefTyName))
5546       Params.push_back(Idx);
5547     else  // The two parameters aren't even close
5548       return false;
5549   }
5550 
5551   return true;
5552 }
5553 
5554 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5555 /// declarator needs to be rebuilt in the current instantiation.
5556 /// Any bits of declarator which appear before the name are valid for
5557 /// consideration here.  That's specifically the type in the decl spec
5558 /// and the base type in any member-pointer chunks.
5559 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5560                                                     DeclarationName Name) {
5561   // The types we specifically need to rebuild are:
5562   //   - typenames, typeofs, and decltypes
5563   //   - types which will become injected class names
5564   // Of course, we also need to rebuild any type referencing such a
5565   // type.  It's safest to just say "dependent", but we call out a
5566   // few cases here.
5567 
5568   DeclSpec &DS = D.getMutableDeclSpec();
5569   switch (DS.getTypeSpecType()) {
5570   case DeclSpec::TST_typename:
5571   case DeclSpec::TST_typeofType:
5572   case DeclSpec::TST_underlyingType:
5573   case DeclSpec::TST_atomic: {
5574     // Grab the type from the parser.
5575     TypeSourceInfo *TSI = nullptr;
5576     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5577     if (T.isNull() || !T->isInstantiationDependentType()) break;
5578 
5579     // Make sure there's a type source info.  This isn't really much
5580     // of a waste; most dependent types should have type source info
5581     // attached already.
5582     if (!TSI)
5583       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5584 
5585     // Rebuild the type in the current instantiation.
5586     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5587     if (!TSI) return true;
5588 
5589     // Store the new type back in the decl spec.
5590     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5591     DS.UpdateTypeRep(LocType);
5592     break;
5593   }
5594 
5595   case DeclSpec::TST_decltype:
5596   case DeclSpec::TST_typeofExpr: {
5597     Expr *E = DS.getRepAsExpr();
5598     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5599     if (Result.isInvalid()) return true;
5600     DS.UpdateExprRep(Result.get());
5601     break;
5602   }
5603 
5604   default:
5605     // Nothing to do for these decl specs.
5606     break;
5607   }
5608 
5609   // It doesn't matter what order we do this in.
5610   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5611     DeclaratorChunk &Chunk = D.getTypeObject(I);
5612 
5613     // The only type information in the declarator which can come
5614     // before the declaration name is the base type of a member
5615     // pointer.
5616     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5617       continue;
5618 
5619     // Rebuild the scope specifier in-place.
5620     CXXScopeSpec &SS = Chunk.Mem.Scope();
5621     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5622       return true;
5623   }
5624 
5625   return false;
5626 }
5627 
5628 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5629   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5630   // of system decl.
5631   if (D->getPreviousDecl() || D->isImplicit())
5632     return;
5633   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5634   if (Status != ReservedIdentifierStatus::NotReserved &&
5635       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5636     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5637         << D << static_cast<int>(Status);
5638 }
5639 
5640 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5641   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5642   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5643 
5644   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5645       Dcl && Dcl->getDeclContext()->isFileContext())
5646     Dcl->setTopLevelDeclInObjCContainer();
5647 
5648   return Dcl;
5649 }
5650 
5651 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5652 ///   If T is the name of a class, then each of the following shall have a
5653 ///   name different from T:
5654 ///     - every static data member of class T;
5655 ///     - every member function of class T
5656 ///     - every member of class T that is itself a type;
5657 /// \returns true if the declaration name violates these rules.
5658 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5659                                    DeclarationNameInfo NameInfo) {
5660   DeclarationName Name = NameInfo.getName();
5661 
5662   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5663   while (Record && Record->isAnonymousStructOrUnion())
5664     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5665   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5666     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5667     return true;
5668   }
5669 
5670   return false;
5671 }
5672 
5673 /// Diagnose a declaration whose declarator-id has the given
5674 /// nested-name-specifier.
5675 ///
5676 /// \param SS The nested-name-specifier of the declarator-id.
5677 ///
5678 /// \param DC The declaration context to which the nested-name-specifier
5679 /// resolves.
5680 ///
5681 /// \param Name The name of the entity being declared.
5682 ///
5683 /// \param Loc The location of the name of the entity being declared.
5684 ///
5685 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5686 /// we're declaring an explicit / partial specialization / instantiation.
5687 ///
5688 /// \returns true if we cannot safely recover from this error, false otherwise.
5689 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5690                                         DeclarationName Name,
5691                                         SourceLocation Loc, bool IsTemplateId) {
5692   DeclContext *Cur = CurContext;
5693   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5694     Cur = Cur->getParent();
5695 
5696   // If the user provided a superfluous scope specifier that refers back to the
5697   // class in which the entity is already declared, diagnose and ignore it.
5698   //
5699   // class X {
5700   //   void X::f();
5701   // };
5702   //
5703   // Note, it was once ill-formed to give redundant qualification in all
5704   // contexts, but that rule was removed by DR482.
5705   if (Cur->Equals(DC)) {
5706     if (Cur->isRecord()) {
5707       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5708                                       : diag::err_member_extra_qualification)
5709         << Name << FixItHint::CreateRemoval(SS.getRange());
5710       SS.clear();
5711     } else {
5712       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5713     }
5714     return false;
5715   }
5716 
5717   // Check whether the qualifying scope encloses the scope of the original
5718   // declaration. For a template-id, we perform the checks in
5719   // CheckTemplateSpecializationScope.
5720   if (!Cur->Encloses(DC) && !IsTemplateId) {
5721     if (Cur->isRecord())
5722       Diag(Loc, diag::err_member_qualification)
5723         << Name << SS.getRange();
5724     else if (isa<TranslationUnitDecl>(DC))
5725       Diag(Loc, diag::err_invalid_declarator_global_scope)
5726         << Name << SS.getRange();
5727     else if (isa<FunctionDecl>(Cur))
5728       Diag(Loc, diag::err_invalid_declarator_in_function)
5729         << Name << SS.getRange();
5730     else if (isa<BlockDecl>(Cur))
5731       Diag(Loc, diag::err_invalid_declarator_in_block)
5732         << Name << SS.getRange();
5733     else
5734       Diag(Loc, diag::err_invalid_declarator_scope)
5735       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5736 
5737     return true;
5738   }
5739 
5740   if (Cur->isRecord()) {
5741     // Cannot qualify members within a class.
5742     Diag(Loc, diag::err_member_qualification)
5743       << Name << SS.getRange();
5744     SS.clear();
5745 
5746     // C++ constructors and destructors with incorrect scopes can break
5747     // our AST invariants by having the wrong underlying types. If
5748     // that's the case, then drop this declaration entirely.
5749     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5750          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5751         !Context.hasSameType(Name.getCXXNameType(),
5752                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5753       return true;
5754 
5755     return false;
5756   }
5757 
5758   // C++11 [dcl.meaning]p1:
5759   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5760   //   not begin with a decltype-specifer"
5761   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5762   while (SpecLoc.getPrefix())
5763     SpecLoc = SpecLoc.getPrefix();
5764   if (dyn_cast_or_null<DecltypeType>(
5765         SpecLoc.getNestedNameSpecifier()->getAsType()))
5766     Diag(Loc, diag::err_decltype_in_declarator)
5767       << SpecLoc.getTypeLoc().getSourceRange();
5768 
5769   return false;
5770 }
5771 
5772 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5773                                   MultiTemplateParamsArg TemplateParamLists) {
5774   // TODO: consider using NameInfo for diagnostic.
5775   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5776   DeclarationName Name = NameInfo.getName();
5777 
5778   // All of these full declarators require an identifier.  If it doesn't have
5779   // one, the ParsedFreeStandingDeclSpec action should be used.
5780   if (D.isDecompositionDeclarator()) {
5781     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5782   } else if (!Name) {
5783     if (!D.isInvalidType())  // Reject this if we think it is valid.
5784       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5785           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5786     return nullptr;
5787   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5788     return nullptr;
5789 
5790   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5791   // we find one that is.
5792   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5793          (S->getFlags() & Scope::TemplateParamScope) != 0)
5794     S = S->getParent();
5795 
5796   DeclContext *DC = CurContext;
5797   if (D.getCXXScopeSpec().isInvalid())
5798     D.setInvalidType();
5799   else if (D.getCXXScopeSpec().isSet()) {
5800     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5801                                         UPPC_DeclarationQualifier))
5802       return nullptr;
5803 
5804     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5805     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5806     if (!DC || isa<EnumDecl>(DC)) {
5807       // If we could not compute the declaration context, it's because the
5808       // declaration context is dependent but does not refer to a class,
5809       // class template, or class template partial specialization. Complain
5810       // and return early, to avoid the coming semantic disaster.
5811       Diag(D.getIdentifierLoc(),
5812            diag::err_template_qualified_declarator_no_match)
5813         << D.getCXXScopeSpec().getScopeRep()
5814         << D.getCXXScopeSpec().getRange();
5815       return nullptr;
5816     }
5817     bool IsDependentContext = DC->isDependentContext();
5818 
5819     if (!IsDependentContext &&
5820         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5821       return nullptr;
5822 
5823     // If a class is incomplete, do not parse entities inside it.
5824     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5825       Diag(D.getIdentifierLoc(),
5826            diag::err_member_def_undefined_record)
5827         << Name << DC << D.getCXXScopeSpec().getRange();
5828       return nullptr;
5829     }
5830     if (!D.getDeclSpec().isFriendSpecified()) {
5831       if (diagnoseQualifiedDeclaration(
5832               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5833               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5834         if (DC->isRecord())
5835           return nullptr;
5836 
5837         D.setInvalidType();
5838       }
5839     }
5840 
5841     // Check whether we need to rebuild the type of the given
5842     // declaration in the current instantiation.
5843     if (EnteringContext && IsDependentContext &&
5844         TemplateParamLists.size() != 0) {
5845       ContextRAII SavedContext(*this, DC);
5846       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5847         D.setInvalidType();
5848     }
5849   }
5850 
5851   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5852   QualType R = TInfo->getType();
5853 
5854   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5855                                       UPPC_DeclarationType))
5856     D.setInvalidType();
5857 
5858   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5859                         forRedeclarationInCurContext());
5860 
5861   // See if this is a redefinition of a variable in the same scope.
5862   if (!D.getCXXScopeSpec().isSet()) {
5863     bool IsLinkageLookup = false;
5864     bool CreateBuiltins = false;
5865 
5866     // If the declaration we're planning to build will be a function
5867     // or object with linkage, then look for another declaration with
5868     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5869     //
5870     // If the declaration we're planning to build will be declared with
5871     // external linkage in the translation unit, create any builtin with
5872     // the same name.
5873     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5874       /* Do nothing*/;
5875     else if (CurContext->isFunctionOrMethod() &&
5876              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5877               R->isFunctionType())) {
5878       IsLinkageLookup = true;
5879       CreateBuiltins =
5880           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5881     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5882                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5883       CreateBuiltins = true;
5884 
5885     if (IsLinkageLookup) {
5886       Previous.clear(LookupRedeclarationWithLinkage);
5887       Previous.setRedeclarationKind(ForExternalRedeclaration);
5888     }
5889 
5890     LookupName(Previous, S, CreateBuiltins);
5891   } else { // Something like "int foo::x;"
5892     LookupQualifiedName(Previous, DC);
5893 
5894     // C++ [dcl.meaning]p1:
5895     //   When the declarator-id is qualified, the declaration shall refer to a
5896     //  previously declared member of the class or namespace to which the
5897     //  qualifier refers (or, in the case of a namespace, of an element of the
5898     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5899     //  thereof; [...]
5900     //
5901     // Note that we already checked the context above, and that we do not have
5902     // enough information to make sure that Previous contains the declaration
5903     // we want to match. For example, given:
5904     //
5905     //   class X {
5906     //     void f();
5907     //     void f(float);
5908     //   };
5909     //
5910     //   void X::f(int) { } // ill-formed
5911     //
5912     // In this case, Previous will point to the overload set
5913     // containing the two f's declared in X, but neither of them
5914     // matches.
5915 
5916     // C++ [dcl.meaning]p1:
5917     //   [...] the member shall not merely have been introduced by a
5918     //   using-declaration in the scope of the class or namespace nominated by
5919     //   the nested-name-specifier of the declarator-id.
5920     RemoveUsingDecls(Previous);
5921   }
5922 
5923   if (Previous.isSingleResult() &&
5924       Previous.getFoundDecl()->isTemplateParameter()) {
5925     // Maybe we will complain about the shadowed template parameter.
5926     if (!D.isInvalidType())
5927       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5928                                       Previous.getFoundDecl());
5929 
5930     // Just pretend that we didn't see the previous declaration.
5931     Previous.clear();
5932   }
5933 
5934   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5935     // Forget that the previous declaration is the injected-class-name.
5936     Previous.clear();
5937 
5938   // In C++, the previous declaration we find might be a tag type
5939   // (class or enum). In this case, the new declaration will hide the
5940   // tag type. Note that this applies to functions, function templates, and
5941   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5942   if (Previous.isSingleTagDecl() &&
5943       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5944       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5945     Previous.clear();
5946 
5947   // Check that there are no default arguments other than in the parameters
5948   // of a function declaration (C++ only).
5949   if (getLangOpts().CPlusPlus)
5950     CheckExtraCXXDefaultArguments(D);
5951 
5952   NamedDecl *New;
5953 
5954   bool AddToScope = true;
5955   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5956     if (TemplateParamLists.size()) {
5957       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5958       return nullptr;
5959     }
5960 
5961     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5962   } else if (R->isFunctionType()) {
5963     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5964                                   TemplateParamLists,
5965                                   AddToScope);
5966   } else {
5967     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5968                                   AddToScope);
5969   }
5970 
5971   if (!New)
5972     return nullptr;
5973 
5974   // If this has an identifier and is not a function template specialization,
5975   // add it to the scope stack.
5976   if (New->getDeclName() && AddToScope)
5977     PushOnScopeChains(New, S);
5978 
5979   if (isInOpenMPDeclareTargetContext())
5980     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5981 
5982   return New;
5983 }
5984 
5985 /// Helper method to turn variable array types into constant array
5986 /// types in certain situations which would otherwise be errors (for
5987 /// GCC compatibility).
5988 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5989                                                     ASTContext &Context,
5990                                                     bool &SizeIsNegative,
5991                                                     llvm::APSInt &Oversized) {
5992   // This method tries to turn a variable array into a constant
5993   // array even when the size isn't an ICE.  This is necessary
5994   // for compatibility with code that depends on gcc's buggy
5995   // constant expression folding, like struct {char x[(int)(char*)2];}
5996   SizeIsNegative = false;
5997   Oversized = 0;
5998 
5999   if (T->isDependentType())
6000     return QualType();
6001 
6002   QualifierCollector Qs;
6003   const Type *Ty = Qs.strip(T);
6004 
6005   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6006     QualType Pointee = PTy->getPointeeType();
6007     QualType FixedType =
6008         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6009                                             Oversized);
6010     if (FixedType.isNull()) return FixedType;
6011     FixedType = Context.getPointerType(FixedType);
6012     return Qs.apply(Context, FixedType);
6013   }
6014   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6015     QualType Inner = PTy->getInnerType();
6016     QualType FixedType =
6017         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6018                                             Oversized);
6019     if (FixedType.isNull()) return FixedType;
6020     FixedType = Context.getParenType(FixedType);
6021     return Qs.apply(Context, FixedType);
6022   }
6023 
6024   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6025   if (!VLATy)
6026     return QualType();
6027 
6028   QualType ElemTy = VLATy->getElementType();
6029   if (ElemTy->isVariablyModifiedType()) {
6030     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6031                                                  SizeIsNegative, Oversized);
6032     if (ElemTy.isNull())
6033       return QualType();
6034   }
6035 
6036   Expr::EvalResult Result;
6037   if (!VLATy->getSizeExpr() ||
6038       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6039     return QualType();
6040 
6041   llvm::APSInt Res = Result.Val.getInt();
6042 
6043   // Check whether the array size is negative.
6044   if (Res.isSigned() && Res.isNegative()) {
6045     SizeIsNegative = true;
6046     return QualType();
6047   }
6048 
6049   // Check whether the array is too large to be addressed.
6050   unsigned ActiveSizeBits =
6051       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6052        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6053           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6054           : Res.getActiveBits();
6055   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6056     Oversized = Res;
6057     return QualType();
6058   }
6059 
6060   QualType FoldedArrayType = Context.getConstantArrayType(
6061       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6062   return Qs.apply(Context, FoldedArrayType);
6063 }
6064 
6065 static void
6066 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6067   SrcTL = SrcTL.getUnqualifiedLoc();
6068   DstTL = DstTL.getUnqualifiedLoc();
6069   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6070     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6071     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6072                                       DstPTL.getPointeeLoc());
6073     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6074     return;
6075   }
6076   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6077     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6078     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6079                                       DstPTL.getInnerLoc());
6080     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6081     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6082     return;
6083   }
6084   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6085   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6086   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6087   TypeLoc DstElemTL = DstATL.getElementLoc();
6088   if (VariableArrayTypeLoc SrcElemATL =
6089           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6090     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6091     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6092   } else {
6093     DstElemTL.initializeFullCopy(SrcElemTL);
6094   }
6095   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6096   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6097   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6098 }
6099 
6100 /// Helper method to turn variable array types into constant array
6101 /// types in certain situations which would otherwise be errors (for
6102 /// GCC compatibility).
6103 static TypeSourceInfo*
6104 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6105                                               ASTContext &Context,
6106                                               bool &SizeIsNegative,
6107                                               llvm::APSInt &Oversized) {
6108   QualType FixedTy
6109     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6110                                           SizeIsNegative, Oversized);
6111   if (FixedTy.isNull())
6112     return nullptr;
6113   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6114   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6115                                     FixedTInfo->getTypeLoc());
6116   return FixedTInfo;
6117 }
6118 
6119 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6120 /// true if we were successful.
6121 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6122                                            QualType &T, SourceLocation Loc,
6123                                            unsigned FailedFoldDiagID) {
6124   bool SizeIsNegative;
6125   llvm::APSInt Oversized;
6126   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6127       TInfo, Context, SizeIsNegative, Oversized);
6128   if (FixedTInfo) {
6129     Diag(Loc, diag::ext_vla_folded_to_constant);
6130     TInfo = FixedTInfo;
6131     T = FixedTInfo->getType();
6132     return true;
6133   }
6134 
6135   if (SizeIsNegative)
6136     Diag(Loc, diag::err_typecheck_negative_array_size);
6137   else if (Oversized.getBoolValue())
6138     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6139   else if (FailedFoldDiagID)
6140     Diag(Loc, FailedFoldDiagID);
6141   return false;
6142 }
6143 
6144 /// Register the given locally-scoped extern "C" declaration so
6145 /// that it can be found later for redeclarations. We include any extern "C"
6146 /// declaration that is not visible in the translation unit here, not just
6147 /// function-scope declarations.
6148 void
6149 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6150   if (!getLangOpts().CPlusPlus &&
6151       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6152     // Don't need to track declarations in the TU in C.
6153     return;
6154 
6155   // Note that we have a locally-scoped external with this name.
6156   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6157 }
6158 
6159 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6160   // FIXME: We can have multiple results via __attribute__((overloadable)).
6161   auto Result = Context.getExternCContextDecl()->lookup(Name);
6162   return Result.empty() ? nullptr : *Result.begin();
6163 }
6164 
6165 /// Diagnose function specifiers on a declaration of an identifier that
6166 /// does not identify a function.
6167 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6168   // FIXME: We should probably indicate the identifier in question to avoid
6169   // confusion for constructs like "virtual int a(), b;"
6170   if (DS.isVirtualSpecified())
6171     Diag(DS.getVirtualSpecLoc(),
6172          diag::err_virtual_non_function);
6173 
6174   if (DS.hasExplicitSpecifier())
6175     Diag(DS.getExplicitSpecLoc(),
6176          diag::err_explicit_non_function);
6177 
6178   if (DS.isNoreturnSpecified())
6179     Diag(DS.getNoreturnSpecLoc(),
6180          diag::err_noreturn_non_function);
6181 }
6182 
6183 NamedDecl*
6184 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6185                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6186   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6187   if (D.getCXXScopeSpec().isSet()) {
6188     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6189       << D.getCXXScopeSpec().getRange();
6190     D.setInvalidType();
6191     // Pretend we didn't see the scope specifier.
6192     DC = CurContext;
6193     Previous.clear();
6194   }
6195 
6196   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6197 
6198   if (D.getDeclSpec().isInlineSpecified())
6199     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6200         << getLangOpts().CPlusPlus17;
6201   if (D.getDeclSpec().hasConstexprSpecifier())
6202     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6203         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6204 
6205   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6206     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6207       Diag(D.getName().StartLocation,
6208            diag::err_deduction_guide_invalid_specifier)
6209           << "typedef";
6210     else
6211       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6212           << D.getName().getSourceRange();
6213     return nullptr;
6214   }
6215 
6216   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6217   if (!NewTD) return nullptr;
6218 
6219   // Handle attributes prior to checking for duplicates in MergeVarDecl
6220   ProcessDeclAttributes(S, NewTD, D);
6221 
6222   CheckTypedefForVariablyModifiedType(S, NewTD);
6223 
6224   bool Redeclaration = D.isRedeclaration();
6225   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6226   D.setRedeclaration(Redeclaration);
6227   return ND;
6228 }
6229 
6230 void
6231 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6232   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6233   // then it shall have block scope.
6234   // Note that variably modified types must be fixed before merging the decl so
6235   // that redeclarations will match.
6236   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6237   QualType T = TInfo->getType();
6238   if (T->isVariablyModifiedType()) {
6239     setFunctionHasBranchProtectedScope();
6240 
6241     if (S->getFnParent() == nullptr) {
6242       bool SizeIsNegative;
6243       llvm::APSInt Oversized;
6244       TypeSourceInfo *FixedTInfo =
6245         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6246                                                       SizeIsNegative,
6247                                                       Oversized);
6248       if (FixedTInfo) {
6249         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6250         NewTD->setTypeSourceInfo(FixedTInfo);
6251       } else {
6252         if (SizeIsNegative)
6253           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6254         else if (T->isVariableArrayType())
6255           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6256         else if (Oversized.getBoolValue())
6257           Diag(NewTD->getLocation(), diag::err_array_too_large)
6258             << toString(Oversized, 10);
6259         else
6260           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6261         NewTD->setInvalidDecl();
6262       }
6263     }
6264   }
6265 }
6266 
6267 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6268 /// declares a typedef-name, either using the 'typedef' type specifier or via
6269 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6270 NamedDecl*
6271 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6272                            LookupResult &Previous, bool &Redeclaration) {
6273 
6274   // Find the shadowed declaration before filtering for scope.
6275   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6276 
6277   // Merge the decl with the existing one if appropriate. If the decl is
6278   // in an outer scope, it isn't the same thing.
6279   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6280                        /*AllowInlineNamespace*/false);
6281   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6282   if (!Previous.empty()) {
6283     Redeclaration = true;
6284     MergeTypedefNameDecl(S, NewTD, Previous);
6285   } else {
6286     inferGslPointerAttribute(NewTD);
6287   }
6288 
6289   if (ShadowedDecl && !Redeclaration)
6290     CheckShadow(NewTD, ShadowedDecl, Previous);
6291 
6292   // If this is the C FILE type, notify the AST context.
6293   if (IdentifierInfo *II = NewTD->getIdentifier())
6294     if (!NewTD->isInvalidDecl() &&
6295         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6296       if (II->isStr("FILE"))
6297         Context.setFILEDecl(NewTD);
6298       else if (II->isStr("jmp_buf"))
6299         Context.setjmp_bufDecl(NewTD);
6300       else if (II->isStr("sigjmp_buf"))
6301         Context.setsigjmp_bufDecl(NewTD);
6302       else if (II->isStr("ucontext_t"))
6303         Context.setucontext_tDecl(NewTD);
6304     }
6305 
6306   return NewTD;
6307 }
6308 
6309 /// Determines whether the given declaration is an out-of-scope
6310 /// previous declaration.
6311 ///
6312 /// This routine should be invoked when name lookup has found a
6313 /// previous declaration (PrevDecl) that is not in the scope where a
6314 /// new declaration by the same name is being introduced. If the new
6315 /// declaration occurs in a local scope, previous declarations with
6316 /// linkage may still be considered previous declarations (C99
6317 /// 6.2.2p4-5, C++ [basic.link]p6).
6318 ///
6319 /// \param PrevDecl the previous declaration found by name
6320 /// lookup
6321 ///
6322 /// \param DC the context in which the new declaration is being
6323 /// declared.
6324 ///
6325 /// \returns true if PrevDecl is an out-of-scope previous declaration
6326 /// for a new delcaration with the same name.
6327 static bool
6328 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6329                                 ASTContext &Context) {
6330   if (!PrevDecl)
6331     return false;
6332 
6333   if (!PrevDecl->hasLinkage())
6334     return false;
6335 
6336   if (Context.getLangOpts().CPlusPlus) {
6337     // C++ [basic.link]p6:
6338     //   If there is a visible declaration of an entity with linkage
6339     //   having the same name and type, ignoring entities declared
6340     //   outside the innermost enclosing namespace scope, the block
6341     //   scope declaration declares that same entity and receives the
6342     //   linkage of the previous declaration.
6343     DeclContext *OuterContext = DC->getRedeclContext();
6344     if (!OuterContext->isFunctionOrMethod())
6345       // This rule only applies to block-scope declarations.
6346       return false;
6347 
6348     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6349     if (PrevOuterContext->isRecord())
6350       // We found a member function: ignore it.
6351       return false;
6352 
6353     // Find the innermost enclosing namespace for the new and
6354     // previous declarations.
6355     OuterContext = OuterContext->getEnclosingNamespaceContext();
6356     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6357 
6358     // The previous declaration is in a different namespace, so it
6359     // isn't the same function.
6360     if (!OuterContext->Equals(PrevOuterContext))
6361       return false;
6362   }
6363 
6364   return true;
6365 }
6366 
6367 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6368   CXXScopeSpec &SS = D.getCXXScopeSpec();
6369   if (!SS.isSet()) return;
6370   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6371 }
6372 
6373 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6374   QualType type = decl->getType();
6375   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6376   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6377     // Various kinds of declaration aren't allowed to be __autoreleasing.
6378     unsigned kind = -1U;
6379     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6380       if (var->hasAttr<BlocksAttr>())
6381         kind = 0; // __block
6382       else if (!var->hasLocalStorage())
6383         kind = 1; // global
6384     } else if (isa<ObjCIvarDecl>(decl)) {
6385       kind = 3; // ivar
6386     } else if (isa<FieldDecl>(decl)) {
6387       kind = 2; // field
6388     }
6389 
6390     if (kind != -1U) {
6391       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6392         << kind;
6393     }
6394   } else if (lifetime == Qualifiers::OCL_None) {
6395     // Try to infer lifetime.
6396     if (!type->isObjCLifetimeType())
6397       return false;
6398 
6399     lifetime = type->getObjCARCImplicitLifetime();
6400     type = Context.getLifetimeQualifiedType(type, lifetime);
6401     decl->setType(type);
6402   }
6403 
6404   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6405     // Thread-local variables cannot have lifetime.
6406     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6407         var->getTLSKind()) {
6408       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6409         << var->getType();
6410       return true;
6411     }
6412   }
6413 
6414   return false;
6415 }
6416 
6417 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6418   if (Decl->getType().hasAddressSpace())
6419     return;
6420   if (Decl->getType()->isDependentType())
6421     return;
6422   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6423     QualType Type = Var->getType();
6424     if (Type->isSamplerT() || Type->isVoidType())
6425       return;
6426     LangAS ImplAS = LangAS::opencl_private;
6427     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6428         Var->hasGlobalStorage())
6429       ImplAS = LangAS::opencl_global;
6430     // If the original type from a decayed type is an array type and that array
6431     // type has no address space yet, deduce it now.
6432     if (auto DT = dyn_cast<DecayedType>(Type)) {
6433       auto OrigTy = DT->getOriginalType();
6434       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6435         // Add the address space to the original array type and then propagate
6436         // that to the element type through `getAsArrayType`.
6437         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6438         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6439         // Re-generate the decayed type.
6440         Type = Context.getDecayedType(OrigTy);
6441       }
6442     }
6443     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6444     // Apply any qualifiers (including address space) from the array type to
6445     // the element type. This implements C99 6.7.3p8: "If the specification of
6446     // an array type includes any type qualifiers, the element type is so
6447     // qualified, not the array type."
6448     if (Type->isArrayType())
6449       Type = QualType(Context.getAsArrayType(Type), 0);
6450     Decl->setType(Type);
6451   }
6452 }
6453 
6454 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6455   // Ensure that an auto decl is deduced otherwise the checks below might cache
6456   // the wrong linkage.
6457   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6458 
6459   // 'weak' only applies to declarations with external linkage.
6460   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6461     if (!ND.isExternallyVisible()) {
6462       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6463       ND.dropAttr<WeakAttr>();
6464     }
6465   }
6466   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6467     if (ND.isExternallyVisible()) {
6468       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6469       ND.dropAttr<WeakRefAttr>();
6470       ND.dropAttr<AliasAttr>();
6471     }
6472   }
6473 
6474   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6475     if (VD->hasInit()) {
6476       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6477         assert(VD->isThisDeclarationADefinition() &&
6478                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6479         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6480         VD->dropAttr<AliasAttr>();
6481       }
6482     }
6483   }
6484 
6485   // 'selectany' only applies to externally visible variable declarations.
6486   // It does not apply to functions.
6487   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6488     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6489       S.Diag(Attr->getLocation(),
6490              diag::err_attribute_selectany_non_extern_data);
6491       ND.dropAttr<SelectAnyAttr>();
6492     }
6493   }
6494 
6495   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6496     auto *VD = dyn_cast<VarDecl>(&ND);
6497     bool IsAnonymousNS = false;
6498     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6499     if (VD) {
6500       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6501       while (NS && !IsAnonymousNS) {
6502         IsAnonymousNS = NS->isAnonymousNamespace();
6503         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6504       }
6505     }
6506     // dll attributes require external linkage. Static locals may have external
6507     // linkage but still cannot be explicitly imported or exported.
6508     // In Microsoft mode, a variable defined in anonymous namespace must have
6509     // external linkage in order to be exported.
6510     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6511     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6512         (!AnonNSInMicrosoftMode &&
6513          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6514       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6515         << &ND << Attr;
6516       ND.setInvalidDecl();
6517     }
6518   }
6519 
6520   // Check the attributes on the function type, if any.
6521   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6522     // Don't declare this variable in the second operand of the for-statement;
6523     // GCC miscompiles that by ending its lifetime before evaluating the
6524     // third operand. See gcc.gnu.org/PR86769.
6525     AttributedTypeLoc ATL;
6526     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6527          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6528          TL = ATL.getModifiedLoc()) {
6529       // The [[lifetimebound]] attribute can be applied to the implicit object
6530       // parameter of a non-static member function (other than a ctor or dtor)
6531       // by applying it to the function type.
6532       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6533         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6534         if (!MD || MD->isStatic()) {
6535           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6536               << !MD << A->getRange();
6537         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6538           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6539               << isa<CXXDestructorDecl>(MD) << A->getRange();
6540         }
6541       }
6542     }
6543   }
6544 }
6545 
6546 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6547                                            NamedDecl *NewDecl,
6548                                            bool IsSpecialization,
6549                                            bool IsDefinition) {
6550   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6551     return;
6552 
6553   bool IsTemplate = false;
6554   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6555     OldDecl = OldTD->getTemplatedDecl();
6556     IsTemplate = true;
6557     if (!IsSpecialization)
6558       IsDefinition = false;
6559   }
6560   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6561     NewDecl = NewTD->getTemplatedDecl();
6562     IsTemplate = true;
6563   }
6564 
6565   if (!OldDecl || !NewDecl)
6566     return;
6567 
6568   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6569   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6570   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6571   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6572 
6573   // dllimport and dllexport are inheritable attributes so we have to exclude
6574   // inherited attribute instances.
6575   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6576                     (NewExportAttr && !NewExportAttr->isInherited());
6577 
6578   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6579   // the only exception being explicit specializations.
6580   // Implicitly generated declarations are also excluded for now because there
6581   // is no other way to switch these to use dllimport or dllexport.
6582   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6583 
6584   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6585     // Allow with a warning for free functions and global variables.
6586     bool JustWarn = false;
6587     if (!OldDecl->isCXXClassMember()) {
6588       auto *VD = dyn_cast<VarDecl>(OldDecl);
6589       if (VD && !VD->getDescribedVarTemplate())
6590         JustWarn = true;
6591       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6592       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6593         JustWarn = true;
6594     }
6595 
6596     // We cannot change a declaration that's been used because IR has already
6597     // been emitted. Dllimported functions will still work though (modulo
6598     // address equality) as they can use the thunk.
6599     if (OldDecl->isUsed())
6600       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6601         JustWarn = false;
6602 
6603     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6604                                : diag::err_attribute_dll_redeclaration;
6605     S.Diag(NewDecl->getLocation(), DiagID)
6606         << NewDecl
6607         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6608     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6609     if (!JustWarn) {
6610       NewDecl->setInvalidDecl();
6611       return;
6612     }
6613   }
6614 
6615   // A redeclaration is not allowed to drop a dllimport attribute, the only
6616   // exceptions being inline function definitions (except for function
6617   // templates), local extern declarations, qualified friend declarations or
6618   // special MSVC extension: in the last case, the declaration is treated as if
6619   // it were marked dllexport.
6620   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6621   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6622   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6623     // Ignore static data because out-of-line definitions are diagnosed
6624     // separately.
6625     IsStaticDataMember = VD->isStaticDataMember();
6626     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6627                    VarDecl::DeclarationOnly;
6628   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6629     IsInline = FD->isInlined();
6630     IsQualifiedFriend = FD->getQualifier() &&
6631                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6632   }
6633 
6634   if (OldImportAttr && !HasNewAttr &&
6635       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6636       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6637     if (IsMicrosoftABI && IsDefinition) {
6638       S.Diag(NewDecl->getLocation(),
6639              diag::warn_redeclaration_without_import_attribute)
6640           << NewDecl;
6641       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6642       NewDecl->dropAttr<DLLImportAttr>();
6643       NewDecl->addAttr(
6644           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6645     } else {
6646       S.Diag(NewDecl->getLocation(),
6647              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6648           << NewDecl << OldImportAttr;
6649       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6650       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6651       OldDecl->dropAttr<DLLImportAttr>();
6652       NewDecl->dropAttr<DLLImportAttr>();
6653     }
6654   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6655     // In MinGW, seeing a function declared inline drops the dllimport
6656     // attribute.
6657     OldDecl->dropAttr<DLLImportAttr>();
6658     NewDecl->dropAttr<DLLImportAttr>();
6659     S.Diag(NewDecl->getLocation(),
6660            diag::warn_dllimport_dropped_from_inline_function)
6661         << NewDecl << OldImportAttr;
6662   }
6663 
6664   // A specialization of a class template member function is processed here
6665   // since it's a redeclaration. If the parent class is dllexport, the
6666   // specialization inherits that attribute. This doesn't happen automatically
6667   // since the parent class isn't instantiated until later.
6668   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6669     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6670         !NewImportAttr && !NewExportAttr) {
6671       if (const DLLExportAttr *ParentExportAttr =
6672               MD->getParent()->getAttr<DLLExportAttr>()) {
6673         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6674         NewAttr->setInherited(true);
6675         NewDecl->addAttr(NewAttr);
6676       }
6677     }
6678   }
6679 }
6680 
6681 /// Given that we are within the definition of the given function,
6682 /// will that definition behave like C99's 'inline', where the
6683 /// definition is discarded except for optimization purposes?
6684 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6685   // Try to avoid calling GetGVALinkageForFunction.
6686 
6687   // All cases of this require the 'inline' keyword.
6688   if (!FD->isInlined()) return false;
6689 
6690   // This is only possible in C++ with the gnu_inline attribute.
6691   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6692     return false;
6693 
6694   // Okay, go ahead and call the relatively-more-expensive function.
6695   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6696 }
6697 
6698 /// Determine whether a variable is extern "C" prior to attaching
6699 /// an initializer. We can't just call isExternC() here, because that
6700 /// will also compute and cache whether the declaration is externally
6701 /// visible, which might change when we attach the initializer.
6702 ///
6703 /// This can only be used if the declaration is known to not be a
6704 /// redeclaration of an internal linkage declaration.
6705 ///
6706 /// For instance:
6707 ///
6708 ///   auto x = []{};
6709 ///
6710 /// Attaching the initializer here makes this declaration not externally
6711 /// visible, because its type has internal linkage.
6712 ///
6713 /// FIXME: This is a hack.
6714 template<typename T>
6715 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6716   if (S.getLangOpts().CPlusPlus) {
6717     // In C++, the overloadable attribute negates the effects of extern "C".
6718     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6719       return false;
6720 
6721     // So do CUDA's host/device attributes.
6722     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6723                                  D->template hasAttr<CUDAHostAttr>()))
6724       return false;
6725   }
6726   return D->isExternC();
6727 }
6728 
6729 static bool shouldConsiderLinkage(const VarDecl *VD) {
6730   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6731   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6732       isa<OMPDeclareMapperDecl>(DC))
6733     return VD->hasExternalStorage();
6734   if (DC->isFileContext())
6735     return true;
6736   if (DC->isRecord())
6737     return false;
6738   if (isa<RequiresExprBodyDecl>(DC))
6739     return false;
6740   llvm_unreachable("Unexpected context");
6741 }
6742 
6743 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6744   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6745   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6746       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6747     return true;
6748   if (DC->isRecord())
6749     return false;
6750   llvm_unreachable("Unexpected context");
6751 }
6752 
6753 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6754                           ParsedAttr::Kind Kind) {
6755   // Check decl attributes on the DeclSpec.
6756   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6757     return true;
6758 
6759   // Walk the declarator structure, checking decl attributes that were in a type
6760   // position to the decl itself.
6761   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6762     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6763       return true;
6764   }
6765 
6766   // Finally, check attributes on the decl itself.
6767   return PD.getAttributes().hasAttribute(Kind);
6768 }
6769 
6770 /// Adjust the \c DeclContext for a function or variable that might be a
6771 /// function-local external declaration.
6772 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6773   if (!DC->isFunctionOrMethod())
6774     return false;
6775 
6776   // If this is a local extern function or variable declared within a function
6777   // template, don't add it into the enclosing namespace scope until it is
6778   // instantiated; it might have a dependent type right now.
6779   if (DC->isDependentContext())
6780     return true;
6781 
6782   // C++11 [basic.link]p7:
6783   //   When a block scope declaration of an entity with linkage is not found to
6784   //   refer to some other declaration, then that entity is a member of the
6785   //   innermost enclosing namespace.
6786   //
6787   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6788   // semantically-enclosing namespace, not a lexically-enclosing one.
6789   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6790     DC = DC->getParent();
6791   return true;
6792 }
6793 
6794 /// Returns true if given declaration has external C language linkage.
6795 static bool isDeclExternC(const Decl *D) {
6796   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6797     return FD->isExternC();
6798   if (const auto *VD = dyn_cast<VarDecl>(D))
6799     return VD->isExternC();
6800 
6801   llvm_unreachable("Unknown type of decl!");
6802 }
6803 
6804 /// Returns true if there hasn't been any invalid type diagnosed.
6805 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6806   DeclContext *DC = NewVD->getDeclContext();
6807   QualType R = NewVD->getType();
6808 
6809   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6810   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6811   // argument.
6812   if (R->isImageType() || R->isPipeType()) {
6813     Se.Diag(NewVD->getLocation(),
6814             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6815         << R;
6816     NewVD->setInvalidDecl();
6817     return false;
6818   }
6819 
6820   // OpenCL v1.2 s6.9.r:
6821   // The event type cannot be used to declare a program scope variable.
6822   // OpenCL v2.0 s6.9.q:
6823   // The clk_event_t and reserve_id_t types cannot be declared in program
6824   // scope.
6825   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6826     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6827       Se.Diag(NewVD->getLocation(),
6828               diag::err_invalid_type_for_program_scope_var)
6829           << R;
6830       NewVD->setInvalidDecl();
6831       return false;
6832     }
6833   }
6834 
6835   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6836   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6837                                                Se.getLangOpts())) {
6838     QualType NR = R.getCanonicalType();
6839     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6840            NR->isReferenceType()) {
6841       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6842           NR->isFunctionReferenceType()) {
6843         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6844             << NR->isReferenceType();
6845         NewVD->setInvalidDecl();
6846         return false;
6847       }
6848       NR = NR->getPointeeType();
6849     }
6850   }
6851 
6852   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6853                                                Se.getLangOpts())) {
6854     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6855     // half array type (unless the cl_khr_fp16 extension is enabled).
6856     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6857       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6858       NewVD->setInvalidDecl();
6859       return false;
6860     }
6861   }
6862 
6863   // OpenCL v1.2 s6.9.r:
6864   // The event type cannot be used with the __local, __constant and __global
6865   // address space qualifiers.
6866   if (R->isEventT()) {
6867     if (R.getAddressSpace() != LangAS::opencl_private) {
6868       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6869       NewVD->setInvalidDecl();
6870       return false;
6871     }
6872   }
6873 
6874   if (R->isSamplerT()) {
6875     // OpenCL v1.2 s6.9.b p4:
6876     // The sampler type cannot be used with the __local and __global address
6877     // space qualifiers.
6878     if (R.getAddressSpace() == LangAS::opencl_local ||
6879         R.getAddressSpace() == LangAS::opencl_global) {
6880       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6881       NewVD->setInvalidDecl();
6882     }
6883 
6884     // OpenCL v1.2 s6.12.14.1:
6885     // A global sampler must be declared with either the constant address
6886     // space qualifier or with the const qualifier.
6887     if (DC->isTranslationUnit() &&
6888         !(R.getAddressSpace() == LangAS::opencl_constant ||
6889           R.isConstQualified())) {
6890       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6891       NewVD->setInvalidDecl();
6892     }
6893     if (NewVD->isInvalidDecl())
6894       return false;
6895   }
6896 
6897   return true;
6898 }
6899 
6900 template <typename AttrTy>
6901 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6902   const TypedefNameDecl *TND = TT->getDecl();
6903   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6904     AttrTy *Clone = Attribute->clone(S.Context);
6905     Clone->setInherited(true);
6906     D->addAttr(Clone);
6907   }
6908 }
6909 
6910 NamedDecl *Sema::ActOnVariableDeclarator(
6911     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6912     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6913     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6914   QualType R = TInfo->getType();
6915   DeclarationName Name = GetNameForDeclarator(D).getName();
6916 
6917   IdentifierInfo *II = Name.getAsIdentifierInfo();
6918 
6919   if (D.isDecompositionDeclarator()) {
6920     // Take the name of the first declarator as our name for diagnostic
6921     // purposes.
6922     auto &Decomp = D.getDecompositionDeclarator();
6923     if (!Decomp.bindings().empty()) {
6924       II = Decomp.bindings()[0].Name;
6925       Name = II;
6926     }
6927   } else if (!II) {
6928     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6929     return nullptr;
6930   }
6931 
6932 
6933   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6934   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6935 
6936   // dllimport globals without explicit storage class are treated as extern. We
6937   // have to change the storage class this early to get the right DeclContext.
6938   if (SC == SC_None && !DC->isRecord() &&
6939       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6940       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6941     SC = SC_Extern;
6942 
6943   DeclContext *OriginalDC = DC;
6944   bool IsLocalExternDecl = SC == SC_Extern &&
6945                            adjustContextForLocalExternDecl(DC);
6946 
6947   if (SCSpec == DeclSpec::SCS_mutable) {
6948     // mutable can only appear on non-static class members, so it's always
6949     // an error here
6950     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6951     D.setInvalidType();
6952     SC = SC_None;
6953   }
6954 
6955   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6956       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6957                               D.getDeclSpec().getStorageClassSpecLoc())) {
6958     // In C++11, the 'register' storage class specifier is deprecated.
6959     // Suppress the warning in system macros, it's used in macros in some
6960     // popular C system headers, such as in glibc's htonl() macro.
6961     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6962          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6963                                    : diag::warn_deprecated_register)
6964       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6965   }
6966 
6967   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6968 
6969   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6970     // C99 6.9p2: The storage-class specifiers auto and register shall not
6971     // appear in the declaration specifiers in an external declaration.
6972     // Global Register+Asm is a GNU extension we support.
6973     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6974       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6975       D.setInvalidType();
6976     }
6977   }
6978 
6979   // If this variable has a VLA type and an initializer, try to
6980   // fold to a constant-sized type. This is otherwise invalid.
6981   if (D.hasInitializer() && R->isVariableArrayType())
6982     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6983                                     /*DiagID=*/0);
6984 
6985   bool IsMemberSpecialization = false;
6986   bool IsVariableTemplateSpecialization = false;
6987   bool IsPartialSpecialization = false;
6988   bool IsVariableTemplate = false;
6989   VarDecl *NewVD = nullptr;
6990   VarTemplateDecl *NewTemplate = nullptr;
6991   TemplateParameterList *TemplateParams = nullptr;
6992   if (!getLangOpts().CPlusPlus) {
6993     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6994                             II, R, TInfo, SC);
6995 
6996     if (R->getContainedDeducedType())
6997       ParsingInitForAutoVars.insert(NewVD);
6998 
6999     if (D.isInvalidType())
7000       NewVD->setInvalidDecl();
7001 
7002     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7003         NewVD->hasLocalStorage())
7004       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7005                             NTCUC_AutoVar, NTCUK_Destruct);
7006   } else {
7007     bool Invalid = false;
7008 
7009     if (DC->isRecord() && !CurContext->isRecord()) {
7010       // This is an out-of-line definition of a static data member.
7011       switch (SC) {
7012       case SC_None:
7013         break;
7014       case SC_Static:
7015         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7016              diag::err_static_out_of_line)
7017           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7018         break;
7019       case SC_Auto:
7020       case SC_Register:
7021       case SC_Extern:
7022         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7023         // to names of variables declared in a block or to function parameters.
7024         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7025         // of class members
7026 
7027         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7028              diag::err_storage_class_for_static_member)
7029           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7030         break;
7031       case SC_PrivateExtern:
7032         llvm_unreachable("C storage class in c++!");
7033       }
7034     }
7035 
7036     if (SC == SC_Static && CurContext->isRecord()) {
7037       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7038         // Walk up the enclosing DeclContexts to check for any that are
7039         // incompatible with static data members.
7040         const DeclContext *FunctionOrMethod = nullptr;
7041         const CXXRecordDecl *AnonStruct = nullptr;
7042         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7043           if (Ctxt->isFunctionOrMethod()) {
7044             FunctionOrMethod = Ctxt;
7045             break;
7046           }
7047           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7048           if (ParentDecl && !ParentDecl->getDeclName()) {
7049             AnonStruct = ParentDecl;
7050             break;
7051           }
7052         }
7053         if (FunctionOrMethod) {
7054           // C++ [class.static.data]p5: A local class shall not have static data
7055           // members.
7056           Diag(D.getIdentifierLoc(),
7057                diag::err_static_data_member_not_allowed_in_local_class)
7058             << Name << RD->getDeclName() << RD->getTagKind();
7059         } else if (AnonStruct) {
7060           // C++ [class.static.data]p4: Unnamed classes and classes contained
7061           // directly or indirectly within unnamed classes shall not contain
7062           // static data members.
7063           Diag(D.getIdentifierLoc(),
7064                diag::err_static_data_member_not_allowed_in_anon_struct)
7065             << Name << AnonStruct->getTagKind();
7066           Invalid = true;
7067         } else if (RD->isUnion()) {
7068           // C++98 [class.union]p1: If a union contains a static data member,
7069           // the program is ill-formed. C++11 drops this restriction.
7070           Diag(D.getIdentifierLoc(),
7071                getLangOpts().CPlusPlus11
7072                  ? diag::warn_cxx98_compat_static_data_member_in_union
7073                  : diag::ext_static_data_member_in_union) << Name;
7074         }
7075       }
7076     }
7077 
7078     // Match up the template parameter lists with the scope specifier, then
7079     // determine whether we have a template or a template specialization.
7080     bool InvalidScope = false;
7081     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7082         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7083         D.getCXXScopeSpec(),
7084         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7085             ? D.getName().TemplateId
7086             : nullptr,
7087         TemplateParamLists,
7088         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7089     Invalid |= InvalidScope;
7090 
7091     if (TemplateParams) {
7092       if (!TemplateParams->size() &&
7093           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7094         // There is an extraneous 'template<>' for this variable. Complain
7095         // about it, but allow the declaration of the variable.
7096         Diag(TemplateParams->getTemplateLoc(),
7097              diag::err_template_variable_noparams)
7098           << II
7099           << SourceRange(TemplateParams->getTemplateLoc(),
7100                          TemplateParams->getRAngleLoc());
7101         TemplateParams = nullptr;
7102       } else {
7103         // Check that we can declare a template here.
7104         if (CheckTemplateDeclScope(S, TemplateParams))
7105           return nullptr;
7106 
7107         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7108           // This is an explicit specialization or a partial specialization.
7109           IsVariableTemplateSpecialization = true;
7110           IsPartialSpecialization = TemplateParams->size() > 0;
7111         } else { // if (TemplateParams->size() > 0)
7112           // This is a template declaration.
7113           IsVariableTemplate = true;
7114 
7115           // Only C++1y supports variable templates (N3651).
7116           Diag(D.getIdentifierLoc(),
7117                getLangOpts().CPlusPlus14
7118                    ? diag::warn_cxx11_compat_variable_template
7119                    : diag::ext_variable_template);
7120         }
7121       }
7122     } else {
7123       // Check that we can declare a member specialization here.
7124       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7125           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7126         return nullptr;
7127       assert((Invalid ||
7128               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7129              "should have a 'template<>' for this decl");
7130     }
7131 
7132     if (IsVariableTemplateSpecialization) {
7133       SourceLocation TemplateKWLoc =
7134           TemplateParamLists.size() > 0
7135               ? TemplateParamLists[0]->getTemplateLoc()
7136               : SourceLocation();
7137       DeclResult Res = ActOnVarTemplateSpecialization(
7138           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7139           IsPartialSpecialization);
7140       if (Res.isInvalid())
7141         return nullptr;
7142       NewVD = cast<VarDecl>(Res.get());
7143       AddToScope = false;
7144     } else if (D.isDecompositionDeclarator()) {
7145       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7146                                         D.getIdentifierLoc(), R, TInfo, SC,
7147                                         Bindings);
7148     } else
7149       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7150                               D.getIdentifierLoc(), II, R, TInfo, SC);
7151 
7152     // If this is supposed to be a variable template, create it as such.
7153     if (IsVariableTemplate) {
7154       NewTemplate =
7155           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7156                                   TemplateParams, NewVD);
7157       NewVD->setDescribedVarTemplate(NewTemplate);
7158     }
7159 
7160     // If this decl has an auto type in need of deduction, make a note of the
7161     // Decl so we can diagnose uses of it in its own initializer.
7162     if (R->getContainedDeducedType())
7163       ParsingInitForAutoVars.insert(NewVD);
7164 
7165     if (D.isInvalidType() || Invalid) {
7166       NewVD->setInvalidDecl();
7167       if (NewTemplate)
7168         NewTemplate->setInvalidDecl();
7169     }
7170 
7171     SetNestedNameSpecifier(*this, NewVD, D);
7172 
7173     // If we have any template parameter lists that don't directly belong to
7174     // the variable (matching the scope specifier), store them.
7175     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7176     if (TemplateParamLists.size() > VDTemplateParamLists)
7177       NewVD->setTemplateParameterListsInfo(
7178           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7179   }
7180 
7181   if (D.getDeclSpec().isInlineSpecified()) {
7182     if (!getLangOpts().CPlusPlus) {
7183       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7184           << 0;
7185     } else if (CurContext->isFunctionOrMethod()) {
7186       // 'inline' is not allowed on block scope variable declaration.
7187       Diag(D.getDeclSpec().getInlineSpecLoc(),
7188            diag::err_inline_declaration_block_scope) << Name
7189         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7190     } else {
7191       Diag(D.getDeclSpec().getInlineSpecLoc(),
7192            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7193                                      : diag::ext_inline_variable);
7194       NewVD->setInlineSpecified();
7195     }
7196   }
7197 
7198   // Set the lexical context. If the declarator has a C++ scope specifier, the
7199   // lexical context will be different from the semantic context.
7200   NewVD->setLexicalDeclContext(CurContext);
7201   if (NewTemplate)
7202     NewTemplate->setLexicalDeclContext(CurContext);
7203 
7204   if (IsLocalExternDecl) {
7205     if (D.isDecompositionDeclarator())
7206       for (auto *B : Bindings)
7207         B->setLocalExternDecl();
7208     else
7209       NewVD->setLocalExternDecl();
7210   }
7211 
7212   bool EmitTLSUnsupportedError = false;
7213   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7214     // C++11 [dcl.stc]p4:
7215     //   When thread_local is applied to a variable of block scope the
7216     //   storage-class-specifier static is implied if it does not appear
7217     //   explicitly.
7218     // Core issue: 'static' is not implied if the variable is declared
7219     //   'extern'.
7220     if (NewVD->hasLocalStorage() &&
7221         (SCSpec != DeclSpec::SCS_unspecified ||
7222          TSCS != DeclSpec::TSCS_thread_local ||
7223          !DC->isFunctionOrMethod()))
7224       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7225            diag::err_thread_non_global)
7226         << DeclSpec::getSpecifierName(TSCS);
7227     else if (!Context.getTargetInfo().isTLSSupported()) {
7228       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7229           getLangOpts().SYCLIsDevice) {
7230         // Postpone error emission until we've collected attributes required to
7231         // figure out whether it's a host or device variable and whether the
7232         // error should be ignored.
7233         EmitTLSUnsupportedError = true;
7234         // We still need to mark the variable as TLS so it shows up in AST with
7235         // proper storage class for other tools to use even if we're not going
7236         // to emit any code for it.
7237         NewVD->setTSCSpec(TSCS);
7238       } else
7239         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7240              diag::err_thread_unsupported);
7241     } else
7242       NewVD->setTSCSpec(TSCS);
7243   }
7244 
7245   switch (D.getDeclSpec().getConstexprSpecifier()) {
7246   case ConstexprSpecKind::Unspecified:
7247     break;
7248 
7249   case ConstexprSpecKind::Consteval:
7250     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7251          diag::err_constexpr_wrong_decl_kind)
7252         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7253     LLVM_FALLTHROUGH;
7254 
7255   case ConstexprSpecKind::Constexpr:
7256     NewVD->setConstexpr(true);
7257     // C++1z [dcl.spec.constexpr]p1:
7258     //   A static data member declared with the constexpr specifier is
7259     //   implicitly an inline variable.
7260     if (NewVD->isStaticDataMember() &&
7261         (getLangOpts().CPlusPlus17 ||
7262          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7263       NewVD->setImplicitlyInline();
7264     break;
7265 
7266   case ConstexprSpecKind::Constinit:
7267     if (!NewVD->hasGlobalStorage())
7268       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7269            diag::err_constinit_local_variable);
7270     else
7271       NewVD->addAttr(ConstInitAttr::Create(
7272           Context, D.getDeclSpec().getConstexprSpecLoc(),
7273           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7274     break;
7275   }
7276 
7277   // C99 6.7.4p3
7278   //   An inline definition of a function with external linkage shall
7279   //   not contain a definition of a modifiable object with static or
7280   //   thread storage duration...
7281   // We only apply this when the function is required to be defined
7282   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7283   // that a local variable with thread storage duration still has to
7284   // be marked 'static'.  Also note that it's possible to get these
7285   // semantics in C++ using __attribute__((gnu_inline)).
7286   if (SC == SC_Static && S->getFnParent() != nullptr &&
7287       !NewVD->getType().isConstQualified()) {
7288     FunctionDecl *CurFD = getCurFunctionDecl();
7289     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7290       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7291            diag::warn_static_local_in_extern_inline);
7292       MaybeSuggestAddingStaticToDecl(CurFD);
7293     }
7294   }
7295 
7296   if (D.getDeclSpec().isModulePrivateSpecified()) {
7297     if (IsVariableTemplateSpecialization)
7298       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7299           << (IsPartialSpecialization ? 1 : 0)
7300           << FixItHint::CreateRemoval(
7301                  D.getDeclSpec().getModulePrivateSpecLoc());
7302     else if (IsMemberSpecialization)
7303       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7304         << 2
7305         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7306     else if (NewVD->hasLocalStorage())
7307       Diag(NewVD->getLocation(), diag::err_module_private_local)
7308           << 0 << NewVD
7309           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7310           << FixItHint::CreateRemoval(
7311                  D.getDeclSpec().getModulePrivateSpecLoc());
7312     else {
7313       NewVD->setModulePrivate();
7314       if (NewTemplate)
7315         NewTemplate->setModulePrivate();
7316       for (auto *B : Bindings)
7317         B->setModulePrivate();
7318     }
7319   }
7320 
7321   if (getLangOpts().OpenCL) {
7322     deduceOpenCLAddressSpace(NewVD);
7323 
7324     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7325     if (TSC != TSCS_unspecified) {
7326       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7327       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7328            diag::err_opencl_unknown_type_specifier)
7329           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7330           << DeclSpec::getSpecifierName(TSC) << 1;
7331       NewVD->setInvalidDecl();
7332     }
7333   }
7334 
7335   // Handle attributes prior to checking for duplicates in MergeVarDecl
7336   ProcessDeclAttributes(S, NewVD, D);
7337 
7338   // FIXME: This is probably the wrong location to be doing this and we should
7339   // probably be doing this for more attributes (especially for function
7340   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7341   // the code to copy attributes would be generated by TableGen.
7342   if (R->isFunctionPointerType())
7343     if (const auto *TT = R->getAs<TypedefType>())
7344       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7345 
7346   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7347       getLangOpts().SYCLIsDevice) {
7348     if (EmitTLSUnsupportedError &&
7349         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7350          (getLangOpts().OpenMPIsDevice &&
7351           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7352       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7353            diag::err_thread_unsupported);
7354 
7355     if (EmitTLSUnsupportedError &&
7356         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7357       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7358     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7359     // storage [duration]."
7360     if (SC == SC_None && S->getFnParent() != nullptr &&
7361         (NewVD->hasAttr<CUDASharedAttr>() ||
7362          NewVD->hasAttr<CUDAConstantAttr>())) {
7363       NewVD->setStorageClass(SC_Static);
7364     }
7365   }
7366 
7367   // Ensure that dllimport globals without explicit storage class are treated as
7368   // extern. The storage class is set above using parsed attributes. Now we can
7369   // check the VarDecl itself.
7370   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7371          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7372          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7373 
7374   // In auto-retain/release, infer strong retension for variables of
7375   // retainable type.
7376   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7377     NewVD->setInvalidDecl();
7378 
7379   // Handle GNU asm-label extension (encoded as an attribute).
7380   if (Expr *E = (Expr*)D.getAsmLabel()) {
7381     // The parser guarantees this is a string.
7382     StringLiteral *SE = cast<StringLiteral>(E);
7383     StringRef Label = SE->getString();
7384     if (S->getFnParent() != nullptr) {
7385       switch (SC) {
7386       case SC_None:
7387       case SC_Auto:
7388         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7389         break;
7390       case SC_Register:
7391         // Local Named register
7392         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7393             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7394           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7395         break;
7396       case SC_Static:
7397       case SC_Extern:
7398       case SC_PrivateExtern:
7399         break;
7400       }
7401     } else if (SC == SC_Register) {
7402       // Global Named register
7403       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7404         const auto &TI = Context.getTargetInfo();
7405         bool HasSizeMismatch;
7406 
7407         if (!TI.isValidGCCRegisterName(Label))
7408           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7409         else if (!TI.validateGlobalRegisterVariable(Label,
7410                                                     Context.getTypeSize(R),
7411                                                     HasSizeMismatch))
7412           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7413         else if (HasSizeMismatch)
7414           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7415       }
7416 
7417       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7418         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7419         NewVD->setInvalidDecl(true);
7420       }
7421     }
7422 
7423     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7424                                         /*IsLiteralLabel=*/true,
7425                                         SE->getStrTokenLoc(0)));
7426   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7427     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7428       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7429     if (I != ExtnameUndeclaredIdentifiers.end()) {
7430       if (isDeclExternC(NewVD)) {
7431         NewVD->addAttr(I->second);
7432         ExtnameUndeclaredIdentifiers.erase(I);
7433       } else
7434         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7435             << /*Variable*/1 << NewVD;
7436     }
7437   }
7438 
7439   // Find the shadowed declaration before filtering for scope.
7440   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7441                                 ? getShadowedDeclaration(NewVD, Previous)
7442                                 : nullptr;
7443 
7444   // Don't consider existing declarations that are in a different
7445   // scope and are out-of-semantic-context declarations (if the new
7446   // declaration has linkage).
7447   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7448                        D.getCXXScopeSpec().isNotEmpty() ||
7449                        IsMemberSpecialization ||
7450                        IsVariableTemplateSpecialization);
7451 
7452   // Check whether the previous declaration is in the same block scope. This
7453   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7454   if (getLangOpts().CPlusPlus &&
7455       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7456     NewVD->setPreviousDeclInSameBlockScope(
7457         Previous.isSingleResult() && !Previous.isShadowed() &&
7458         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7459 
7460   if (!getLangOpts().CPlusPlus) {
7461     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7462   } else {
7463     // If this is an explicit specialization of a static data member, check it.
7464     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7465         CheckMemberSpecialization(NewVD, Previous))
7466       NewVD->setInvalidDecl();
7467 
7468     // Merge the decl with the existing one if appropriate.
7469     if (!Previous.empty()) {
7470       if (Previous.isSingleResult() &&
7471           isa<FieldDecl>(Previous.getFoundDecl()) &&
7472           D.getCXXScopeSpec().isSet()) {
7473         // The user tried to define a non-static data member
7474         // out-of-line (C++ [dcl.meaning]p1).
7475         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7476           << D.getCXXScopeSpec().getRange();
7477         Previous.clear();
7478         NewVD->setInvalidDecl();
7479       }
7480     } else if (D.getCXXScopeSpec().isSet()) {
7481       // No previous declaration in the qualifying scope.
7482       Diag(D.getIdentifierLoc(), diag::err_no_member)
7483         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7484         << D.getCXXScopeSpec().getRange();
7485       NewVD->setInvalidDecl();
7486     }
7487 
7488     if (!IsVariableTemplateSpecialization)
7489       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7490 
7491     if (NewTemplate) {
7492       VarTemplateDecl *PrevVarTemplate =
7493           NewVD->getPreviousDecl()
7494               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7495               : nullptr;
7496 
7497       // Check the template parameter list of this declaration, possibly
7498       // merging in the template parameter list from the previous variable
7499       // template declaration.
7500       if (CheckTemplateParameterList(
7501               TemplateParams,
7502               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7503                               : nullptr,
7504               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7505                DC->isDependentContext())
7506                   ? TPC_ClassTemplateMember
7507                   : TPC_VarTemplate))
7508         NewVD->setInvalidDecl();
7509 
7510       // If we are providing an explicit specialization of a static variable
7511       // template, make a note of that.
7512       if (PrevVarTemplate &&
7513           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7514         PrevVarTemplate->setMemberSpecialization();
7515     }
7516   }
7517 
7518   // Diagnose shadowed variables iff this isn't a redeclaration.
7519   if (ShadowedDecl && !D.isRedeclaration())
7520     CheckShadow(NewVD, ShadowedDecl, Previous);
7521 
7522   ProcessPragmaWeak(S, NewVD);
7523 
7524   // If this is the first declaration of an extern C variable, update
7525   // the map of such variables.
7526   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7527       isIncompleteDeclExternC(*this, NewVD))
7528     RegisterLocallyScopedExternCDecl(NewVD, S);
7529 
7530   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7531     MangleNumberingContext *MCtx;
7532     Decl *ManglingContextDecl;
7533     std::tie(MCtx, ManglingContextDecl) =
7534         getCurrentMangleNumberContext(NewVD->getDeclContext());
7535     if (MCtx) {
7536       Context.setManglingNumber(
7537           NewVD, MCtx->getManglingNumber(
7538                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7539       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7540     }
7541   }
7542 
7543   // Special handling of variable named 'main'.
7544   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7545       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7546       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7547 
7548     // C++ [basic.start.main]p3
7549     // A program that declares a variable main at global scope is ill-formed.
7550     if (getLangOpts().CPlusPlus)
7551       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7552 
7553     // In C, and external-linkage variable named main results in undefined
7554     // behavior.
7555     else if (NewVD->hasExternalFormalLinkage())
7556       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7557   }
7558 
7559   if (D.isRedeclaration() && !Previous.empty()) {
7560     NamedDecl *Prev = Previous.getRepresentativeDecl();
7561     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7562                                    D.isFunctionDefinition());
7563   }
7564 
7565   if (NewTemplate) {
7566     if (NewVD->isInvalidDecl())
7567       NewTemplate->setInvalidDecl();
7568     ActOnDocumentableDecl(NewTemplate);
7569     return NewTemplate;
7570   }
7571 
7572   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7573     CompleteMemberSpecialization(NewVD, Previous);
7574 
7575   return NewVD;
7576 }
7577 
7578 /// Enum describing the %select options in diag::warn_decl_shadow.
7579 enum ShadowedDeclKind {
7580   SDK_Local,
7581   SDK_Global,
7582   SDK_StaticMember,
7583   SDK_Field,
7584   SDK_Typedef,
7585   SDK_Using,
7586   SDK_StructuredBinding
7587 };
7588 
7589 /// Determine what kind of declaration we're shadowing.
7590 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7591                                                 const DeclContext *OldDC) {
7592   if (isa<TypeAliasDecl>(ShadowedDecl))
7593     return SDK_Using;
7594   else if (isa<TypedefDecl>(ShadowedDecl))
7595     return SDK_Typedef;
7596   else if (isa<BindingDecl>(ShadowedDecl))
7597     return SDK_StructuredBinding;
7598   else if (isa<RecordDecl>(OldDC))
7599     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7600 
7601   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7602 }
7603 
7604 /// Return the location of the capture if the given lambda captures the given
7605 /// variable \p VD, or an invalid source location otherwise.
7606 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7607                                          const VarDecl *VD) {
7608   for (const Capture &Capture : LSI->Captures) {
7609     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7610       return Capture.getLocation();
7611   }
7612   return SourceLocation();
7613 }
7614 
7615 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7616                                      const LookupResult &R) {
7617   // Only diagnose if we're shadowing an unambiguous field or variable.
7618   if (R.getResultKind() != LookupResult::Found)
7619     return false;
7620 
7621   // Return false if warning is ignored.
7622   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7623 }
7624 
7625 /// Return the declaration shadowed by the given variable \p D, or null
7626 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7627 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7628                                         const LookupResult &R) {
7629   if (!shouldWarnIfShadowedDecl(Diags, R))
7630     return nullptr;
7631 
7632   // Don't diagnose declarations at file scope.
7633   if (D->hasGlobalStorage())
7634     return nullptr;
7635 
7636   NamedDecl *ShadowedDecl = R.getFoundDecl();
7637   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7638                                                             : nullptr;
7639 }
7640 
7641 /// Return the declaration shadowed by the given typedef \p D, or null
7642 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7643 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7644                                         const LookupResult &R) {
7645   // Don't warn if typedef declaration is part of a class
7646   if (D->getDeclContext()->isRecord())
7647     return nullptr;
7648 
7649   if (!shouldWarnIfShadowedDecl(Diags, R))
7650     return nullptr;
7651 
7652   NamedDecl *ShadowedDecl = R.getFoundDecl();
7653   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7654 }
7655 
7656 /// Return the declaration shadowed by the given variable \p D, or null
7657 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7658 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7659                                         const LookupResult &R) {
7660   if (!shouldWarnIfShadowedDecl(Diags, R))
7661     return nullptr;
7662 
7663   NamedDecl *ShadowedDecl = R.getFoundDecl();
7664   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7665                                                             : nullptr;
7666 }
7667 
7668 /// Diagnose variable or built-in function shadowing.  Implements
7669 /// -Wshadow.
7670 ///
7671 /// This method is called whenever a VarDecl is added to a "useful"
7672 /// scope.
7673 ///
7674 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7675 /// \param R the lookup of the name
7676 ///
7677 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7678                        const LookupResult &R) {
7679   DeclContext *NewDC = D->getDeclContext();
7680 
7681   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7682     // Fields are not shadowed by variables in C++ static methods.
7683     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7684       if (MD->isStatic())
7685         return;
7686 
7687     // Fields shadowed by constructor parameters are a special case. Usually
7688     // the constructor initializes the field with the parameter.
7689     if (isa<CXXConstructorDecl>(NewDC))
7690       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7691         // Remember that this was shadowed so we can either warn about its
7692         // modification or its existence depending on warning settings.
7693         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7694         return;
7695       }
7696   }
7697 
7698   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7699     if (shadowedVar->isExternC()) {
7700       // For shadowing external vars, make sure that we point to the global
7701       // declaration, not a locally scoped extern declaration.
7702       for (auto I : shadowedVar->redecls())
7703         if (I->isFileVarDecl()) {
7704           ShadowedDecl = I;
7705           break;
7706         }
7707     }
7708 
7709   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7710 
7711   unsigned WarningDiag = diag::warn_decl_shadow;
7712   SourceLocation CaptureLoc;
7713   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7714       isa<CXXMethodDecl>(NewDC)) {
7715     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7716       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7717         if (RD->getLambdaCaptureDefault() == LCD_None) {
7718           // Try to avoid warnings for lambdas with an explicit capture list.
7719           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7720           // Warn only when the lambda captures the shadowed decl explicitly.
7721           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7722           if (CaptureLoc.isInvalid())
7723             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7724         } else {
7725           // Remember that this was shadowed so we can avoid the warning if the
7726           // shadowed decl isn't captured and the warning settings allow it.
7727           cast<LambdaScopeInfo>(getCurFunction())
7728               ->ShadowingDecls.push_back(
7729                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7730           return;
7731         }
7732       }
7733 
7734       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7735         // A variable can't shadow a local variable in an enclosing scope, if
7736         // they are separated by a non-capturing declaration context.
7737         for (DeclContext *ParentDC = NewDC;
7738              ParentDC && !ParentDC->Equals(OldDC);
7739              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7740           // Only block literals, captured statements, and lambda expressions
7741           // can capture; other scopes don't.
7742           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7743               !isLambdaCallOperator(ParentDC)) {
7744             return;
7745           }
7746         }
7747       }
7748     }
7749   }
7750 
7751   // Only warn about certain kinds of shadowing for class members.
7752   if (NewDC && NewDC->isRecord()) {
7753     // In particular, don't warn about shadowing non-class members.
7754     if (!OldDC->isRecord())
7755       return;
7756 
7757     // TODO: should we warn about static data members shadowing
7758     // static data members from base classes?
7759 
7760     // TODO: don't diagnose for inaccessible shadowed members.
7761     // This is hard to do perfectly because we might friend the
7762     // shadowing context, but that's just a false negative.
7763   }
7764 
7765 
7766   DeclarationName Name = R.getLookupName();
7767 
7768   // Emit warning and note.
7769   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7770     return;
7771   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7772   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7773   if (!CaptureLoc.isInvalid())
7774     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7775         << Name << /*explicitly*/ 1;
7776   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7777 }
7778 
7779 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7780 /// when these variables are captured by the lambda.
7781 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7782   for (const auto &Shadow : LSI->ShadowingDecls) {
7783     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7784     // Try to avoid the warning when the shadowed decl isn't captured.
7785     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7786     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7787     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7788                                        ? diag::warn_decl_shadow_uncaptured_local
7789                                        : diag::warn_decl_shadow)
7790         << Shadow.VD->getDeclName()
7791         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7792     if (!CaptureLoc.isInvalid())
7793       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7794           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7795     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7796   }
7797 }
7798 
7799 /// Check -Wshadow without the advantage of a previous lookup.
7800 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7801   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7802     return;
7803 
7804   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7805                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7806   LookupName(R, S);
7807   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7808     CheckShadow(D, ShadowedDecl, R);
7809 }
7810 
7811 /// Check if 'E', which is an expression that is about to be modified, refers
7812 /// to a constructor parameter that shadows a field.
7813 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7814   // Quickly ignore expressions that can't be shadowing ctor parameters.
7815   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7816     return;
7817   E = E->IgnoreParenImpCasts();
7818   auto *DRE = dyn_cast<DeclRefExpr>(E);
7819   if (!DRE)
7820     return;
7821   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7822   auto I = ShadowingDecls.find(D);
7823   if (I == ShadowingDecls.end())
7824     return;
7825   const NamedDecl *ShadowedDecl = I->second;
7826   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7827   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7828   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7829   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7830 
7831   // Avoid issuing multiple warnings about the same decl.
7832   ShadowingDecls.erase(I);
7833 }
7834 
7835 /// Check for conflict between this global or extern "C" declaration and
7836 /// previous global or extern "C" declarations. This is only used in C++.
7837 template<typename T>
7838 static bool checkGlobalOrExternCConflict(
7839     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7840   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7841   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7842 
7843   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7844     // The common case: this global doesn't conflict with any extern "C"
7845     // declaration.
7846     return false;
7847   }
7848 
7849   if (Prev) {
7850     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7851       // Both the old and new declarations have C language linkage. This is a
7852       // redeclaration.
7853       Previous.clear();
7854       Previous.addDecl(Prev);
7855       return true;
7856     }
7857 
7858     // This is a global, non-extern "C" declaration, and there is a previous
7859     // non-global extern "C" declaration. Diagnose if this is a variable
7860     // declaration.
7861     if (!isa<VarDecl>(ND))
7862       return false;
7863   } else {
7864     // The declaration is extern "C". Check for any declaration in the
7865     // translation unit which might conflict.
7866     if (IsGlobal) {
7867       // We have already performed the lookup into the translation unit.
7868       IsGlobal = false;
7869       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7870            I != E; ++I) {
7871         if (isa<VarDecl>(*I)) {
7872           Prev = *I;
7873           break;
7874         }
7875       }
7876     } else {
7877       DeclContext::lookup_result R =
7878           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7879       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7880            I != E; ++I) {
7881         if (isa<VarDecl>(*I)) {
7882           Prev = *I;
7883           break;
7884         }
7885         // FIXME: If we have any other entity with this name in global scope,
7886         // the declaration is ill-formed, but that is a defect: it breaks the
7887         // 'stat' hack, for instance. Only variables can have mangled name
7888         // clashes with extern "C" declarations, so only they deserve a
7889         // diagnostic.
7890       }
7891     }
7892 
7893     if (!Prev)
7894       return false;
7895   }
7896 
7897   // Use the first declaration's location to ensure we point at something which
7898   // is lexically inside an extern "C" linkage-spec.
7899   assert(Prev && "should have found a previous declaration to diagnose");
7900   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7901     Prev = FD->getFirstDecl();
7902   else
7903     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7904 
7905   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7906     << IsGlobal << ND;
7907   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7908     << IsGlobal;
7909   return false;
7910 }
7911 
7912 /// Apply special rules for handling extern "C" declarations. Returns \c true
7913 /// if we have found that this is a redeclaration of some prior entity.
7914 ///
7915 /// Per C++ [dcl.link]p6:
7916 ///   Two declarations [for a function or variable] with C language linkage
7917 ///   with the same name that appear in different scopes refer to the same
7918 ///   [entity]. An entity with C language linkage shall not be declared with
7919 ///   the same name as an entity in global scope.
7920 template<typename T>
7921 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7922                                                   LookupResult &Previous) {
7923   if (!S.getLangOpts().CPlusPlus) {
7924     // In C, when declaring a global variable, look for a corresponding 'extern'
7925     // variable declared in function scope. We don't need this in C++, because
7926     // we find local extern decls in the surrounding file-scope DeclContext.
7927     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7928       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7929         Previous.clear();
7930         Previous.addDecl(Prev);
7931         return true;
7932       }
7933     }
7934     return false;
7935   }
7936 
7937   // A declaration in the translation unit can conflict with an extern "C"
7938   // declaration.
7939   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7940     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7941 
7942   // An extern "C" declaration can conflict with a declaration in the
7943   // translation unit or can be a redeclaration of an extern "C" declaration
7944   // in another scope.
7945   if (isIncompleteDeclExternC(S,ND))
7946     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7947 
7948   // Neither global nor extern "C": nothing to do.
7949   return false;
7950 }
7951 
7952 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7953   // If the decl is already known invalid, don't check it.
7954   if (NewVD->isInvalidDecl())
7955     return;
7956 
7957   QualType T = NewVD->getType();
7958 
7959   // Defer checking an 'auto' type until its initializer is attached.
7960   if (T->isUndeducedType())
7961     return;
7962 
7963   if (NewVD->hasAttrs())
7964     CheckAlignasUnderalignment(NewVD);
7965 
7966   if (T->isObjCObjectType()) {
7967     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7968       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7969     T = Context.getObjCObjectPointerType(T);
7970     NewVD->setType(T);
7971   }
7972 
7973   // Emit an error if an address space was applied to decl with local storage.
7974   // This includes arrays of objects with address space qualifiers, but not
7975   // automatic variables that point to other address spaces.
7976   // ISO/IEC TR 18037 S5.1.2
7977   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7978       T.getAddressSpace() != LangAS::Default) {
7979     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7980     NewVD->setInvalidDecl();
7981     return;
7982   }
7983 
7984   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7985   // scope.
7986   if (getLangOpts().OpenCLVersion == 120 &&
7987       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7988                                             getLangOpts()) &&
7989       NewVD->isStaticLocal()) {
7990     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7991     NewVD->setInvalidDecl();
7992     return;
7993   }
7994 
7995   if (getLangOpts().OpenCL) {
7996     if (!diagnoseOpenCLTypes(*this, NewVD))
7997       return;
7998 
7999     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8000     if (NewVD->hasAttr<BlocksAttr>()) {
8001       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8002       return;
8003     }
8004 
8005     if (T->isBlockPointerType()) {
8006       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8007       // can't use 'extern' storage class.
8008       if (!T.isConstQualified()) {
8009         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8010             << 0 /*const*/;
8011         NewVD->setInvalidDecl();
8012         return;
8013       }
8014       if (NewVD->hasExternalStorage()) {
8015         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8016         NewVD->setInvalidDecl();
8017         return;
8018       }
8019     }
8020 
8021     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
8022     // __constant address space.
8023     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
8024     // variables inside a function can also be declared in the global
8025     // address space.
8026     // C++ for OpenCL inherits rule from OpenCL C v2.0.
8027     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8028     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8029         NewVD->hasExternalStorage()) {
8030       if (!T->isSamplerT() &&
8031           !T->isDependentType() &&
8032           !(T.getAddressSpace() == LangAS::opencl_constant ||
8033             (T.getAddressSpace() == LangAS::opencl_global &&
8034              (getLangOpts().OpenCLVersion == 200 ||
8035               getLangOpts().OpenCLCPlusPlus)))) {
8036         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8037         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
8038           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8039               << Scope << "global or constant";
8040         else
8041           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8042               << Scope << "constant";
8043         NewVD->setInvalidDecl();
8044         return;
8045       }
8046     } else {
8047       if (T.getAddressSpace() == LangAS::opencl_global) {
8048         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8049             << 1 /*is any function*/ << "global";
8050         NewVD->setInvalidDecl();
8051         return;
8052       }
8053       if (T.getAddressSpace() == LangAS::opencl_constant ||
8054           T.getAddressSpace() == LangAS::opencl_local) {
8055         FunctionDecl *FD = getCurFunctionDecl();
8056         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8057         // in functions.
8058         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8059           if (T.getAddressSpace() == LangAS::opencl_constant)
8060             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8061                 << 0 /*non-kernel only*/ << "constant";
8062           else
8063             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8064                 << 0 /*non-kernel only*/ << "local";
8065           NewVD->setInvalidDecl();
8066           return;
8067         }
8068         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8069         // in the outermost scope of a kernel function.
8070         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8071           if (!getCurScope()->isFunctionScope()) {
8072             if (T.getAddressSpace() == LangAS::opencl_constant)
8073               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8074                   << "constant";
8075             else
8076               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8077                   << "local";
8078             NewVD->setInvalidDecl();
8079             return;
8080           }
8081         }
8082       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8083                  // If we are parsing a template we didn't deduce an addr
8084                  // space yet.
8085                  T.getAddressSpace() != LangAS::Default) {
8086         // Do not allow other address spaces on automatic variable.
8087         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8088         NewVD->setInvalidDecl();
8089         return;
8090       }
8091     }
8092   }
8093 
8094   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8095       && !NewVD->hasAttr<BlocksAttr>()) {
8096     if (getLangOpts().getGC() != LangOptions::NonGC)
8097       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8098     else {
8099       assert(!getLangOpts().ObjCAutoRefCount);
8100       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8101     }
8102   }
8103 
8104   bool isVM = T->isVariablyModifiedType();
8105   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8106       NewVD->hasAttr<BlocksAttr>())
8107     setFunctionHasBranchProtectedScope();
8108 
8109   if ((isVM && NewVD->hasLinkage()) ||
8110       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8111     bool SizeIsNegative;
8112     llvm::APSInt Oversized;
8113     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8114         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8115     QualType FixedT;
8116     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8117       FixedT = FixedTInfo->getType();
8118     else if (FixedTInfo) {
8119       // Type and type-as-written are canonically different. We need to fix up
8120       // both types separately.
8121       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8122                                                    Oversized);
8123     }
8124     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8125       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8126       // FIXME: This won't give the correct result for
8127       // int a[10][n];
8128       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8129 
8130       if (NewVD->isFileVarDecl())
8131         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8132         << SizeRange;
8133       else if (NewVD->isStaticLocal())
8134         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8135         << SizeRange;
8136       else
8137         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8138         << SizeRange;
8139       NewVD->setInvalidDecl();
8140       return;
8141     }
8142 
8143     if (!FixedTInfo) {
8144       if (NewVD->isFileVarDecl())
8145         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8146       else
8147         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8148       NewVD->setInvalidDecl();
8149       return;
8150     }
8151 
8152     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8153     NewVD->setType(FixedT);
8154     NewVD->setTypeSourceInfo(FixedTInfo);
8155   }
8156 
8157   if (T->isVoidType()) {
8158     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8159     //                    of objects and functions.
8160     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8161       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8162         << T;
8163       NewVD->setInvalidDecl();
8164       return;
8165     }
8166   }
8167 
8168   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8169     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8170     NewVD->setInvalidDecl();
8171     return;
8172   }
8173 
8174   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8175     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8176     NewVD->setInvalidDecl();
8177     return;
8178   }
8179 
8180   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8181     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8182     NewVD->setInvalidDecl();
8183     return;
8184   }
8185 
8186   if (NewVD->isConstexpr() && !T->isDependentType() &&
8187       RequireLiteralType(NewVD->getLocation(), T,
8188                          diag::err_constexpr_var_non_literal)) {
8189     NewVD->setInvalidDecl();
8190     return;
8191   }
8192 
8193   // PPC MMA non-pointer types are not allowed as non-local variable types.
8194   if (Context.getTargetInfo().getTriple().isPPC64() &&
8195       !NewVD->isLocalVarDecl() &&
8196       CheckPPCMMAType(T, NewVD->getLocation())) {
8197     NewVD->setInvalidDecl();
8198     return;
8199   }
8200 }
8201 
8202 /// Perform semantic checking on a newly-created variable
8203 /// declaration.
8204 ///
8205 /// This routine performs all of the type-checking required for a
8206 /// variable declaration once it has been built. It is used both to
8207 /// check variables after they have been parsed and their declarators
8208 /// have been translated into a declaration, and to check variables
8209 /// that have been instantiated from a template.
8210 ///
8211 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8212 ///
8213 /// Returns true if the variable declaration is a redeclaration.
8214 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8215   CheckVariableDeclarationType(NewVD);
8216 
8217   // If the decl is already known invalid, don't check it.
8218   if (NewVD->isInvalidDecl())
8219     return false;
8220 
8221   // If we did not find anything by this name, look for a non-visible
8222   // extern "C" declaration with the same name.
8223   if (Previous.empty() &&
8224       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8225     Previous.setShadowed();
8226 
8227   if (!Previous.empty()) {
8228     MergeVarDecl(NewVD, Previous);
8229     return true;
8230   }
8231   return false;
8232 }
8233 
8234 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8235 /// and if so, check that it's a valid override and remember it.
8236 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8237   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8238 
8239   // Look for methods in base classes that this method might override.
8240   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8241                      /*DetectVirtual=*/false);
8242   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8243     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8244     DeclarationName Name = MD->getDeclName();
8245 
8246     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8247       // We really want to find the base class destructor here.
8248       QualType T = Context.getTypeDeclType(BaseRecord);
8249       CanQualType CT = Context.getCanonicalType(T);
8250       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8251     }
8252 
8253     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8254       CXXMethodDecl *BaseMD =
8255           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8256       if (!BaseMD || !BaseMD->isVirtual() ||
8257           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8258                      /*ConsiderCudaAttrs=*/true,
8259                      // C++2a [class.virtual]p2 does not consider requires
8260                      // clauses when overriding.
8261                      /*ConsiderRequiresClauses=*/false))
8262         continue;
8263 
8264       if (Overridden.insert(BaseMD).second) {
8265         MD->addOverriddenMethod(BaseMD);
8266         CheckOverridingFunctionReturnType(MD, BaseMD);
8267         CheckOverridingFunctionAttributes(MD, BaseMD);
8268         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8269         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8270       }
8271 
8272       // A method can only override one function from each base class. We
8273       // don't track indirectly overridden methods from bases of bases.
8274       return true;
8275     }
8276 
8277     return false;
8278   };
8279 
8280   DC->lookupInBases(VisitBase, Paths);
8281   return !Overridden.empty();
8282 }
8283 
8284 namespace {
8285   // Struct for holding all of the extra arguments needed by
8286   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8287   struct ActOnFDArgs {
8288     Scope *S;
8289     Declarator &D;
8290     MultiTemplateParamsArg TemplateParamLists;
8291     bool AddToScope;
8292   };
8293 } // end anonymous namespace
8294 
8295 namespace {
8296 
8297 // Callback to only accept typo corrections that have a non-zero edit distance.
8298 // Also only accept corrections that have the same parent decl.
8299 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8300  public:
8301   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8302                             CXXRecordDecl *Parent)
8303       : Context(Context), OriginalFD(TypoFD),
8304         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8305 
8306   bool ValidateCandidate(const TypoCorrection &candidate) override {
8307     if (candidate.getEditDistance() == 0)
8308       return false;
8309 
8310     SmallVector<unsigned, 1> MismatchedParams;
8311     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8312                                           CDeclEnd = candidate.end();
8313          CDecl != CDeclEnd; ++CDecl) {
8314       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8315 
8316       if (FD && !FD->hasBody() &&
8317           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8318         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8319           CXXRecordDecl *Parent = MD->getParent();
8320           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8321             return true;
8322         } else if (!ExpectedParent) {
8323           return true;
8324         }
8325       }
8326     }
8327 
8328     return false;
8329   }
8330 
8331   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8332     return std::make_unique<DifferentNameValidatorCCC>(*this);
8333   }
8334 
8335  private:
8336   ASTContext &Context;
8337   FunctionDecl *OriginalFD;
8338   CXXRecordDecl *ExpectedParent;
8339 };
8340 
8341 } // end anonymous namespace
8342 
8343 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8344   TypoCorrectedFunctionDefinitions.insert(F);
8345 }
8346 
8347 /// Generate diagnostics for an invalid function redeclaration.
8348 ///
8349 /// This routine handles generating the diagnostic messages for an invalid
8350 /// function redeclaration, including finding possible similar declarations
8351 /// or performing typo correction if there are no previous declarations with
8352 /// the same name.
8353 ///
8354 /// Returns a NamedDecl iff typo correction was performed and substituting in
8355 /// the new declaration name does not cause new errors.
8356 static NamedDecl *DiagnoseInvalidRedeclaration(
8357     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8358     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8359   DeclarationName Name = NewFD->getDeclName();
8360   DeclContext *NewDC = NewFD->getDeclContext();
8361   SmallVector<unsigned, 1> MismatchedParams;
8362   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8363   TypoCorrection Correction;
8364   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8365   unsigned DiagMsg =
8366     IsLocalFriend ? diag::err_no_matching_local_friend :
8367     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8368     diag::err_member_decl_does_not_match;
8369   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8370                     IsLocalFriend ? Sema::LookupLocalFriendName
8371                                   : Sema::LookupOrdinaryName,
8372                     Sema::ForVisibleRedeclaration);
8373 
8374   NewFD->setInvalidDecl();
8375   if (IsLocalFriend)
8376     SemaRef.LookupName(Prev, S);
8377   else
8378     SemaRef.LookupQualifiedName(Prev, NewDC);
8379   assert(!Prev.isAmbiguous() &&
8380          "Cannot have an ambiguity in previous-declaration lookup");
8381   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8382   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8383                                 MD ? MD->getParent() : nullptr);
8384   if (!Prev.empty()) {
8385     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8386          Func != FuncEnd; ++Func) {
8387       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8388       if (FD &&
8389           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8390         // Add 1 to the index so that 0 can mean the mismatch didn't
8391         // involve a parameter
8392         unsigned ParamNum =
8393             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8394         NearMatches.push_back(std::make_pair(FD, ParamNum));
8395       }
8396     }
8397   // If the qualified name lookup yielded nothing, try typo correction
8398   } else if ((Correction = SemaRef.CorrectTypo(
8399                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8400                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8401                   IsLocalFriend ? nullptr : NewDC))) {
8402     // Set up everything for the call to ActOnFunctionDeclarator
8403     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8404                               ExtraArgs.D.getIdentifierLoc());
8405     Previous.clear();
8406     Previous.setLookupName(Correction.getCorrection());
8407     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8408                                     CDeclEnd = Correction.end();
8409          CDecl != CDeclEnd; ++CDecl) {
8410       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8411       if (FD && !FD->hasBody() &&
8412           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8413         Previous.addDecl(FD);
8414       }
8415     }
8416     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8417 
8418     NamedDecl *Result;
8419     // Retry building the function declaration with the new previous
8420     // declarations, and with errors suppressed.
8421     {
8422       // Trap errors.
8423       Sema::SFINAETrap Trap(SemaRef);
8424 
8425       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8426       // pieces need to verify the typo-corrected C++ declaration and hopefully
8427       // eliminate the need for the parameter pack ExtraArgs.
8428       Result = SemaRef.ActOnFunctionDeclarator(
8429           ExtraArgs.S, ExtraArgs.D,
8430           Correction.getCorrectionDecl()->getDeclContext(),
8431           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8432           ExtraArgs.AddToScope);
8433 
8434       if (Trap.hasErrorOccurred())
8435         Result = nullptr;
8436     }
8437 
8438     if (Result) {
8439       // Determine which correction we picked.
8440       Decl *Canonical = Result->getCanonicalDecl();
8441       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8442            I != E; ++I)
8443         if ((*I)->getCanonicalDecl() == Canonical)
8444           Correction.setCorrectionDecl(*I);
8445 
8446       // Let Sema know about the correction.
8447       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8448       SemaRef.diagnoseTypo(
8449           Correction,
8450           SemaRef.PDiag(IsLocalFriend
8451                           ? diag::err_no_matching_local_friend_suggest
8452                           : diag::err_member_decl_does_not_match_suggest)
8453             << Name << NewDC << IsDefinition);
8454       return Result;
8455     }
8456 
8457     // Pretend the typo correction never occurred
8458     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8459                               ExtraArgs.D.getIdentifierLoc());
8460     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8461     Previous.clear();
8462     Previous.setLookupName(Name);
8463   }
8464 
8465   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8466       << Name << NewDC << IsDefinition << NewFD->getLocation();
8467 
8468   bool NewFDisConst = false;
8469   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8470     NewFDisConst = NewMD->isConst();
8471 
8472   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8473        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8474        NearMatch != NearMatchEnd; ++NearMatch) {
8475     FunctionDecl *FD = NearMatch->first;
8476     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8477     bool FDisConst = MD && MD->isConst();
8478     bool IsMember = MD || !IsLocalFriend;
8479 
8480     // FIXME: These notes are poorly worded for the local friend case.
8481     if (unsigned Idx = NearMatch->second) {
8482       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8483       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8484       if (Loc.isInvalid()) Loc = FD->getLocation();
8485       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8486                                  : diag::note_local_decl_close_param_match)
8487         << Idx << FDParam->getType()
8488         << NewFD->getParamDecl(Idx - 1)->getType();
8489     } else if (FDisConst != NewFDisConst) {
8490       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8491           << NewFDisConst << FD->getSourceRange().getEnd();
8492     } else
8493       SemaRef.Diag(FD->getLocation(),
8494                    IsMember ? diag::note_member_def_close_match
8495                             : diag::note_local_decl_close_match);
8496   }
8497   return nullptr;
8498 }
8499 
8500 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8501   switch (D.getDeclSpec().getStorageClassSpec()) {
8502   default: llvm_unreachable("Unknown storage class!");
8503   case DeclSpec::SCS_auto:
8504   case DeclSpec::SCS_register:
8505   case DeclSpec::SCS_mutable:
8506     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8507                  diag::err_typecheck_sclass_func);
8508     D.getMutableDeclSpec().ClearStorageClassSpecs();
8509     D.setInvalidType();
8510     break;
8511   case DeclSpec::SCS_unspecified: break;
8512   case DeclSpec::SCS_extern:
8513     if (D.getDeclSpec().isExternInLinkageSpec())
8514       return SC_None;
8515     return SC_Extern;
8516   case DeclSpec::SCS_static: {
8517     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8518       // C99 6.7.1p5:
8519       //   The declaration of an identifier for a function that has
8520       //   block scope shall have no explicit storage-class specifier
8521       //   other than extern
8522       // See also (C++ [dcl.stc]p4).
8523       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8524                    diag::err_static_block_func);
8525       break;
8526     } else
8527       return SC_Static;
8528   }
8529   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8530   }
8531 
8532   // No explicit storage class has already been returned
8533   return SC_None;
8534 }
8535 
8536 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8537                                            DeclContext *DC, QualType &R,
8538                                            TypeSourceInfo *TInfo,
8539                                            StorageClass SC,
8540                                            bool &IsVirtualOkay) {
8541   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8542   DeclarationName Name = NameInfo.getName();
8543 
8544   FunctionDecl *NewFD = nullptr;
8545   bool isInline = D.getDeclSpec().isInlineSpecified();
8546 
8547   if (!SemaRef.getLangOpts().CPlusPlus) {
8548     // Determine whether the function was written with a
8549     // prototype. This true when:
8550     //   - there is a prototype in the declarator, or
8551     //   - the type R of the function is some kind of typedef or other non-
8552     //     attributed reference to a type name (which eventually refers to a
8553     //     function type).
8554     bool HasPrototype =
8555       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8556       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8557 
8558     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8559                                  R, TInfo, SC, isInline, HasPrototype,
8560                                  ConstexprSpecKind::Unspecified,
8561                                  /*TrailingRequiresClause=*/nullptr);
8562     if (D.isInvalidType())
8563       NewFD->setInvalidDecl();
8564 
8565     return NewFD;
8566   }
8567 
8568   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8569 
8570   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8571   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8572     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8573                  diag::err_constexpr_wrong_decl_kind)
8574         << static_cast<int>(ConstexprKind);
8575     ConstexprKind = ConstexprSpecKind::Unspecified;
8576     D.getMutableDeclSpec().ClearConstexprSpec();
8577   }
8578   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8579 
8580   // Check that the return type is not an abstract class type.
8581   // For record types, this is done by the AbstractClassUsageDiagnoser once
8582   // the class has been completely parsed.
8583   if (!DC->isRecord() &&
8584       SemaRef.RequireNonAbstractType(
8585           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8586           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8587     D.setInvalidType();
8588 
8589   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8590     // This is a C++ constructor declaration.
8591     assert(DC->isRecord() &&
8592            "Constructors can only be declared in a member context");
8593 
8594     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8595     return CXXConstructorDecl::Create(
8596         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8597         TInfo, ExplicitSpecifier, isInline,
8598         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8599         TrailingRequiresClause);
8600 
8601   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8602     // This is a C++ destructor declaration.
8603     if (DC->isRecord()) {
8604       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8605       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8606       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8607           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8608           isInline, /*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(SemaRef.Context, DC, D.getBeginLoc(),
8627                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8628                                   isInline,
8629                                   /*hasPrototype=*/true, ConstexprKind,
8630                                   TrailingRequiresClause);
8631     }
8632 
8633   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8634     if (!DC->isRecord()) {
8635       SemaRef.Diag(D.getIdentifierLoc(),
8636            diag::err_conv_function_not_member);
8637       return nullptr;
8638     }
8639 
8640     SemaRef.CheckConversionDeclarator(D, R, SC);
8641     if (D.isInvalidType())
8642       return nullptr;
8643 
8644     IsVirtualOkay = true;
8645     return CXXConversionDecl::Create(
8646         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8647         TInfo, isInline, 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, isInline, ConstexprKind, SourceLocation(),
8677         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(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8690                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8691                                 ConstexprKind, TrailingRequiresClause);
8692   }
8693 }
8694 
8695 enum OpenCLParamType {
8696   ValidKernelParam,
8697   PtrPtrKernelParam,
8698   PtrKernelParam,
8699   InvalidAddrSpacePtrKernelParam,
8700   InvalidKernelParam,
8701   RecordKernelParam
8702 };
8703 
8704 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8705   // Size dependent types are just typedefs to normal integer types
8706   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8707   // integers other than by their names.
8708   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8709 
8710   // Remove typedefs one by one until we reach a typedef
8711   // for a size dependent type.
8712   QualType DesugaredTy = Ty;
8713   do {
8714     ArrayRef<StringRef> Names(SizeTypeNames);
8715     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8716     if (Names.end() != Match)
8717       return true;
8718 
8719     Ty = DesugaredTy;
8720     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8721   } while (DesugaredTy != Ty);
8722 
8723   return false;
8724 }
8725 
8726 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8727   if (PT->isDependentType())
8728     return InvalidKernelParam;
8729 
8730   if (PT->isPointerType() || PT->isReferenceType()) {
8731     QualType PointeeType = PT->getPointeeType();
8732     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8733         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8734         PointeeType.getAddressSpace() == LangAS::Default)
8735       return InvalidAddrSpacePtrKernelParam;
8736 
8737     if (PointeeType->isPointerType()) {
8738       // This is a pointer to pointer parameter.
8739       // Recursively check inner type.
8740       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8741       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8742           ParamKind == InvalidKernelParam)
8743         return ParamKind;
8744 
8745       return PtrPtrKernelParam;
8746     }
8747 
8748     // C++ for OpenCL v1.0 s2.4:
8749     // Moreover the types used in parameters of the kernel functions must be:
8750     // Standard layout types for pointer parameters. The same applies to
8751     // reference if an implementation supports them in kernel parameters.
8752     if (S.getLangOpts().OpenCLCPlusPlus &&
8753         !S.getOpenCLOptions().isAvailableOption(
8754             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8755         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8756         !PointeeType->isStandardLayoutType())
8757       return InvalidKernelParam;
8758 
8759     return PtrKernelParam;
8760   }
8761 
8762   // OpenCL v1.2 s6.9.k:
8763   // Arguments to kernel functions in a program cannot be declared with the
8764   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8765   // uintptr_t or a struct and/or union that contain fields declared to be one
8766   // of these built-in scalar types.
8767   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8768     return InvalidKernelParam;
8769 
8770   if (PT->isImageType())
8771     return PtrKernelParam;
8772 
8773   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8774     return InvalidKernelParam;
8775 
8776   // OpenCL extension spec v1.2 s9.5:
8777   // This extension adds support for half scalar and vector types as built-in
8778   // types that can be used for arithmetic operations, conversions etc.
8779   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8780       PT->isHalfType())
8781     return InvalidKernelParam;
8782 
8783   // Look into an array argument to check if it has a forbidden type.
8784   if (PT->isArrayType()) {
8785     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8786     // Call ourself to check an underlying type of an array. Since the
8787     // getPointeeOrArrayElementType returns an innermost type which is not an
8788     // array, this recursive call only happens once.
8789     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8790   }
8791 
8792   // C++ for OpenCL v1.0 s2.4:
8793   // Moreover the types used in parameters of the kernel functions must be:
8794   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8795   // types) for parameters passed by value;
8796   if (S.getLangOpts().OpenCLCPlusPlus &&
8797       !S.getOpenCLOptions().isAvailableOption(
8798           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8799       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8800     return InvalidKernelParam;
8801 
8802   if (PT->isRecordType())
8803     return RecordKernelParam;
8804 
8805   return ValidKernelParam;
8806 }
8807 
8808 static void checkIsValidOpenCLKernelParameter(
8809   Sema &S,
8810   Declarator &D,
8811   ParmVarDecl *Param,
8812   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8813   QualType PT = Param->getType();
8814 
8815   // Cache the valid types we encounter to avoid rechecking structs that are
8816   // used again
8817   if (ValidTypes.count(PT.getTypePtr()))
8818     return;
8819 
8820   switch (getOpenCLKernelParameterType(S, PT)) {
8821   case PtrPtrKernelParam:
8822     // OpenCL v3.0 s6.11.a:
8823     // A kernel function argument cannot be declared as a pointer to a pointer
8824     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8825     if (S.getLangOpts().OpenCLVersion < 120 &&
8826         !S.getLangOpts().OpenCLCPlusPlus) {
8827       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8828       D.setInvalidType();
8829       return;
8830     }
8831 
8832     ValidTypes.insert(PT.getTypePtr());
8833     return;
8834 
8835   case InvalidAddrSpacePtrKernelParam:
8836     // OpenCL v1.0 s6.5:
8837     // __kernel function arguments declared to be a pointer of a type can point
8838     // to one of the following address spaces only : __global, __local or
8839     // __constant.
8840     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8841     D.setInvalidType();
8842     return;
8843 
8844     // OpenCL v1.2 s6.9.k:
8845     // Arguments to kernel functions in a program cannot be declared with the
8846     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8847     // uintptr_t or a struct and/or union that contain fields declared to be
8848     // one of these built-in scalar types.
8849 
8850   case InvalidKernelParam:
8851     // OpenCL v1.2 s6.8 n:
8852     // A kernel function argument cannot be declared
8853     // of event_t type.
8854     // Do not diagnose half type since it is diagnosed as invalid argument
8855     // type for any function elsewhere.
8856     if (!PT->isHalfType()) {
8857       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8858 
8859       // Explain what typedefs are involved.
8860       const TypedefType *Typedef = nullptr;
8861       while ((Typedef = PT->getAs<TypedefType>())) {
8862         SourceLocation Loc = Typedef->getDecl()->getLocation();
8863         // SourceLocation may be invalid for a built-in type.
8864         if (Loc.isValid())
8865           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8866         PT = Typedef->desugar();
8867       }
8868     }
8869 
8870     D.setInvalidType();
8871     return;
8872 
8873   case PtrKernelParam:
8874   case ValidKernelParam:
8875     ValidTypes.insert(PT.getTypePtr());
8876     return;
8877 
8878   case RecordKernelParam:
8879     break;
8880   }
8881 
8882   // Track nested structs we will inspect
8883   SmallVector<const Decl *, 4> VisitStack;
8884 
8885   // Track where we are in the nested structs. Items will migrate from
8886   // VisitStack to HistoryStack as we do the DFS for bad field.
8887   SmallVector<const FieldDecl *, 4> HistoryStack;
8888   HistoryStack.push_back(nullptr);
8889 
8890   // At this point we already handled everything except of a RecordType or
8891   // an ArrayType of a RecordType.
8892   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8893   const RecordType *RecTy =
8894       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8895   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8896 
8897   VisitStack.push_back(RecTy->getDecl());
8898   assert(VisitStack.back() && "First decl null?");
8899 
8900   do {
8901     const Decl *Next = VisitStack.pop_back_val();
8902     if (!Next) {
8903       assert(!HistoryStack.empty());
8904       // Found a marker, we have gone up a level
8905       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8906         ValidTypes.insert(Hist->getType().getTypePtr());
8907 
8908       continue;
8909     }
8910 
8911     // Adds everything except the original parameter declaration (which is not a
8912     // field itself) to the history stack.
8913     const RecordDecl *RD;
8914     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8915       HistoryStack.push_back(Field);
8916 
8917       QualType FieldTy = Field->getType();
8918       // Other field types (known to be valid or invalid) are handled while we
8919       // walk around RecordDecl::fields().
8920       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8921              "Unexpected type.");
8922       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8923 
8924       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8925     } else {
8926       RD = cast<RecordDecl>(Next);
8927     }
8928 
8929     // Add a null marker so we know when we've gone back up a level
8930     VisitStack.push_back(nullptr);
8931 
8932     for (const auto *FD : RD->fields()) {
8933       QualType QT = FD->getType();
8934 
8935       if (ValidTypes.count(QT.getTypePtr()))
8936         continue;
8937 
8938       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8939       if (ParamType == ValidKernelParam)
8940         continue;
8941 
8942       if (ParamType == RecordKernelParam) {
8943         VisitStack.push_back(FD);
8944         continue;
8945       }
8946 
8947       // OpenCL v1.2 s6.9.p:
8948       // Arguments to kernel functions that are declared to be a struct or union
8949       // do not allow OpenCL objects to be passed as elements of the struct or
8950       // union.
8951       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8952           ParamType == InvalidAddrSpacePtrKernelParam) {
8953         S.Diag(Param->getLocation(),
8954                diag::err_record_with_pointers_kernel_param)
8955           << PT->isUnionType()
8956           << PT;
8957       } else {
8958         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8959       }
8960 
8961       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8962           << OrigRecDecl->getDeclName();
8963 
8964       // We have an error, now let's go back up through history and show where
8965       // the offending field came from
8966       for (ArrayRef<const FieldDecl *>::const_iterator
8967                I = HistoryStack.begin() + 1,
8968                E = HistoryStack.end();
8969            I != E; ++I) {
8970         const FieldDecl *OuterField = *I;
8971         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8972           << OuterField->getType();
8973       }
8974 
8975       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8976         << QT->isPointerType()
8977         << QT;
8978       D.setInvalidType();
8979       return;
8980     }
8981   } while (!VisitStack.empty());
8982 }
8983 
8984 /// Find the DeclContext in which a tag is implicitly declared if we see an
8985 /// elaborated type specifier in the specified context, and lookup finds
8986 /// nothing.
8987 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8988   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8989     DC = DC->getParent();
8990   return DC;
8991 }
8992 
8993 /// Find the Scope in which a tag is implicitly declared if we see an
8994 /// elaborated type specifier in the specified context, and lookup finds
8995 /// nothing.
8996 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8997   while (S->isClassScope() ||
8998          (LangOpts.CPlusPlus &&
8999           S->isFunctionPrototypeScope()) ||
9000          ((S->getFlags() & Scope::DeclScope) == 0) ||
9001          (S->getEntity() && S->getEntity()->isTransparentContext()))
9002     S = S->getParent();
9003   return S;
9004 }
9005 
9006 NamedDecl*
9007 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9008                               TypeSourceInfo *TInfo, LookupResult &Previous,
9009                               MultiTemplateParamsArg TemplateParamListsRef,
9010                               bool &AddToScope) {
9011   QualType R = TInfo->getType();
9012 
9013   assert(R->isFunctionType());
9014   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9015     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9016 
9017   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9018   for (TemplateParameterList *TPL : TemplateParamListsRef)
9019     TemplateParamLists.push_back(TPL);
9020   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9021     if (!TemplateParamLists.empty() &&
9022         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9023       TemplateParamLists.back() = Invented;
9024     else
9025       TemplateParamLists.push_back(Invented);
9026   }
9027 
9028   // TODO: consider using NameInfo for diagnostic.
9029   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9030   DeclarationName Name = NameInfo.getName();
9031   StorageClass SC = getFunctionStorageClass(*this, D);
9032 
9033   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9034     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9035          diag::err_invalid_thread)
9036       << DeclSpec::getSpecifierName(TSCS);
9037 
9038   if (D.isFirstDeclarationOfMember())
9039     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9040                            D.getIdentifierLoc());
9041 
9042   bool isFriend = false;
9043   FunctionTemplateDecl *FunctionTemplate = nullptr;
9044   bool isMemberSpecialization = false;
9045   bool isFunctionTemplateSpecialization = false;
9046 
9047   bool isDependentClassScopeExplicitSpecialization = false;
9048   bool HasExplicitTemplateArgs = false;
9049   TemplateArgumentListInfo TemplateArgs;
9050 
9051   bool isVirtualOkay = false;
9052 
9053   DeclContext *OriginalDC = DC;
9054   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9055 
9056   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9057                                               isVirtualOkay);
9058   if (!NewFD) return nullptr;
9059 
9060   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9061     NewFD->setTopLevelDeclInObjCContainer();
9062 
9063   // Set the lexical context. If this is a function-scope declaration, or has a
9064   // C++ scope specifier, or is the object of a friend declaration, the lexical
9065   // context will be different from the semantic context.
9066   NewFD->setLexicalDeclContext(CurContext);
9067 
9068   if (IsLocalExternDecl)
9069     NewFD->setLocalExternDecl();
9070 
9071   if (getLangOpts().CPlusPlus) {
9072     bool isInline = D.getDeclSpec().isInlineSpecified();
9073     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9074     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9075     isFriend = D.getDeclSpec().isFriendSpecified();
9076     if (isFriend && !isInline && D.isFunctionDefinition()) {
9077       // C++ [class.friend]p5
9078       //   A function can be defined in a friend declaration of a
9079       //   class . . . . Such a function is implicitly inline.
9080       NewFD->setImplicitlyInline();
9081     }
9082 
9083     // If this is a method defined in an __interface, and is not a constructor
9084     // or an overloaded operator, then set the pure flag (isVirtual will already
9085     // return true).
9086     if (const CXXRecordDecl *Parent =
9087           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9088       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9089         NewFD->setPure(true);
9090 
9091       // C++ [class.union]p2
9092       //   A union can have member functions, but not virtual functions.
9093       if (isVirtual && Parent->isUnion())
9094         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9095     }
9096 
9097     SetNestedNameSpecifier(*this, NewFD, D);
9098     isMemberSpecialization = false;
9099     isFunctionTemplateSpecialization = false;
9100     if (D.isInvalidType())
9101       NewFD->setInvalidDecl();
9102 
9103     // Match up the template parameter lists with the scope specifier, then
9104     // determine whether we have a template or a template specialization.
9105     bool Invalid = false;
9106     TemplateParameterList *TemplateParams =
9107         MatchTemplateParametersToScopeSpecifier(
9108             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9109             D.getCXXScopeSpec(),
9110             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9111                 ? D.getName().TemplateId
9112                 : nullptr,
9113             TemplateParamLists, isFriend, isMemberSpecialization,
9114             Invalid);
9115     if (TemplateParams) {
9116       // Check that we can declare a template here.
9117       if (CheckTemplateDeclScope(S, TemplateParams))
9118         NewFD->setInvalidDecl();
9119 
9120       if (TemplateParams->size() > 0) {
9121         // This is a function template
9122 
9123         // A destructor cannot be a template.
9124         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9125           Diag(NewFD->getLocation(), diag::err_destructor_template);
9126           NewFD->setInvalidDecl();
9127         }
9128 
9129         // If we're adding a template to a dependent context, we may need to
9130         // rebuilding some of the types used within the template parameter list,
9131         // now that we know what the current instantiation is.
9132         if (DC->isDependentContext()) {
9133           ContextRAII SavedContext(*this, DC);
9134           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9135             Invalid = true;
9136         }
9137 
9138         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9139                                                         NewFD->getLocation(),
9140                                                         Name, TemplateParams,
9141                                                         NewFD);
9142         FunctionTemplate->setLexicalDeclContext(CurContext);
9143         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9144 
9145         // For source fidelity, store the other template param lists.
9146         if (TemplateParamLists.size() > 1) {
9147           NewFD->setTemplateParameterListsInfo(Context,
9148               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9149                   .drop_back(1));
9150         }
9151       } else {
9152         // This is a function template specialization.
9153         isFunctionTemplateSpecialization = true;
9154         // For source fidelity, store all the template param lists.
9155         if (TemplateParamLists.size() > 0)
9156           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9157 
9158         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9159         if (isFriend) {
9160           // We want to remove the "template<>", found here.
9161           SourceRange RemoveRange = TemplateParams->getSourceRange();
9162 
9163           // If we remove the template<> and the name is not a
9164           // template-id, we're actually silently creating a problem:
9165           // the friend declaration will refer to an untemplated decl,
9166           // and clearly the user wants a template specialization.  So
9167           // we need to insert '<>' after the name.
9168           SourceLocation InsertLoc;
9169           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9170             InsertLoc = D.getName().getSourceRange().getEnd();
9171             InsertLoc = getLocForEndOfToken(InsertLoc);
9172           }
9173 
9174           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9175             << Name << RemoveRange
9176             << FixItHint::CreateRemoval(RemoveRange)
9177             << FixItHint::CreateInsertion(InsertLoc, "<>");
9178         }
9179       }
9180     } else {
9181       // Check that we can declare a template here.
9182       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9183           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9184         NewFD->setInvalidDecl();
9185 
9186       // All template param lists were matched against the scope specifier:
9187       // this is NOT (an explicit specialization of) a template.
9188       if (TemplateParamLists.size() > 0)
9189         // For source fidelity, store all the template param lists.
9190         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9191     }
9192 
9193     if (Invalid) {
9194       NewFD->setInvalidDecl();
9195       if (FunctionTemplate)
9196         FunctionTemplate->setInvalidDecl();
9197     }
9198 
9199     // C++ [dcl.fct.spec]p5:
9200     //   The virtual specifier shall only be used in declarations of
9201     //   nonstatic class member functions that appear within a
9202     //   member-specification of a class declaration; see 10.3.
9203     //
9204     if (isVirtual && !NewFD->isInvalidDecl()) {
9205       if (!isVirtualOkay) {
9206         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9207              diag::err_virtual_non_function);
9208       } else if (!CurContext->isRecord()) {
9209         // 'virtual' was specified outside of the class.
9210         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9211              diag::err_virtual_out_of_class)
9212           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9213       } else if (NewFD->getDescribedFunctionTemplate()) {
9214         // C++ [temp.mem]p3:
9215         //  A member function template shall not be virtual.
9216         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9217              diag::err_virtual_member_function_template)
9218           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9219       } else {
9220         // Okay: Add virtual to the method.
9221         NewFD->setVirtualAsWritten(true);
9222       }
9223 
9224       if (getLangOpts().CPlusPlus14 &&
9225           NewFD->getReturnType()->isUndeducedType())
9226         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9227     }
9228 
9229     if (getLangOpts().CPlusPlus14 &&
9230         (NewFD->isDependentContext() ||
9231          (isFriend && CurContext->isDependentContext())) &&
9232         NewFD->getReturnType()->isUndeducedType()) {
9233       // If the function template is referenced directly (for instance, as a
9234       // member of the current instantiation), pretend it has a dependent type.
9235       // This is not really justified by the standard, but is the only sane
9236       // thing to do.
9237       // FIXME: For a friend function, we have not marked the function as being
9238       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9239       const FunctionProtoType *FPT =
9240           NewFD->getType()->castAs<FunctionProtoType>();
9241       QualType Result =
9242           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9243       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9244                                              FPT->getExtProtoInfo()));
9245     }
9246 
9247     // C++ [dcl.fct.spec]p3:
9248     //  The inline specifier shall not appear on a block scope function
9249     //  declaration.
9250     if (isInline && !NewFD->isInvalidDecl()) {
9251       if (CurContext->isFunctionOrMethod()) {
9252         // 'inline' is not allowed on block scope function declaration.
9253         Diag(D.getDeclSpec().getInlineSpecLoc(),
9254              diag::err_inline_declaration_block_scope) << Name
9255           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9256       }
9257     }
9258 
9259     // C++ [dcl.fct.spec]p6:
9260     //  The explicit specifier shall be used only in the declaration of a
9261     //  constructor or conversion function within its class definition;
9262     //  see 12.3.1 and 12.3.2.
9263     if (hasExplicit && !NewFD->isInvalidDecl() &&
9264         !isa<CXXDeductionGuideDecl>(NewFD)) {
9265       if (!CurContext->isRecord()) {
9266         // 'explicit' was specified outside of the class.
9267         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9268              diag::err_explicit_out_of_class)
9269             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9270       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9271                  !isa<CXXConversionDecl>(NewFD)) {
9272         // 'explicit' was specified on a function that wasn't a constructor
9273         // or conversion function.
9274         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9275              diag::err_explicit_non_ctor_or_conv_function)
9276             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9277       }
9278     }
9279 
9280     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9281     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9282       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9283       // are implicitly inline.
9284       NewFD->setImplicitlyInline();
9285 
9286       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9287       // be either constructors or to return a literal type. Therefore,
9288       // destructors cannot be declared constexpr.
9289       if (isa<CXXDestructorDecl>(NewFD) &&
9290           (!getLangOpts().CPlusPlus20 ||
9291            ConstexprKind == ConstexprSpecKind::Consteval)) {
9292         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9293             << static_cast<int>(ConstexprKind);
9294         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9295                                     ? ConstexprSpecKind::Unspecified
9296                                     : ConstexprSpecKind::Constexpr);
9297       }
9298       // C++20 [dcl.constexpr]p2: An allocation function, or a
9299       // deallocation function shall not be declared with the consteval
9300       // specifier.
9301       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9302           (NewFD->getOverloadedOperator() == OO_New ||
9303            NewFD->getOverloadedOperator() == OO_Array_New ||
9304            NewFD->getOverloadedOperator() == OO_Delete ||
9305            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9306         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9307              diag::err_invalid_consteval_decl_kind)
9308             << NewFD;
9309         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9310       }
9311     }
9312 
9313     // If __module_private__ was specified, mark the function accordingly.
9314     if (D.getDeclSpec().isModulePrivateSpecified()) {
9315       if (isFunctionTemplateSpecialization) {
9316         SourceLocation ModulePrivateLoc
9317           = D.getDeclSpec().getModulePrivateSpecLoc();
9318         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9319           << 0
9320           << FixItHint::CreateRemoval(ModulePrivateLoc);
9321       } else {
9322         NewFD->setModulePrivate();
9323         if (FunctionTemplate)
9324           FunctionTemplate->setModulePrivate();
9325       }
9326     }
9327 
9328     if (isFriend) {
9329       if (FunctionTemplate) {
9330         FunctionTemplate->setObjectOfFriendDecl();
9331         FunctionTemplate->setAccess(AS_public);
9332       }
9333       NewFD->setObjectOfFriendDecl();
9334       NewFD->setAccess(AS_public);
9335     }
9336 
9337     // If a function is defined as defaulted or deleted, mark it as such now.
9338     // We'll do the relevant checks on defaulted / deleted functions later.
9339     switch (D.getFunctionDefinitionKind()) {
9340     case FunctionDefinitionKind::Declaration:
9341     case FunctionDefinitionKind::Definition:
9342       break;
9343 
9344     case FunctionDefinitionKind::Defaulted:
9345       NewFD->setDefaulted();
9346       break;
9347 
9348     case FunctionDefinitionKind::Deleted:
9349       NewFD->setDeletedAsWritten();
9350       break;
9351     }
9352 
9353     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9354         D.isFunctionDefinition()) {
9355       // C++ [class.mfct]p2:
9356       //   A member function may be defined (8.4) in its class definition, in
9357       //   which case it is an inline member function (7.1.2)
9358       NewFD->setImplicitlyInline();
9359     }
9360 
9361     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9362         !CurContext->isRecord()) {
9363       // C++ [class.static]p1:
9364       //   A data or function member of a class may be declared static
9365       //   in a class definition, in which case it is a static member of
9366       //   the class.
9367 
9368       // Complain about the 'static' specifier if it's on an out-of-line
9369       // member function definition.
9370 
9371       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9372       // member function template declaration and class member template
9373       // declaration (MSVC versions before 2015), warn about this.
9374       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9375            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9376              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9377            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9378            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9379         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9380     }
9381 
9382     // C++11 [except.spec]p15:
9383     //   A deallocation function with no exception-specification is treated
9384     //   as if it were specified with noexcept(true).
9385     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9386     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9387          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9388         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9389       NewFD->setType(Context.getFunctionType(
9390           FPT->getReturnType(), FPT->getParamTypes(),
9391           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9392   }
9393 
9394   // Filter out previous declarations that don't match the scope.
9395   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9396                        D.getCXXScopeSpec().isNotEmpty() ||
9397                        isMemberSpecialization ||
9398                        isFunctionTemplateSpecialization);
9399 
9400   // Handle GNU asm-label extension (encoded as an attribute).
9401   if (Expr *E = (Expr*) D.getAsmLabel()) {
9402     // The parser guarantees this is a string.
9403     StringLiteral *SE = cast<StringLiteral>(E);
9404     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9405                                         /*IsLiteralLabel=*/true,
9406                                         SE->getStrTokenLoc(0)));
9407   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9408     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9409       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9410     if (I != ExtnameUndeclaredIdentifiers.end()) {
9411       if (isDeclExternC(NewFD)) {
9412         NewFD->addAttr(I->second);
9413         ExtnameUndeclaredIdentifiers.erase(I);
9414       } else
9415         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9416             << /*Variable*/0 << NewFD;
9417     }
9418   }
9419 
9420   // Copy the parameter declarations from the declarator D to the function
9421   // declaration NewFD, if they are available.  First scavenge them into Params.
9422   SmallVector<ParmVarDecl*, 16> Params;
9423   unsigned FTIIdx;
9424   if (D.isFunctionDeclarator(FTIIdx)) {
9425     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9426 
9427     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9428     // function that takes no arguments, not a function that takes a
9429     // single void argument.
9430     // We let through "const void" here because Sema::GetTypeForDeclarator
9431     // already checks for that case.
9432     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9433       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9434         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9435         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9436         Param->setDeclContext(NewFD);
9437         Params.push_back(Param);
9438 
9439         if (Param->isInvalidDecl())
9440           NewFD->setInvalidDecl();
9441       }
9442     }
9443 
9444     if (!getLangOpts().CPlusPlus) {
9445       // In C, find all the tag declarations from the prototype and move them
9446       // into the function DeclContext. Remove them from the surrounding tag
9447       // injection context of the function, which is typically but not always
9448       // the TU.
9449       DeclContext *PrototypeTagContext =
9450           getTagInjectionContext(NewFD->getLexicalDeclContext());
9451       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9452         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9453 
9454         // We don't want to reparent enumerators. Look at their parent enum
9455         // instead.
9456         if (!TD) {
9457           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9458             TD = cast<EnumDecl>(ECD->getDeclContext());
9459         }
9460         if (!TD)
9461           continue;
9462         DeclContext *TagDC = TD->getLexicalDeclContext();
9463         if (!TagDC->containsDecl(TD))
9464           continue;
9465         TagDC->removeDecl(TD);
9466         TD->setDeclContext(NewFD);
9467         NewFD->addDecl(TD);
9468 
9469         // Preserve the lexical DeclContext if it is not the surrounding tag
9470         // injection context of the FD. In this example, the semantic context of
9471         // E will be f and the lexical context will be S, while both the
9472         // semantic and lexical contexts of S will be f:
9473         //   void f(struct S { enum E { a } f; } s);
9474         if (TagDC != PrototypeTagContext)
9475           TD->setLexicalDeclContext(TagDC);
9476       }
9477     }
9478   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9479     // When we're declaring a function with a typedef, typeof, etc as in the
9480     // following example, we'll need to synthesize (unnamed)
9481     // parameters for use in the declaration.
9482     //
9483     // @code
9484     // typedef void fn(int);
9485     // fn f;
9486     // @endcode
9487 
9488     // Synthesize a parameter for each argument type.
9489     for (const auto &AI : FT->param_types()) {
9490       ParmVarDecl *Param =
9491           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9492       Param->setScopeInfo(0, Params.size());
9493       Params.push_back(Param);
9494     }
9495   } else {
9496     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9497            "Should not need args for typedef of non-prototype fn");
9498   }
9499 
9500   // Finally, we know we have the right number of parameters, install them.
9501   NewFD->setParams(Params);
9502 
9503   if (D.getDeclSpec().isNoreturnSpecified())
9504     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9505                                            D.getDeclSpec().getNoreturnSpecLoc(),
9506                                            AttributeCommonInfo::AS_Keyword));
9507 
9508   // Functions returning a variably modified type violate C99 6.7.5.2p2
9509   // because all functions have linkage.
9510   if (!NewFD->isInvalidDecl() &&
9511       NewFD->getReturnType()->isVariablyModifiedType()) {
9512     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9513     NewFD->setInvalidDecl();
9514   }
9515 
9516   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9517   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9518       !NewFD->hasAttr<SectionAttr>())
9519     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9520         Context, PragmaClangTextSection.SectionName,
9521         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9522 
9523   // Apply an implicit SectionAttr if #pragma code_seg is active.
9524   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9525       !NewFD->hasAttr<SectionAttr>()) {
9526     NewFD->addAttr(SectionAttr::CreateImplicit(
9527         Context, CodeSegStack.CurrentValue->getString(),
9528         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9529         SectionAttr::Declspec_allocate));
9530     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9531                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9532                          ASTContext::PSF_Read,
9533                      NewFD))
9534       NewFD->dropAttr<SectionAttr>();
9535   }
9536 
9537   // Apply an implicit CodeSegAttr from class declspec or
9538   // apply an implicit SectionAttr from #pragma code_seg if active.
9539   if (!NewFD->hasAttr<CodeSegAttr>()) {
9540     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9541                                                                  D.isFunctionDefinition())) {
9542       NewFD->addAttr(SAttr);
9543     }
9544   }
9545 
9546   // Handle attributes.
9547   ProcessDeclAttributes(S, NewFD, D);
9548 
9549   if (getLangOpts().OpenCL) {
9550     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9551     // type declaration will generate a compilation error.
9552     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9553     if (AddressSpace != LangAS::Default) {
9554       Diag(NewFD->getLocation(),
9555            diag::err_opencl_return_value_with_address_space);
9556       NewFD->setInvalidDecl();
9557     }
9558   }
9559 
9560   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9561     checkDeviceDecl(NewFD, D.getBeginLoc());
9562 
9563   if (!getLangOpts().CPlusPlus) {
9564     // Perform semantic checking on the function declaration.
9565     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9566       CheckMain(NewFD, D.getDeclSpec());
9567 
9568     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9569       CheckMSVCRTEntryPoint(NewFD);
9570 
9571     if (!NewFD->isInvalidDecl())
9572       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9573                                                   isMemberSpecialization));
9574     else if (!Previous.empty())
9575       // Recover gracefully from an invalid redeclaration.
9576       D.setRedeclaration(true);
9577     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9578             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9579            "previous declaration set still overloaded");
9580 
9581     // Diagnose no-prototype function declarations with calling conventions that
9582     // don't support variadic calls. Only do this in C and do it after merging
9583     // possibly prototyped redeclarations.
9584     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9585     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9586       CallingConv CC = FT->getExtInfo().getCC();
9587       if (!supportsVariadicCall(CC)) {
9588         // Windows system headers sometimes accidentally use stdcall without
9589         // (void) parameters, so we relax this to a warning.
9590         int DiagID =
9591             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9592         Diag(NewFD->getLocation(), DiagID)
9593             << FunctionType::getNameForCallConv(CC);
9594       }
9595     }
9596 
9597    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9598        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9599      checkNonTrivialCUnion(NewFD->getReturnType(),
9600                            NewFD->getReturnTypeSourceRange().getBegin(),
9601                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9602   } else {
9603     // C++11 [replacement.functions]p3:
9604     //  The program's definitions shall not be specified as inline.
9605     //
9606     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9607     //
9608     // Suppress the diagnostic if the function is __attribute__((used)), since
9609     // that forces an external definition to be emitted.
9610     if (D.getDeclSpec().isInlineSpecified() &&
9611         NewFD->isReplaceableGlobalAllocationFunction() &&
9612         !NewFD->hasAttr<UsedAttr>())
9613       Diag(D.getDeclSpec().getInlineSpecLoc(),
9614            diag::ext_operator_new_delete_declared_inline)
9615         << NewFD->getDeclName();
9616 
9617     // If the declarator is a template-id, translate the parser's template
9618     // argument list into our AST format.
9619     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9620       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9621       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9622       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9623       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9624                                          TemplateId->NumArgs);
9625       translateTemplateArguments(TemplateArgsPtr,
9626                                  TemplateArgs);
9627 
9628       HasExplicitTemplateArgs = true;
9629 
9630       if (NewFD->isInvalidDecl()) {
9631         HasExplicitTemplateArgs = false;
9632       } else if (FunctionTemplate) {
9633         // Function template with explicit template arguments.
9634         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9635           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9636 
9637         HasExplicitTemplateArgs = false;
9638       } else {
9639         assert((isFunctionTemplateSpecialization ||
9640                 D.getDeclSpec().isFriendSpecified()) &&
9641                "should have a 'template<>' for this decl");
9642         // "friend void foo<>(int);" is an implicit specialization decl.
9643         isFunctionTemplateSpecialization = true;
9644       }
9645     } else if (isFriend && isFunctionTemplateSpecialization) {
9646       // This combination is only possible in a recovery case;  the user
9647       // wrote something like:
9648       //   template <> friend void foo(int);
9649       // which we're recovering from as if the user had written:
9650       //   friend void foo<>(int);
9651       // Go ahead and fake up a template id.
9652       HasExplicitTemplateArgs = true;
9653       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9654       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9655     }
9656 
9657     // We do not add HD attributes to specializations here because
9658     // they may have different constexpr-ness compared to their
9659     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9660     // may end up with different effective targets. Instead, a
9661     // specialization inherits its target attributes from its template
9662     // in the CheckFunctionTemplateSpecialization() call below.
9663     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9664       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9665 
9666     // If it's a friend (and only if it's a friend), it's possible
9667     // that either the specialized function type or the specialized
9668     // template is dependent, and therefore matching will fail.  In
9669     // this case, don't check the specialization yet.
9670     if (isFunctionTemplateSpecialization && isFriend &&
9671         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9672          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9673              TemplateArgs.arguments()))) {
9674       assert(HasExplicitTemplateArgs &&
9675              "friend function specialization without template args");
9676       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9677                                                        Previous))
9678         NewFD->setInvalidDecl();
9679     } else if (isFunctionTemplateSpecialization) {
9680       if (CurContext->isDependentContext() && CurContext->isRecord()
9681           && !isFriend) {
9682         isDependentClassScopeExplicitSpecialization = true;
9683       } else if (!NewFD->isInvalidDecl() &&
9684                  CheckFunctionTemplateSpecialization(
9685                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9686                      Previous))
9687         NewFD->setInvalidDecl();
9688 
9689       // C++ [dcl.stc]p1:
9690       //   A storage-class-specifier shall not be specified in an explicit
9691       //   specialization (14.7.3)
9692       FunctionTemplateSpecializationInfo *Info =
9693           NewFD->getTemplateSpecializationInfo();
9694       if (Info && SC != SC_None) {
9695         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9696           Diag(NewFD->getLocation(),
9697                diag::err_explicit_specialization_inconsistent_storage_class)
9698             << SC
9699             << FixItHint::CreateRemoval(
9700                                       D.getDeclSpec().getStorageClassSpecLoc());
9701 
9702         else
9703           Diag(NewFD->getLocation(),
9704                diag::ext_explicit_specialization_storage_class)
9705             << FixItHint::CreateRemoval(
9706                                       D.getDeclSpec().getStorageClassSpecLoc());
9707       }
9708     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9709       if (CheckMemberSpecialization(NewFD, Previous))
9710           NewFD->setInvalidDecl();
9711     }
9712 
9713     // Perform semantic checking on the function declaration.
9714     if (!isDependentClassScopeExplicitSpecialization) {
9715       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9716         CheckMain(NewFD, D.getDeclSpec());
9717 
9718       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9719         CheckMSVCRTEntryPoint(NewFD);
9720 
9721       if (!NewFD->isInvalidDecl())
9722         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9723                                                     isMemberSpecialization));
9724       else if (!Previous.empty())
9725         // Recover gracefully from an invalid redeclaration.
9726         D.setRedeclaration(true);
9727     }
9728 
9729     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9730             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9731            "previous declaration set still overloaded");
9732 
9733     NamedDecl *PrincipalDecl = (FunctionTemplate
9734                                 ? cast<NamedDecl>(FunctionTemplate)
9735                                 : NewFD);
9736 
9737     if (isFriend && NewFD->getPreviousDecl()) {
9738       AccessSpecifier Access = AS_public;
9739       if (!NewFD->isInvalidDecl())
9740         Access = NewFD->getPreviousDecl()->getAccess();
9741 
9742       NewFD->setAccess(Access);
9743       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9744     }
9745 
9746     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9747         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9748       PrincipalDecl->setNonMemberOperator();
9749 
9750     // If we have a function template, check the template parameter
9751     // list. This will check and merge default template arguments.
9752     if (FunctionTemplate) {
9753       FunctionTemplateDecl *PrevTemplate =
9754                                      FunctionTemplate->getPreviousDecl();
9755       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9756                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9757                                     : nullptr,
9758                             D.getDeclSpec().isFriendSpecified()
9759                               ? (D.isFunctionDefinition()
9760                                    ? TPC_FriendFunctionTemplateDefinition
9761                                    : TPC_FriendFunctionTemplate)
9762                               : (D.getCXXScopeSpec().isSet() &&
9763                                  DC && DC->isRecord() &&
9764                                  DC->isDependentContext())
9765                                   ? TPC_ClassTemplateMember
9766                                   : TPC_FunctionTemplate);
9767     }
9768 
9769     if (NewFD->isInvalidDecl()) {
9770       // Ignore all the rest of this.
9771     } else if (!D.isRedeclaration()) {
9772       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9773                                        AddToScope };
9774       // Fake up an access specifier if it's supposed to be a class member.
9775       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9776         NewFD->setAccess(AS_public);
9777 
9778       // Qualified decls generally require a previous declaration.
9779       if (D.getCXXScopeSpec().isSet()) {
9780         // ...with the major exception of templated-scope or
9781         // dependent-scope friend declarations.
9782 
9783         // TODO: we currently also suppress this check in dependent
9784         // contexts because (1) the parameter depth will be off when
9785         // matching friend templates and (2) we might actually be
9786         // selecting a friend based on a dependent factor.  But there
9787         // are situations where these conditions don't apply and we
9788         // can actually do this check immediately.
9789         //
9790         // Unless the scope is dependent, it's always an error if qualified
9791         // redeclaration lookup found nothing at all. Diagnose that now;
9792         // nothing will diagnose that error later.
9793         if (isFriend &&
9794             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9795              (!Previous.empty() && CurContext->isDependentContext()))) {
9796           // ignore these
9797         } else if (NewFD->isCPUDispatchMultiVersion() ||
9798                    NewFD->isCPUSpecificMultiVersion()) {
9799           // ignore this, we allow the redeclaration behavior here to create new
9800           // versions of the function.
9801         } else {
9802           // The user tried to provide an out-of-line definition for a
9803           // function that is a member of a class or namespace, but there
9804           // was no such member function declared (C++ [class.mfct]p2,
9805           // C++ [namespace.memdef]p2). For example:
9806           //
9807           // class X {
9808           //   void f() const;
9809           // };
9810           //
9811           // void X::f() { } // ill-formed
9812           //
9813           // Complain about this problem, and attempt to suggest close
9814           // matches (e.g., those that differ only in cv-qualifiers and
9815           // whether the parameter types are references).
9816 
9817           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9818                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9819             AddToScope = ExtraArgs.AddToScope;
9820             return Result;
9821           }
9822         }
9823 
9824         // Unqualified local friend declarations are required to resolve
9825         // to something.
9826       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9827         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9828                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9829           AddToScope = ExtraArgs.AddToScope;
9830           return Result;
9831         }
9832       }
9833     } else if (!D.isFunctionDefinition() &&
9834                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9835                !isFriend && !isFunctionTemplateSpecialization &&
9836                !isMemberSpecialization) {
9837       // An out-of-line member function declaration must also be a
9838       // definition (C++ [class.mfct]p2).
9839       // Note that this is not the case for explicit specializations of
9840       // function templates or member functions of class templates, per
9841       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9842       // extension for compatibility with old SWIG code which likes to
9843       // generate them.
9844       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9845         << D.getCXXScopeSpec().getRange();
9846     }
9847   }
9848 
9849   // If this is the first declaration of a library builtin function, add
9850   // attributes as appropriate.
9851   if (!D.isRedeclaration() &&
9852       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9853     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9854       if (unsigned BuiltinID = II->getBuiltinID()) {
9855         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9856           // Validate the type matches unless this builtin is specified as
9857           // matching regardless of its declared type.
9858           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9859             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9860           } else {
9861             ASTContext::GetBuiltinTypeError Error;
9862             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9863             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9864 
9865             if (!Error && !BuiltinType.isNull() &&
9866                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9867                     NewFD->getType(), BuiltinType))
9868               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9869           }
9870         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9871                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9872           // FIXME: We should consider this a builtin only in the std namespace.
9873           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9874         }
9875       }
9876     }
9877   }
9878 
9879   ProcessPragmaWeak(S, NewFD);
9880   checkAttributesAfterMerging(*this, *NewFD);
9881 
9882   AddKnownFunctionAttributes(NewFD);
9883 
9884   if (NewFD->hasAttr<OverloadableAttr>() &&
9885       !NewFD->getType()->getAs<FunctionProtoType>()) {
9886     Diag(NewFD->getLocation(),
9887          diag::err_attribute_overloadable_no_prototype)
9888       << NewFD;
9889 
9890     // Turn this into a variadic function with no parameters.
9891     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9892     FunctionProtoType::ExtProtoInfo EPI(
9893         Context.getDefaultCallingConvention(true, false));
9894     EPI.Variadic = true;
9895     EPI.ExtInfo = FT->getExtInfo();
9896 
9897     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9898     NewFD->setType(R);
9899   }
9900 
9901   // If there's a #pragma GCC visibility in scope, and this isn't a class
9902   // member, set the visibility of this function.
9903   if (!DC->isRecord() && NewFD->isExternallyVisible())
9904     AddPushedVisibilityAttribute(NewFD);
9905 
9906   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9907   // marking the function.
9908   AddCFAuditedAttribute(NewFD);
9909 
9910   // If this is a function definition, check if we have to apply optnone due to
9911   // a pragma.
9912   if(D.isFunctionDefinition())
9913     AddRangeBasedOptnone(NewFD);
9914 
9915   // If this is the first declaration of an extern C variable, update
9916   // the map of such variables.
9917   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9918       isIncompleteDeclExternC(*this, NewFD))
9919     RegisterLocallyScopedExternCDecl(NewFD, S);
9920 
9921   // Set this FunctionDecl's range up to the right paren.
9922   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9923 
9924   if (D.isRedeclaration() && !Previous.empty()) {
9925     NamedDecl *Prev = Previous.getRepresentativeDecl();
9926     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9927                                    isMemberSpecialization ||
9928                                        isFunctionTemplateSpecialization,
9929                                    D.isFunctionDefinition());
9930   }
9931 
9932   if (getLangOpts().CUDA) {
9933     IdentifierInfo *II = NewFD->getIdentifier();
9934     if (II && II->isStr(getCudaConfigureFuncName()) &&
9935         !NewFD->isInvalidDecl() &&
9936         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9937       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9938         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9939             << getCudaConfigureFuncName();
9940       Context.setcudaConfigureCallDecl(NewFD);
9941     }
9942 
9943     // Variadic functions, other than a *declaration* of printf, are not allowed
9944     // in device-side CUDA code, unless someone passed
9945     // -fcuda-allow-variadic-functions.
9946     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9947         (NewFD->hasAttr<CUDADeviceAttr>() ||
9948          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9949         !(II && II->isStr("printf") && NewFD->isExternC() &&
9950           !D.isFunctionDefinition())) {
9951       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9952     }
9953   }
9954 
9955   MarkUnusedFileScopedDecl(NewFD);
9956 
9957 
9958 
9959   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9960     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9961     if ((getLangOpts().OpenCLVersion >= 120)
9962         && (SC == SC_Static)) {
9963       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9964       D.setInvalidType();
9965     }
9966 
9967     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9968     if (!NewFD->getReturnType()->isVoidType()) {
9969       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9970       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9971           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9972                                 : FixItHint());
9973       D.setInvalidType();
9974     }
9975 
9976     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9977     for (auto Param : NewFD->parameters())
9978       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9979 
9980     if (getLangOpts().OpenCLCPlusPlus) {
9981       if (DC->isRecord()) {
9982         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9983         D.setInvalidType();
9984       }
9985       if (FunctionTemplate) {
9986         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9987         D.setInvalidType();
9988       }
9989     }
9990   }
9991 
9992   if (getLangOpts().CPlusPlus) {
9993     if (FunctionTemplate) {
9994       if (NewFD->isInvalidDecl())
9995         FunctionTemplate->setInvalidDecl();
9996       return FunctionTemplate;
9997     }
9998 
9999     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10000       CompleteMemberSpecialization(NewFD, Previous);
10001   }
10002 
10003   for (const ParmVarDecl *Param : NewFD->parameters()) {
10004     QualType PT = Param->getType();
10005 
10006     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10007     // types.
10008     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10009       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10010         QualType ElemTy = PipeTy->getElementType();
10011           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10012             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10013             D.setInvalidType();
10014           }
10015       }
10016     }
10017   }
10018 
10019   // Here we have an function template explicit specialization at class scope.
10020   // The actual specialization will be postponed to template instatiation
10021   // time via the ClassScopeFunctionSpecializationDecl node.
10022   if (isDependentClassScopeExplicitSpecialization) {
10023     ClassScopeFunctionSpecializationDecl *NewSpec =
10024                          ClassScopeFunctionSpecializationDecl::Create(
10025                                 Context, CurContext, NewFD->getLocation(),
10026                                 cast<CXXMethodDecl>(NewFD),
10027                                 HasExplicitTemplateArgs, TemplateArgs);
10028     CurContext->addDecl(NewSpec);
10029     AddToScope = false;
10030   }
10031 
10032   // Diagnose availability attributes. Availability cannot be used on functions
10033   // that are run during load/unload.
10034   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10035     if (NewFD->hasAttr<ConstructorAttr>()) {
10036       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10037           << 1;
10038       NewFD->dropAttr<AvailabilityAttr>();
10039     }
10040     if (NewFD->hasAttr<DestructorAttr>()) {
10041       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10042           << 2;
10043       NewFD->dropAttr<AvailabilityAttr>();
10044     }
10045   }
10046 
10047   // Diagnose no_builtin attribute on function declaration that are not a
10048   // definition.
10049   // FIXME: We should really be doing this in
10050   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10051   // the FunctionDecl and at this point of the code
10052   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10053   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10054   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10055     switch (D.getFunctionDefinitionKind()) {
10056     case FunctionDefinitionKind::Defaulted:
10057     case FunctionDefinitionKind::Deleted:
10058       Diag(NBA->getLocation(),
10059            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10060           << NBA->getSpelling();
10061       break;
10062     case FunctionDefinitionKind::Declaration:
10063       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10064           << NBA->getSpelling();
10065       break;
10066     case FunctionDefinitionKind::Definition:
10067       break;
10068     }
10069 
10070   return NewFD;
10071 }
10072 
10073 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10074 /// when __declspec(code_seg) "is applied to a class, all member functions of
10075 /// the class and nested classes -- this includes compiler-generated special
10076 /// member functions -- are put in the specified segment."
10077 /// The actual behavior is a little more complicated. The Microsoft compiler
10078 /// won't check outer classes if there is an active value from #pragma code_seg.
10079 /// The CodeSeg is always applied from the direct parent but only from outer
10080 /// classes when the #pragma code_seg stack is empty. See:
10081 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10082 /// available since MS has removed the page.
10083 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10084   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10085   if (!Method)
10086     return nullptr;
10087   const CXXRecordDecl *Parent = Method->getParent();
10088   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10089     Attr *NewAttr = SAttr->clone(S.getASTContext());
10090     NewAttr->setImplicit(true);
10091     return NewAttr;
10092   }
10093 
10094   // The Microsoft compiler won't check outer classes for the CodeSeg
10095   // when the #pragma code_seg stack is active.
10096   if (S.CodeSegStack.CurrentValue)
10097    return nullptr;
10098 
10099   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10100     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10101       Attr *NewAttr = SAttr->clone(S.getASTContext());
10102       NewAttr->setImplicit(true);
10103       return NewAttr;
10104     }
10105   }
10106   return nullptr;
10107 }
10108 
10109 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10110 /// containing class. Otherwise it will return implicit SectionAttr if the
10111 /// function is a definition and there is an active value on CodeSegStack
10112 /// (from the current #pragma code-seg value).
10113 ///
10114 /// \param FD Function being declared.
10115 /// \param IsDefinition Whether it is a definition or just a declarartion.
10116 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10117 ///          nullptr if no attribute should be added.
10118 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10119                                                        bool IsDefinition) {
10120   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10121     return A;
10122   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10123       CodeSegStack.CurrentValue)
10124     return SectionAttr::CreateImplicit(
10125         getASTContext(), CodeSegStack.CurrentValue->getString(),
10126         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10127         SectionAttr::Declspec_allocate);
10128   return nullptr;
10129 }
10130 
10131 /// Determines if we can perform a correct type check for \p D as a
10132 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10133 /// best-effort check.
10134 ///
10135 /// \param NewD The new declaration.
10136 /// \param OldD The old declaration.
10137 /// \param NewT The portion of the type of the new declaration to check.
10138 /// \param OldT The portion of the type of the old declaration to check.
10139 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10140                                           QualType NewT, QualType OldT) {
10141   if (!NewD->getLexicalDeclContext()->isDependentContext())
10142     return true;
10143 
10144   // For dependently-typed local extern declarations and friends, we can't
10145   // perform a correct type check in general until instantiation:
10146   //
10147   //   int f();
10148   //   template<typename T> void g() { T f(); }
10149   //
10150   // (valid if g() is only instantiated with T = int).
10151   if (NewT->isDependentType() &&
10152       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10153     return false;
10154 
10155   // Similarly, if the previous declaration was a dependent local extern
10156   // declaration, we don't really know its type yet.
10157   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10158     return false;
10159 
10160   return true;
10161 }
10162 
10163 /// Checks if the new declaration declared in dependent context must be
10164 /// put in the same redeclaration chain as the specified declaration.
10165 ///
10166 /// \param D Declaration that is checked.
10167 /// \param PrevDecl Previous declaration found with proper lookup method for the
10168 ///                 same declaration name.
10169 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10170 ///          belongs to.
10171 ///
10172 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10173   if (!D->getLexicalDeclContext()->isDependentContext())
10174     return true;
10175 
10176   // Don't chain dependent friend function definitions until instantiation, to
10177   // permit cases like
10178   //
10179   //   void func();
10180   //   template<typename T> class C1 { friend void func() {} };
10181   //   template<typename T> class C2 { friend void func() {} };
10182   //
10183   // ... which is valid if only one of C1 and C2 is ever instantiated.
10184   //
10185   // FIXME: This need only apply to function definitions. For now, we proxy
10186   // this by checking for a file-scope function. We do not want this to apply
10187   // to friend declarations nominating member functions, because that gets in
10188   // the way of access checks.
10189   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10190     return false;
10191 
10192   auto *VD = dyn_cast<ValueDecl>(D);
10193   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10194   return !VD || !PrevVD ||
10195          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10196                                         PrevVD->getType());
10197 }
10198 
10199 /// Check the target attribute of the function for MultiVersion
10200 /// validity.
10201 ///
10202 /// Returns true if there was an error, false otherwise.
10203 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10204   const auto *TA = FD->getAttr<TargetAttr>();
10205   assert(TA && "MultiVersion Candidate requires a target attribute");
10206   ParsedTargetAttr ParseInfo = TA->parse();
10207   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10208   enum ErrType { Feature = 0, Architecture = 1 };
10209 
10210   if (!ParseInfo.Architecture.empty() &&
10211       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10212     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10213         << Architecture << ParseInfo.Architecture;
10214     return true;
10215   }
10216 
10217   for (const auto &Feat : ParseInfo.Features) {
10218     auto BareFeat = StringRef{Feat}.substr(1);
10219     if (Feat[0] == '-') {
10220       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10221           << Feature << ("no-" + BareFeat).str();
10222       return true;
10223     }
10224 
10225     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10226         !TargetInfo.isValidFeatureName(BareFeat)) {
10227       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10228           << Feature << BareFeat;
10229       return true;
10230     }
10231   }
10232   return false;
10233 }
10234 
10235 // Provide a white-list of attributes that are allowed to be combined with
10236 // multiversion functions.
10237 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10238                                            MultiVersionKind MVType) {
10239   // Note: this list/diagnosis must match the list in
10240   // checkMultiversionAttributesAllSame.
10241   switch (Kind) {
10242   default:
10243     return false;
10244   case attr::Used:
10245     return MVType == MultiVersionKind::Target;
10246   case attr::NonNull:
10247   case attr::NoThrow:
10248     return true;
10249   }
10250 }
10251 
10252 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10253                                                  const FunctionDecl *FD,
10254                                                  const FunctionDecl *CausedFD,
10255                                                  MultiVersionKind MVType) {
10256   bool IsCPUSpecificCPUDispatchMVType =
10257       MVType == MultiVersionKind::CPUDispatch ||
10258       MVType == MultiVersionKind::CPUSpecific;
10259   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10260                             Sema &S, const Attr *A) {
10261     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10262         << IsCPUSpecificCPUDispatchMVType << A;
10263     if (CausedFD)
10264       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10265     return true;
10266   };
10267 
10268   for (const Attr *A : FD->attrs()) {
10269     switch (A->getKind()) {
10270     case attr::CPUDispatch:
10271     case attr::CPUSpecific:
10272       if (MVType != MultiVersionKind::CPUDispatch &&
10273           MVType != MultiVersionKind::CPUSpecific)
10274         return Diagnose(S, A);
10275       break;
10276     case attr::Target:
10277       if (MVType != MultiVersionKind::Target)
10278         return Diagnose(S, A);
10279       break;
10280     default:
10281       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10282         return Diagnose(S, A);
10283       break;
10284     }
10285   }
10286   return false;
10287 }
10288 
10289 bool Sema::areMultiversionVariantFunctionsCompatible(
10290     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10291     const PartialDiagnostic &NoProtoDiagID,
10292     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10293     const PartialDiagnosticAt &NoSupportDiagIDAt,
10294     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10295     bool ConstexprSupported, bool CLinkageMayDiffer) {
10296   enum DoesntSupport {
10297     FuncTemplates = 0,
10298     VirtFuncs = 1,
10299     DeducedReturn = 2,
10300     Constructors = 3,
10301     Destructors = 4,
10302     DeletedFuncs = 5,
10303     DefaultedFuncs = 6,
10304     ConstexprFuncs = 7,
10305     ConstevalFuncs = 8,
10306   };
10307   enum Different {
10308     CallingConv = 0,
10309     ReturnType = 1,
10310     ConstexprSpec = 2,
10311     InlineSpec = 3,
10312     StorageClass = 4,
10313     Linkage = 5,
10314   };
10315 
10316   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10317       !OldFD->getType()->getAs<FunctionProtoType>()) {
10318     Diag(OldFD->getLocation(), NoProtoDiagID);
10319     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10320     return true;
10321   }
10322 
10323   if (NoProtoDiagID.getDiagID() != 0 &&
10324       !NewFD->getType()->getAs<FunctionProtoType>())
10325     return Diag(NewFD->getLocation(), NoProtoDiagID);
10326 
10327   if (!TemplatesSupported &&
10328       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10329     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10330            << FuncTemplates;
10331 
10332   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10333     if (NewCXXFD->isVirtual())
10334       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10335              << VirtFuncs;
10336 
10337     if (isa<CXXConstructorDecl>(NewCXXFD))
10338       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10339              << Constructors;
10340 
10341     if (isa<CXXDestructorDecl>(NewCXXFD))
10342       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10343              << Destructors;
10344   }
10345 
10346   if (NewFD->isDeleted())
10347     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10348            << DeletedFuncs;
10349 
10350   if (NewFD->isDefaulted())
10351     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10352            << DefaultedFuncs;
10353 
10354   if (!ConstexprSupported && NewFD->isConstexpr())
10355     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10356            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10357 
10358   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10359   const auto *NewType = cast<FunctionType>(NewQType);
10360   QualType NewReturnType = NewType->getReturnType();
10361 
10362   if (NewReturnType->isUndeducedType())
10363     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10364            << DeducedReturn;
10365 
10366   // Ensure the return type is identical.
10367   if (OldFD) {
10368     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10369     const auto *OldType = cast<FunctionType>(OldQType);
10370     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10371     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10372 
10373     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10374       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10375 
10376     QualType OldReturnType = OldType->getReturnType();
10377 
10378     if (OldReturnType != NewReturnType)
10379       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10380 
10381     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10382       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10383 
10384     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10385       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10386 
10387     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10388       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10389 
10390     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10391       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10392 
10393     if (CheckEquivalentExceptionSpec(
10394             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10395             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10396       return true;
10397   }
10398   return false;
10399 }
10400 
10401 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10402                                              const FunctionDecl *NewFD,
10403                                              bool CausesMV,
10404                                              MultiVersionKind MVType) {
10405   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10406     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10407     if (OldFD)
10408       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10409     return true;
10410   }
10411 
10412   bool IsCPUSpecificCPUDispatchMVType =
10413       MVType == MultiVersionKind::CPUDispatch ||
10414       MVType == MultiVersionKind::CPUSpecific;
10415 
10416   if (CausesMV && OldFD &&
10417       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10418     return true;
10419 
10420   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10421     return true;
10422 
10423   // Only allow transition to MultiVersion if it hasn't been used.
10424   if (OldFD && CausesMV && OldFD->isUsed(false))
10425     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10426 
10427   return S.areMultiversionVariantFunctionsCompatible(
10428       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10429       PartialDiagnosticAt(NewFD->getLocation(),
10430                           S.PDiag(diag::note_multiversioning_caused_here)),
10431       PartialDiagnosticAt(NewFD->getLocation(),
10432                           S.PDiag(diag::err_multiversion_doesnt_support)
10433                               << IsCPUSpecificCPUDispatchMVType),
10434       PartialDiagnosticAt(NewFD->getLocation(),
10435                           S.PDiag(diag::err_multiversion_diff)),
10436       /*TemplatesSupported=*/false,
10437       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10438       /*CLinkageMayDiffer=*/false);
10439 }
10440 
10441 /// Check the validity of a multiversion function declaration that is the
10442 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10443 ///
10444 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10445 ///
10446 /// Returns true if there was an error, false otherwise.
10447 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10448                                            MultiVersionKind MVType,
10449                                            const TargetAttr *TA) {
10450   assert(MVType != MultiVersionKind::None &&
10451          "Function lacks multiversion attribute");
10452 
10453   // Target only causes MV if it is default, otherwise this is a normal
10454   // function.
10455   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10456     return false;
10457 
10458   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10459     FD->setInvalidDecl();
10460     return true;
10461   }
10462 
10463   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10464     FD->setInvalidDecl();
10465     return true;
10466   }
10467 
10468   FD->setIsMultiVersion();
10469   return false;
10470 }
10471 
10472 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10473   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10474     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10475       return true;
10476   }
10477 
10478   return false;
10479 }
10480 
10481 static bool CheckTargetCausesMultiVersioning(
10482     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10483     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10484     LookupResult &Previous) {
10485   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10486   ParsedTargetAttr NewParsed = NewTA->parse();
10487   // Sort order doesn't matter, it just needs to be consistent.
10488   llvm::sort(NewParsed.Features);
10489 
10490   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10491   // to change, this is a simple redeclaration.
10492   if (!NewTA->isDefaultVersion() &&
10493       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10494     return false;
10495 
10496   // Otherwise, this decl causes MultiVersioning.
10497   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10498     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10499     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10500     NewFD->setInvalidDecl();
10501     return true;
10502   }
10503 
10504   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10505                                        MultiVersionKind::Target)) {
10506     NewFD->setInvalidDecl();
10507     return true;
10508   }
10509 
10510   if (CheckMultiVersionValue(S, NewFD)) {
10511     NewFD->setInvalidDecl();
10512     return true;
10513   }
10514 
10515   // If this is 'default', permit the forward declaration.
10516   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10517     Redeclaration = true;
10518     OldDecl = OldFD;
10519     OldFD->setIsMultiVersion();
10520     NewFD->setIsMultiVersion();
10521     return false;
10522   }
10523 
10524   if (CheckMultiVersionValue(S, OldFD)) {
10525     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10526     NewFD->setInvalidDecl();
10527     return true;
10528   }
10529 
10530   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10531 
10532   if (OldParsed == NewParsed) {
10533     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10534     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10535     NewFD->setInvalidDecl();
10536     return true;
10537   }
10538 
10539   for (const auto *FD : OldFD->redecls()) {
10540     const auto *CurTA = FD->getAttr<TargetAttr>();
10541     // We allow forward declarations before ANY multiversioning attributes, but
10542     // nothing after the fact.
10543     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10544         (!CurTA || CurTA->isInherited())) {
10545       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10546           << 0;
10547       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10548       NewFD->setInvalidDecl();
10549       return true;
10550     }
10551   }
10552 
10553   OldFD->setIsMultiVersion();
10554   NewFD->setIsMultiVersion();
10555   Redeclaration = false;
10556   MergeTypeWithPrevious = false;
10557   OldDecl = nullptr;
10558   Previous.clear();
10559   return false;
10560 }
10561 
10562 /// Check the validity of a new function declaration being added to an existing
10563 /// multiversioned declaration collection.
10564 static bool CheckMultiVersionAdditionalDecl(
10565     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10566     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10567     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10568     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10569     LookupResult &Previous) {
10570 
10571   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10572   // Disallow mixing of multiversioning types.
10573   if ((OldMVType == MultiVersionKind::Target &&
10574        NewMVType != MultiVersionKind::Target) ||
10575       (NewMVType == MultiVersionKind::Target &&
10576        OldMVType != MultiVersionKind::Target)) {
10577     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10578     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10579     NewFD->setInvalidDecl();
10580     return true;
10581   }
10582 
10583   ParsedTargetAttr NewParsed;
10584   if (NewTA) {
10585     NewParsed = NewTA->parse();
10586     llvm::sort(NewParsed.Features);
10587   }
10588 
10589   bool UseMemberUsingDeclRules =
10590       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10591 
10592   // Next, check ALL non-overloads to see if this is a redeclaration of a
10593   // previous member of the MultiVersion set.
10594   for (NamedDecl *ND : Previous) {
10595     FunctionDecl *CurFD = ND->getAsFunction();
10596     if (!CurFD)
10597       continue;
10598     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10599       continue;
10600 
10601     if (NewMVType == MultiVersionKind::Target) {
10602       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10603       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10604         NewFD->setIsMultiVersion();
10605         Redeclaration = true;
10606         OldDecl = ND;
10607         return false;
10608       }
10609 
10610       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10611       if (CurParsed == NewParsed) {
10612         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10613         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10614         NewFD->setInvalidDecl();
10615         return true;
10616       }
10617     } else {
10618       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10619       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10620       // Handle CPUDispatch/CPUSpecific versions.
10621       // Only 1 CPUDispatch function is allowed, this will make it go through
10622       // the redeclaration errors.
10623       if (NewMVType == MultiVersionKind::CPUDispatch &&
10624           CurFD->hasAttr<CPUDispatchAttr>()) {
10625         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10626             std::equal(
10627                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10628                 NewCPUDisp->cpus_begin(),
10629                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10630                   return Cur->getName() == New->getName();
10631                 })) {
10632           NewFD->setIsMultiVersion();
10633           Redeclaration = true;
10634           OldDecl = ND;
10635           return false;
10636         }
10637 
10638         // If the declarations don't match, this is an error condition.
10639         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10640         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10641         NewFD->setInvalidDecl();
10642         return true;
10643       }
10644       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10645 
10646         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10647             std::equal(
10648                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10649                 NewCPUSpec->cpus_begin(),
10650                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10651                   return Cur->getName() == New->getName();
10652                 })) {
10653           NewFD->setIsMultiVersion();
10654           Redeclaration = true;
10655           OldDecl = ND;
10656           return false;
10657         }
10658 
10659         // Only 1 version of CPUSpecific is allowed for each CPU.
10660         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10661           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10662             if (CurII == NewII) {
10663               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10664                   << NewII;
10665               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10666               NewFD->setInvalidDecl();
10667               return true;
10668             }
10669           }
10670         }
10671       }
10672       // If the two decls aren't the same MVType, there is no possible error
10673       // condition.
10674     }
10675   }
10676 
10677   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10678   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10679   // handled in the attribute adding step.
10680   if (NewMVType == MultiVersionKind::Target &&
10681       CheckMultiVersionValue(S, NewFD)) {
10682     NewFD->setInvalidDecl();
10683     return true;
10684   }
10685 
10686   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10687                                        !OldFD->isMultiVersion(), NewMVType)) {
10688     NewFD->setInvalidDecl();
10689     return true;
10690   }
10691 
10692   // Permit forward declarations in the case where these two are compatible.
10693   if (!OldFD->isMultiVersion()) {
10694     OldFD->setIsMultiVersion();
10695     NewFD->setIsMultiVersion();
10696     Redeclaration = true;
10697     OldDecl = OldFD;
10698     return false;
10699   }
10700 
10701   NewFD->setIsMultiVersion();
10702   Redeclaration = false;
10703   MergeTypeWithPrevious = false;
10704   OldDecl = nullptr;
10705   Previous.clear();
10706   return false;
10707 }
10708 
10709 
10710 /// Check the validity of a mulitversion function declaration.
10711 /// Also sets the multiversion'ness' of the function itself.
10712 ///
10713 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10714 ///
10715 /// Returns true if there was an error, false otherwise.
10716 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10717                                       bool &Redeclaration, NamedDecl *&OldDecl,
10718                                       bool &MergeTypeWithPrevious,
10719                                       LookupResult &Previous) {
10720   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10721   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10722   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10723 
10724   // Mixing Multiversioning types is prohibited.
10725   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10726       (NewCPUDisp && NewCPUSpec)) {
10727     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10728     NewFD->setInvalidDecl();
10729     return true;
10730   }
10731 
10732   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10733 
10734   // Main isn't allowed to become a multiversion function, however it IS
10735   // permitted to have 'main' be marked with the 'target' optimization hint.
10736   if (NewFD->isMain()) {
10737     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10738         MVType == MultiVersionKind::CPUDispatch ||
10739         MVType == MultiVersionKind::CPUSpecific) {
10740       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10741       NewFD->setInvalidDecl();
10742       return true;
10743     }
10744     return false;
10745   }
10746 
10747   if (!OldDecl || !OldDecl->getAsFunction() ||
10748       OldDecl->getDeclContext()->getRedeclContext() !=
10749           NewFD->getDeclContext()->getRedeclContext()) {
10750     // If there's no previous declaration, AND this isn't attempting to cause
10751     // multiversioning, this isn't an error condition.
10752     if (MVType == MultiVersionKind::None)
10753       return false;
10754     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10755   }
10756 
10757   FunctionDecl *OldFD = OldDecl->getAsFunction();
10758 
10759   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10760     return false;
10761 
10762   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10763     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10764         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10765     NewFD->setInvalidDecl();
10766     return true;
10767   }
10768 
10769   // Handle the target potentially causes multiversioning case.
10770   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10771     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10772                                             Redeclaration, OldDecl,
10773                                             MergeTypeWithPrevious, Previous);
10774 
10775   // At this point, we have a multiversion function decl (in OldFD) AND an
10776   // appropriate attribute in the current function decl.  Resolve that these are
10777   // still compatible with previous declarations.
10778   return CheckMultiVersionAdditionalDecl(
10779       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10780       OldDecl, MergeTypeWithPrevious, Previous);
10781 }
10782 
10783 /// Perform semantic checking of a new function declaration.
10784 ///
10785 /// Performs semantic analysis of the new function declaration
10786 /// NewFD. This routine performs all semantic checking that does not
10787 /// require the actual declarator involved in the declaration, and is
10788 /// used both for the declaration of functions as they are parsed
10789 /// (called via ActOnDeclarator) and for the declaration of functions
10790 /// that have been instantiated via C++ template instantiation (called
10791 /// via InstantiateDecl).
10792 ///
10793 /// \param IsMemberSpecialization whether this new function declaration is
10794 /// a member specialization (that replaces any definition provided by the
10795 /// previous declaration).
10796 ///
10797 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10798 ///
10799 /// \returns true if the function declaration is a redeclaration.
10800 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10801                                     LookupResult &Previous,
10802                                     bool IsMemberSpecialization) {
10803   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10804          "Variably modified return types are not handled here");
10805 
10806   // Determine whether the type of this function should be merged with
10807   // a previous visible declaration. This never happens for functions in C++,
10808   // and always happens in C if the previous declaration was visible.
10809   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10810                                !Previous.isShadowed();
10811 
10812   bool Redeclaration = false;
10813   NamedDecl *OldDecl = nullptr;
10814   bool MayNeedOverloadableChecks = false;
10815 
10816   // Merge or overload the declaration with an existing declaration of
10817   // the same name, if appropriate.
10818   if (!Previous.empty()) {
10819     // Determine whether NewFD is an overload of PrevDecl or
10820     // a declaration that requires merging. If it's an overload,
10821     // there's no more work to do here; we'll just add the new
10822     // function to the scope.
10823     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10824       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10825       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10826         Redeclaration = true;
10827         OldDecl = Candidate;
10828       }
10829     } else {
10830       MayNeedOverloadableChecks = true;
10831       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10832                             /*NewIsUsingDecl*/ false)) {
10833       case Ovl_Match:
10834         Redeclaration = true;
10835         break;
10836 
10837       case Ovl_NonFunction:
10838         Redeclaration = true;
10839         break;
10840 
10841       case Ovl_Overload:
10842         Redeclaration = false;
10843         break;
10844       }
10845     }
10846   }
10847 
10848   // Check for a previous extern "C" declaration with this name.
10849   if (!Redeclaration &&
10850       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10851     if (!Previous.empty()) {
10852       // This is an extern "C" declaration with the same name as a previous
10853       // declaration, and thus redeclares that entity...
10854       Redeclaration = true;
10855       OldDecl = Previous.getFoundDecl();
10856       MergeTypeWithPrevious = false;
10857 
10858       // ... except in the presence of __attribute__((overloadable)).
10859       if (OldDecl->hasAttr<OverloadableAttr>() ||
10860           NewFD->hasAttr<OverloadableAttr>()) {
10861         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10862           MayNeedOverloadableChecks = true;
10863           Redeclaration = false;
10864           OldDecl = nullptr;
10865         }
10866       }
10867     }
10868   }
10869 
10870   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10871                                 MergeTypeWithPrevious, Previous))
10872     return Redeclaration;
10873 
10874   // PPC MMA non-pointer types are not allowed as function return types.
10875   if (Context.getTargetInfo().getTriple().isPPC64() &&
10876       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10877     NewFD->setInvalidDecl();
10878   }
10879 
10880   // C++11 [dcl.constexpr]p8:
10881   //   A constexpr specifier for a non-static member function that is not
10882   //   a constructor declares that member function to be const.
10883   //
10884   // This needs to be delayed until we know whether this is an out-of-line
10885   // definition of a static member function.
10886   //
10887   // This rule is not present in C++1y, so we produce a backwards
10888   // compatibility warning whenever it happens in C++11.
10889   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10890   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10891       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10892       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10893     CXXMethodDecl *OldMD = nullptr;
10894     if (OldDecl)
10895       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10896     if (!OldMD || !OldMD->isStatic()) {
10897       const FunctionProtoType *FPT =
10898         MD->getType()->castAs<FunctionProtoType>();
10899       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10900       EPI.TypeQuals.addConst();
10901       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10902                                           FPT->getParamTypes(), EPI));
10903 
10904       // Warn that we did this, if we're not performing template instantiation.
10905       // In that case, we'll have warned already when the template was defined.
10906       if (!inTemplateInstantiation()) {
10907         SourceLocation AddConstLoc;
10908         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10909                 .IgnoreParens().getAs<FunctionTypeLoc>())
10910           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10911 
10912         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10913           << FixItHint::CreateInsertion(AddConstLoc, " const");
10914       }
10915     }
10916   }
10917 
10918   if (Redeclaration) {
10919     // NewFD and OldDecl represent declarations that need to be
10920     // merged.
10921     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10922       NewFD->setInvalidDecl();
10923       return Redeclaration;
10924     }
10925 
10926     Previous.clear();
10927     Previous.addDecl(OldDecl);
10928 
10929     if (FunctionTemplateDecl *OldTemplateDecl =
10930             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10931       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10932       FunctionTemplateDecl *NewTemplateDecl
10933         = NewFD->getDescribedFunctionTemplate();
10934       assert(NewTemplateDecl && "Template/non-template mismatch");
10935 
10936       // The call to MergeFunctionDecl above may have created some state in
10937       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10938       // can add it as a redeclaration.
10939       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10940 
10941       NewFD->setPreviousDeclaration(OldFD);
10942       if (NewFD->isCXXClassMember()) {
10943         NewFD->setAccess(OldTemplateDecl->getAccess());
10944         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10945       }
10946 
10947       // If this is an explicit specialization of a member that is a function
10948       // template, mark it as a member specialization.
10949       if (IsMemberSpecialization &&
10950           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10951         NewTemplateDecl->setMemberSpecialization();
10952         assert(OldTemplateDecl->isMemberSpecialization());
10953         // Explicit specializations of a member template do not inherit deleted
10954         // status from the parent member template that they are specializing.
10955         if (OldFD->isDeleted()) {
10956           // FIXME: This assert will not hold in the presence of modules.
10957           assert(OldFD->getCanonicalDecl() == OldFD);
10958           // FIXME: We need an update record for this AST mutation.
10959           OldFD->setDeletedAsWritten(false);
10960         }
10961       }
10962 
10963     } else {
10964       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10965         auto *OldFD = cast<FunctionDecl>(OldDecl);
10966         // This needs to happen first so that 'inline' propagates.
10967         NewFD->setPreviousDeclaration(OldFD);
10968         if (NewFD->isCXXClassMember())
10969           NewFD->setAccess(OldFD->getAccess());
10970       }
10971     }
10972   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10973              !NewFD->getAttr<OverloadableAttr>()) {
10974     assert((Previous.empty() ||
10975             llvm::any_of(Previous,
10976                          [](const NamedDecl *ND) {
10977                            return ND->hasAttr<OverloadableAttr>();
10978                          })) &&
10979            "Non-redecls shouldn't happen without overloadable present");
10980 
10981     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10982       const auto *FD = dyn_cast<FunctionDecl>(ND);
10983       return FD && !FD->hasAttr<OverloadableAttr>();
10984     });
10985 
10986     if (OtherUnmarkedIter != Previous.end()) {
10987       Diag(NewFD->getLocation(),
10988            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10989       Diag((*OtherUnmarkedIter)->getLocation(),
10990            diag::note_attribute_overloadable_prev_overload)
10991           << false;
10992 
10993       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10994     }
10995   }
10996 
10997   if (LangOpts.OpenMP)
10998     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10999 
11000   // Semantic checking for this function declaration (in isolation).
11001 
11002   if (getLangOpts().CPlusPlus) {
11003     // C++-specific checks.
11004     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11005       CheckConstructor(Constructor);
11006     } else if (CXXDestructorDecl *Destructor =
11007                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11008       CXXRecordDecl *Record = Destructor->getParent();
11009       QualType ClassType = Context.getTypeDeclType(Record);
11010 
11011       // FIXME: Shouldn't we be able to perform this check even when the class
11012       // type is dependent? Both gcc and edg can handle that.
11013       if (!ClassType->isDependentType()) {
11014         DeclarationName Name
11015           = Context.DeclarationNames.getCXXDestructorName(
11016                                         Context.getCanonicalType(ClassType));
11017         if (NewFD->getDeclName() != Name) {
11018           Diag(NewFD->getLocation(), diag::err_destructor_name);
11019           NewFD->setInvalidDecl();
11020           return Redeclaration;
11021         }
11022       }
11023     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11024       if (auto *TD = Guide->getDescribedFunctionTemplate())
11025         CheckDeductionGuideTemplate(TD);
11026 
11027       // A deduction guide is not on the list of entities that can be
11028       // explicitly specialized.
11029       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11030         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11031             << /*explicit specialization*/ 1;
11032     }
11033 
11034     // Find any virtual functions that this function overrides.
11035     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11036       if (!Method->isFunctionTemplateSpecialization() &&
11037           !Method->getDescribedFunctionTemplate() &&
11038           Method->isCanonicalDecl()) {
11039         AddOverriddenMethods(Method->getParent(), Method);
11040       }
11041       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11042         // C++2a [class.virtual]p6
11043         // A virtual method shall not have a requires-clause.
11044         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11045              diag::err_constrained_virtual_method);
11046 
11047       if (Method->isStatic())
11048         checkThisInStaticMemberFunctionType(Method);
11049     }
11050 
11051     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11052       ActOnConversionDeclarator(Conversion);
11053 
11054     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11055     if (NewFD->isOverloadedOperator() &&
11056         CheckOverloadedOperatorDeclaration(NewFD)) {
11057       NewFD->setInvalidDecl();
11058       return Redeclaration;
11059     }
11060 
11061     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11062     if (NewFD->getLiteralIdentifier() &&
11063         CheckLiteralOperatorDeclaration(NewFD)) {
11064       NewFD->setInvalidDecl();
11065       return Redeclaration;
11066     }
11067 
11068     // In C++, check default arguments now that we have merged decls. Unless
11069     // the lexical context is the class, because in this case this is done
11070     // during delayed parsing anyway.
11071     if (!CurContext->isRecord())
11072       CheckCXXDefaultArguments(NewFD);
11073 
11074     // If this function is declared as being extern "C", then check to see if
11075     // the function returns a UDT (class, struct, or union type) that is not C
11076     // compatible, and if it does, warn the user.
11077     // But, issue any diagnostic on the first declaration only.
11078     if (Previous.empty() && NewFD->isExternC()) {
11079       QualType R = NewFD->getReturnType();
11080       if (R->isIncompleteType() && !R->isVoidType())
11081         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11082             << NewFD << R;
11083       else if (!R.isPODType(Context) && !R->isVoidType() &&
11084                !R->isObjCObjectPointerType())
11085         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11086     }
11087 
11088     // C++1z [dcl.fct]p6:
11089     //   [...] whether the function has a non-throwing exception-specification
11090     //   [is] part of the function type
11091     //
11092     // This results in an ABI break between C++14 and C++17 for functions whose
11093     // declared type includes an exception-specification in a parameter or
11094     // return type. (Exception specifications on the function itself are OK in
11095     // most cases, and exception specifications are not permitted in most other
11096     // contexts where they could make it into a mangling.)
11097     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11098       auto HasNoexcept = [&](QualType T) -> bool {
11099         // Strip off declarator chunks that could be between us and a function
11100         // type. We don't need to look far, exception specifications are very
11101         // restricted prior to C++17.
11102         if (auto *RT = T->getAs<ReferenceType>())
11103           T = RT->getPointeeType();
11104         else if (T->isAnyPointerType())
11105           T = T->getPointeeType();
11106         else if (auto *MPT = T->getAs<MemberPointerType>())
11107           T = MPT->getPointeeType();
11108         if (auto *FPT = T->getAs<FunctionProtoType>())
11109           if (FPT->isNothrow())
11110             return true;
11111         return false;
11112       };
11113 
11114       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11115       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11116       for (QualType T : FPT->param_types())
11117         AnyNoexcept |= HasNoexcept(T);
11118       if (AnyNoexcept)
11119         Diag(NewFD->getLocation(),
11120              diag::warn_cxx17_compat_exception_spec_in_signature)
11121             << NewFD;
11122     }
11123 
11124     if (!Redeclaration && LangOpts.CUDA)
11125       checkCUDATargetOverload(NewFD, Previous);
11126   }
11127   return Redeclaration;
11128 }
11129 
11130 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11131   // C++11 [basic.start.main]p3:
11132   //   A program that [...] declares main to be inline, static or
11133   //   constexpr is ill-formed.
11134   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11135   //   appear in a declaration of main.
11136   // static main is not an error under C99, but we should warn about it.
11137   // We accept _Noreturn main as an extension.
11138   if (FD->getStorageClass() == SC_Static)
11139     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11140          ? diag::err_static_main : diag::warn_static_main)
11141       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11142   if (FD->isInlineSpecified())
11143     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11144       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11145   if (DS.isNoreturnSpecified()) {
11146     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11147     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11148     Diag(NoreturnLoc, diag::ext_noreturn_main);
11149     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11150       << FixItHint::CreateRemoval(NoreturnRange);
11151   }
11152   if (FD->isConstexpr()) {
11153     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11154         << FD->isConsteval()
11155         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11156     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11157   }
11158 
11159   if (getLangOpts().OpenCL) {
11160     Diag(FD->getLocation(), diag::err_opencl_no_main)
11161         << FD->hasAttr<OpenCLKernelAttr>();
11162     FD->setInvalidDecl();
11163     return;
11164   }
11165 
11166   QualType T = FD->getType();
11167   assert(T->isFunctionType() && "function decl is not of function type");
11168   const FunctionType* FT = T->castAs<FunctionType>();
11169 
11170   // Set default calling convention for main()
11171   if (FT->getCallConv() != CC_C) {
11172     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11173     FD->setType(QualType(FT, 0));
11174     T = Context.getCanonicalType(FD->getType());
11175   }
11176 
11177   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11178     // In C with GNU extensions we allow main() to have non-integer return
11179     // type, but we should warn about the extension, and we disable the
11180     // implicit-return-zero rule.
11181 
11182     // GCC in C mode accepts qualified 'int'.
11183     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11184       FD->setHasImplicitReturnZero(true);
11185     else {
11186       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11187       SourceRange RTRange = FD->getReturnTypeSourceRange();
11188       if (RTRange.isValid())
11189         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11190             << FixItHint::CreateReplacement(RTRange, "int");
11191     }
11192   } else {
11193     // In C and C++, main magically returns 0 if you fall off the end;
11194     // set the flag which tells us that.
11195     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11196 
11197     // All the standards say that main() should return 'int'.
11198     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11199       FD->setHasImplicitReturnZero(true);
11200     else {
11201       // Otherwise, this is just a flat-out error.
11202       SourceRange RTRange = FD->getReturnTypeSourceRange();
11203       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11204           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11205                                 : FixItHint());
11206       FD->setInvalidDecl(true);
11207     }
11208   }
11209 
11210   // Treat protoless main() as nullary.
11211   if (isa<FunctionNoProtoType>(FT)) return;
11212 
11213   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11214   unsigned nparams = FTP->getNumParams();
11215   assert(FD->getNumParams() == nparams);
11216 
11217   bool HasExtraParameters = (nparams > 3);
11218 
11219   if (FTP->isVariadic()) {
11220     Diag(FD->getLocation(), diag::ext_variadic_main);
11221     // FIXME: if we had information about the location of the ellipsis, we
11222     // could add a FixIt hint to remove it as a parameter.
11223   }
11224 
11225   // Darwin passes an undocumented fourth argument of type char**.  If
11226   // other platforms start sprouting these, the logic below will start
11227   // getting shifty.
11228   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11229     HasExtraParameters = false;
11230 
11231   if (HasExtraParameters) {
11232     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11233     FD->setInvalidDecl(true);
11234     nparams = 3;
11235   }
11236 
11237   // FIXME: a lot of the following diagnostics would be improved
11238   // if we had some location information about types.
11239 
11240   QualType CharPP =
11241     Context.getPointerType(Context.getPointerType(Context.CharTy));
11242   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11243 
11244   for (unsigned i = 0; i < nparams; ++i) {
11245     QualType AT = FTP->getParamType(i);
11246 
11247     bool mismatch = true;
11248 
11249     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11250       mismatch = false;
11251     else if (Expected[i] == CharPP) {
11252       // As an extension, the following forms are okay:
11253       //   char const **
11254       //   char const * const *
11255       //   char * const *
11256 
11257       QualifierCollector qs;
11258       const PointerType* PT;
11259       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11260           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11261           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11262                               Context.CharTy)) {
11263         qs.removeConst();
11264         mismatch = !qs.empty();
11265       }
11266     }
11267 
11268     if (mismatch) {
11269       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11270       // TODO: suggest replacing given type with expected type
11271       FD->setInvalidDecl(true);
11272     }
11273   }
11274 
11275   if (nparams == 1 && !FD->isInvalidDecl()) {
11276     Diag(FD->getLocation(), diag::warn_main_one_arg);
11277   }
11278 
11279   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11280     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11281     FD->setInvalidDecl();
11282   }
11283 }
11284 
11285 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11286 
11287   // Default calling convention for main and wmain is __cdecl
11288   if (FD->getName() == "main" || FD->getName() == "wmain")
11289     return false;
11290 
11291   // Default calling convention for MinGW is __cdecl
11292   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11293   if (T.isWindowsGNUEnvironment())
11294     return false;
11295 
11296   // Default calling convention for WinMain, wWinMain and DllMain
11297   // is __stdcall on 32 bit Windows
11298   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11299     return true;
11300 
11301   return false;
11302 }
11303 
11304 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11305   QualType T = FD->getType();
11306   assert(T->isFunctionType() && "function decl is not of function type");
11307   const FunctionType *FT = T->castAs<FunctionType>();
11308 
11309   // Set an implicit return of 'zero' if the function can return some integral,
11310   // enumeration, pointer or nullptr type.
11311   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11312       FT->getReturnType()->isAnyPointerType() ||
11313       FT->getReturnType()->isNullPtrType())
11314     // DllMain is exempt because a return value of zero means it failed.
11315     if (FD->getName() != "DllMain")
11316       FD->setHasImplicitReturnZero(true);
11317 
11318   // Explicity specified calling conventions are applied to MSVC entry points
11319   if (!hasExplicitCallingConv(T)) {
11320     if (isDefaultStdCall(FD, *this)) {
11321       if (FT->getCallConv() != CC_X86StdCall) {
11322         FT = Context.adjustFunctionType(
11323             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11324         FD->setType(QualType(FT, 0));
11325       }
11326     } else if (FT->getCallConv() != CC_C) {
11327       FT = Context.adjustFunctionType(FT,
11328                                       FT->getExtInfo().withCallingConv(CC_C));
11329       FD->setType(QualType(FT, 0));
11330     }
11331   }
11332 
11333   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11334     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11335     FD->setInvalidDecl();
11336   }
11337 }
11338 
11339 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11340   // FIXME: Need strict checking.  In C89, we need to check for
11341   // any assignment, increment, decrement, function-calls, or
11342   // commas outside of a sizeof.  In C99, it's the same list,
11343   // except that the aforementioned are allowed in unevaluated
11344   // expressions.  Everything else falls under the
11345   // "may accept other forms of constant expressions" exception.
11346   //
11347   // Regular C++ code will not end up here (exceptions: language extensions,
11348   // OpenCL C++ etc), so the constant expression rules there don't matter.
11349   if (Init->isValueDependent()) {
11350     assert(Init->containsErrors() &&
11351            "Dependent code should only occur in error-recovery path.");
11352     return true;
11353   }
11354   const Expr *Culprit;
11355   if (Init->isConstantInitializer(Context, false, &Culprit))
11356     return false;
11357   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11358     << Culprit->getSourceRange();
11359   return true;
11360 }
11361 
11362 namespace {
11363   // Visits an initialization expression to see if OrigDecl is evaluated in
11364   // its own initialization and throws a warning if it does.
11365   class SelfReferenceChecker
11366       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11367     Sema &S;
11368     Decl *OrigDecl;
11369     bool isRecordType;
11370     bool isPODType;
11371     bool isReferenceType;
11372 
11373     bool isInitList;
11374     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11375 
11376   public:
11377     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11378 
11379     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11380                                                     S(S), OrigDecl(OrigDecl) {
11381       isPODType = false;
11382       isRecordType = false;
11383       isReferenceType = false;
11384       isInitList = false;
11385       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11386         isPODType = VD->getType().isPODType(S.Context);
11387         isRecordType = VD->getType()->isRecordType();
11388         isReferenceType = VD->getType()->isReferenceType();
11389       }
11390     }
11391 
11392     // For most expressions, just call the visitor.  For initializer lists,
11393     // track the index of the field being initialized since fields are
11394     // initialized in order allowing use of previously initialized fields.
11395     void CheckExpr(Expr *E) {
11396       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11397       if (!InitList) {
11398         Visit(E);
11399         return;
11400       }
11401 
11402       // Track and increment the index here.
11403       isInitList = true;
11404       InitFieldIndex.push_back(0);
11405       for (auto Child : InitList->children()) {
11406         CheckExpr(cast<Expr>(Child));
11407         ++InitFieldIndex.back();
11408       }
11409       InitFieldIndex.pop_back();
11410     }
11411 
11412     // Returns true if MemberExpr is checked and no further checking is needed.
11413     // Returns false if additional checking is required.
11414     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11415       llvm::SmallVector<FieldDecl*, 4> Fields;
11416       Expr *Base = E;
11417       bool ReferenceField = false;
11418 
11419       // Get the field members used.
11420       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11421         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11422         if (!FD)
11423           return false;
11424         Fields.push_back(FD);
11425         if (FD->getType()->isReferenceType())
11426           ReferenceField = true;
11427         Base = ME->getBase()->IgnoreParenImpCasts();
11428       }
11429 
11430       // Keep checking only if the base Decl is the same.
11431       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11432       if (!DRE || DRE->getDecl() != OrigDecl)
11433         return false;
11434 
11435       // A reference field can be bound to an unininitialized field.
11436       if (CheckReference && !ReferenceField)
11437         return true;
11438 
11439       // Convert FieldDecls to their index number.
11440       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11441       for (const FieldDecl *I : llvm::reverse(Fields))
11442         UsedFieldIndex.push_back(I->getFieldIndex());
11443 
11444       // See if a warning is needed by checking the first difference in index
11445       // numbers.  If field being used has index less than the field being
11446       // initialized, then the use is safe.
11447       for (auto UsedIter = UsedFieldIndex.begin(),
11448                 UsedEnd = UsedFieldIndex.end(),
11449                 OrigIter = InitFieldIndex.begin(),
11450                 OrigEnd = InitFieldIndex.end();
11451            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11452         if (*UsedIter < *OrigIter)
11453           return true;
11454         if (*UsedIter > *OrigIter)
11455           break;
11456       }
11457 
11458       // TODO: Add a different warning which will print the field names.
11459       HandleDeclRefExpr(DRE);
11460       return true;
11461     }
11462 
11463     // For most expressions, the cast is directly above the DeclRefExpr.
11464     // For conditional operators, the cast can be outside the conditional
11465     // operator if both expressions are DeclRefExpr's.
11466     void HandleValue(Expr *E) {
11467       E = E->IgnoreParens();
11468       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11469         HandleDeclRefExpr(DRE);
11470         return;
11471       }
11472 
11473       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11474         Visit(CO->getCond());
11475         HandleValue(CO->getTrueExpr());
11476         HandleValue(CO->getFalseExpr());
11477         return;
11478       }
11479 
11480       if (BinaryConditionalOperator *BCO =
11481               dyn_cast<BinaryConditionalOperator>(E)) {
11482         Visit(BCO->getCond());
11483         HandleValue(BCO->getFalseExpr());
11484         return;
11485       }
11486 
11487       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11488         HandleValue(OVE->getSourceExpr());
11489         return;
11490       }
11491 
11492       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11493         if (BO->getOpcode() == BO_Comma) {
11494           Visit(BO->getLHS());
11495           HandleValue(BO->getRHS());
11496           return;
11497         }
11498       }
11499 
11500       if (isa<MemberExpr>(E)) {
11501         if (isInitList) {
11502           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11503                                       false /*CheckReference*/))
11504             return;
11505         }
11506 
11507         Expr *Base = E->IgnoreParenImpCasts();
11508         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11509           // Check for static member variables and don't warn on them.
11510           if (!isa<FieldDecl>(ME->getMemberDecl()))
11511             return;
11512           Base = ME->getBase()->IgnoreParenImpCasts();
11513         }
11514         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11515           HandleDeclRefExpr(DRE);
11516         return;
11517       }
11518 
11519       Visit(E);
11520     }
11521 
11522     // Reference types not handled in HandleValue are handled here since all
11523     // uses of references are bad, not just r-value uses.
11524     void VisitDeclRefExpr(DeclRefExpr *E) {
11525       if (isReferenceType)
11526         HandleDeclRefExpr(E);
11527     }
11528 
11529     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11530       if (E->getCastKind() == CK_LValueToRValue) {
11531         HandleValue(E->getSubExpr());
11532         return;
11533       }
11534 
11535       Inherited::VisitImplicitCastExpr(E);
11536     }
11537 
11538     void VisitMemberExpr(MemberExpr *E) {
11539       if (isInitList) {
11540         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11541           return;
11542       }
11543 
11544       // Don't warn on arrays since they can be treated as pointers.
11545       if (E->getType()->canDecayToPointerType()) return;
11546 
11547       // Warn when a non-static method call is followed by non-static member
11548       // field accesses, which is followed by a DeclRefExpr.
11549       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11550       bool Warn = (MD && !MD->isStatic());
11551       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11552       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11553         if (!isa<FieldDecl>(ME->getMemberDecl()))
11554           Warn = false;
11555         Base = ME->getBase()->IgnoreParenImpCasts();
11556       }
11557 
11558       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11559         if (Warn)
11560           HandleDeclRefExpr(DRE);
11561         return;
11562       }
11563 
11564       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11565       // Visit that expression.
11566       Visit(Base);
11567     }
11568 
11569     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11570       Expr *Callee = E->getCallee();
11571 
11572       if (isa<UnresolvedLookupExpr>(Callee))
11573         return Inherited::VisitCXXOperatorCallExpr(E);
11574 
11575       Visit(Callee);
11576       for (auto Arg: E->arguments())
11577         HandleValue(Arg->IgnoreParenImpCasts());
11578     }
11579 
11580     void VisitUnaryOperator(UnaryOperator *E) {
11581       // For POD record types, addresses of its own members are well-defined.
11582       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11583           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11584         if (!isPODType)
11585           HandleValue(E->getSubExpr());
11586         return;
11587       }
11588 
11589       if (E->isIncrementDecrementOp()) {
11590         HandleValue(E->getSubExpr());
11591         return;
11592       }
11593 
11594       Inherited::VisitUnaryOperator(E);
11595     }
11596 
11597     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11598 
11599     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11600       if (E->getConstructor()->isCopyConstructor()) {
11601         Expr *ArgExpr = E->getArg(0);
11602         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11603           if (ILE->getNumInits() == 1)
11604             ArgExpr = ILE->getInit(0);
11605         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11606           if (ICE->getCastKind() == CK_NoOp)
11607             ArgExpr = ICE->getSubExpr();
11608         HandleValue(ArgExpr);
11609         return;
11610       }
11611       Inherited::VisitCXXConstructExpr(E);
11612     }
11613 
11614     void VisitCallExpr(CallExpr *E) {
11615       // Treat std::move as a use.
11616       if (E->isCallToStdMove()) {
11617         HandleValue(E->getArg(0));
11618         return;
11619       }
11620 
11621       Inherited::VisitCallExpr(E);
11622     }
11623 
11624     void VisitBinaryOperator(BinaryOperator *E) {
11625       if (E->isCompoundAssignmentOp()) {
11626         HandleValue(E->getLHS());
11627         Visit(E->getRHS());
11628         return;
11629       }
11630 
11631       Inherited::VisitBinaryOperator(E);
11632     }
11633 
11634     // A custom visitor for BinaryConditionalOperator is needed because the
11635     // regular visitor would check the condition and true expression separately
11636     // but both point to the same place giving duplicate diagnostics.
11637     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11638       Visit(E->getCond());
11639       Visit(E->getFalseExpr());
11640     }
11641 
11642     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11643       Decl* ReferenceDecl = DRE->getDecl();
11644       if (OrigDecl != ReferenceDecl) return;
11645       unsigned diag;
11646       if (isReferenceType) {
11647         diag = diag::warn_uninit_self_reference_in_reference_init;
11648       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11649         diag = diag::warn_static_self_reference_in_init;
11650       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11651                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11652                  DRE->getDecl()->getType()->isRecordType()) {
11653         diag = diag::warn_uninit_self_reference_in_init;
11654       } else {
11655         // Local variables will be handled by the CFG analysis.
11656         return;
11657       }
11658 
11659       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11660                             S.PDiag(diag)
11661                                 << DRE->getDecl() << OrigDecl->getLocation()
11662                                 << DRE->getSourceRange());
11663     }
11664   };
11665 
11666   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11667   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11668                                  bool DirectInit) {
11669     // Parameters arguments are occassionially constructed with itself,
11670     // for instance, in recursive functions.  Skip them.
11671     if (isa<ParmVarDecl>(OrigDecl))
11672       return;
11673 
11674     E = E->IgnoreParens();
11675 
11676     // Skip checking T a = a where T is not a record or reference type.
11677     // Doing so is a way to silence uninitialized warnings.
11678     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11679       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11680         if (ICE->getCastKind() == CK_LValueToRValue)
11681           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11682             if (DRE->getDecl() == OrigDecl)
11683               return;
11684 
11685     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11686   }
11687 } // end anonymous namespace
11688 
11689 namespace {
11690   // Simple wrapper to add the name of a variable or (if no variable is
11691   // available) a DeclarationName into a diagnostic.
11692   struct VarDeclOrName {
11693     VarDecl *VDecl;
11694     DeclarationName Name;
11695 
11696     friend const Sema::SemaDiagnosticBuilder &
11697     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11698       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11699     }
11700   };
11701 } // end anonymous namespace
11702 
11703 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11704                                             DeclarationName Name, QualType Type,
11705                                             TypeSourceInfo *TSI,
11706                                             SourceRange Range, bool DirectInit,
11707                                             Expr *Init) {
11708   bool IsInitCapture = !VDecl;
11709   assert((!VDecl || !VDecl->isInitCapture()) &&
11710          "init captures are expected to be deduced prior to initialization");
11711 
11712   VarDeclOrName VN{VDecl, Name};
11713 
11714   DeducedType *Deduced = Type->getContainedDeducedType();
11715   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11716 
11717   // C++11 [dcl.spec.auto]p3
11718   if (!Init) {
11719     assert(VDecl && "no init for init capture deduction?");
11720 
11721     // Except for class argument deduction, and then for an initializing
11722     // declaration only, i.e. no static at class scope or extern.
11723     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11724         VDecl->hasExternalStorage() ||
11725         VDecl->isStaticDataMember()) {
11726       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11727         << VDecl->getDeclName() << Type;
11728       return QualType();
11729     }
11730   }
11731 
11732   ArrayRef<Expr*> DeduceInits;
11733   if (Init)
11734     DeduceInits = Init;
11735 
11736   if (DirectInit) {
11737     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11738       DeduceInits = PL->exprs();
11739   }
11740 
11741   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11742     assert(VDecl && "non-auto type for init capture deduction?");
11743     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11744     InitializationKind Kind = InitializationKind::CreateForInit(
11745         VDecl->getLocation(), DirectInit, Init);
11746     // FIXME: Initialization should not be taking a mutable list of inits.
11747     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11748     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11749                                                        InitsCopy);
11750   }
11751 
11752   if (DirectInit) {
11753     if (auto *IL = dyn_cast<InitListExpr>(Init))
11754       DeduceInits = IL->inits();
11755   }
11756 
11757   // Deduction only works if we have exactly one source expression.
11758   if (DeduceInits.empty()) {
11759     // It isn't possible to write this directly, but it is possible to
11760     // end up in this situation with "auto x(some_pack...);"
11761     Diag(Init->getBeginLoc(), IsInitCapture
11762                                   ? diag::err_init_capture_no_expression
11763                                   : diag::err_auto_var_init_no_expression)
11764         << VN << Type << Range;
11765     return QualType();
11766   }
11767 
11768   if (DeduceInits.size() > 1) {
11769     Diag(DeduceInits[1]->getBeginLoc(),
11770          IsInitCapture ? diag::err_init_capture_multiple_expressions
11771                        : diag::err_auto_var_init_multiple_expressions)
11772         << VN << Type << Range;
11773     return QualType();
11774   }
11775 
11776   Expr *DeduceInit = DeduceInits[0];
11777   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11778     Diag(Init->getBeginLoc(), IsInitCapture
11779                                   ? diag::err_init_capture_paren_braces
11780                                   : diag::err_auto_var_init_paren_braces)
11781         << isa<InitListExpr>(Init) << VN << Type << Range;
11782     return QualType();
11783   }
11784 
11785   // Expressions default to 'id' when we're in a debugger.
11786   bool DefaultedAnyToId = false;
11787   if (getLangOpts().DebuggerCastResultToId &&
11788       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11789     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11790     if (Result.isInvalid()) {
11791       return QualType();
11792     }
11793     Init = Result.get();
11794     DefaultedAnyToId = true;
11795   }
11796 
11797   // C++ [dcl.decomp]p1:
11798   //   If the assignment-expression [...] has array type A and no ref-qualifier
11799   //   is present, e has type cv A
11800   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11801       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11802       DeduceInit->getType()->isConstantArrayType())
11803     return Context.getQualifiedType(DeduceInit->getType(),
11804                                     Type.getQualifiers());
11805 
11806   QualType DeducedType;
11807   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11808     if (!IsInitCapture)
11809       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11810     else if (isa<InitListExpr>(Init))
11811       Diag(Range.getBegin(),
11812            diag::err_init_capture_deduction_failure_from_init_list)
11813           << VN
11814           << (DeduceInit->getType().isNull() ? TSI->getType()
11815                                              : DeduceInit->getType())
11816           << DeduceInit->getSourceRange();
11817     else
11818       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11819           << VN << TSI->getType()
11820           << (DeduceInit->getType().isNull() ? TSI->getType()
11821                                              : DeduceInit->getType())
11822           << DeduceInit->getSourceRange();
11823   }
11824 
11825   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11826   // 'id' instead of a specific object type prevents most of our usual
11827   // checks.
11828   // We only want to warn outside of template instantiations, though:
11829   // inside a template, the 'id' could have come from a parameter.
11830   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11831       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11832     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11833     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11834   }
11835 
11836   return DeducedType;
11837 }
11838 
11839 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11840                                          Expr *Init) {
11841   assert(!Init || !Init->containsErrors());
11842   QualType DeducedType = deduceVarTypeFromInitializer(
11843       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11844       VDecl->getSourceRange(), DirectInit, Init);
11845   if (DeducedType.isNull()) {
11846     VDecl->setInvalidDecl();
11847     return true;
11848   }
11849 
11850   VDecl->setType(DeducedType);
11851   assert(VDecl->isLinkageValid());
11852 
11853   // In ARC, infer lifetime.
11854   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11855     VDecl->setInvalidDecl();
11856 
11857   if (getLangOpts().OpenCL)
11858     deduceOpenCLAddressSpace(VDecl);
11859 
11860   // If this is a redeclaration, check that the type we just deduced matches
11861   // the previously declared type.
11862   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11863     // We never need to merge the type, because we cannot form an incomplete
11864     // array of auto, nor deduce such a type.
11865     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11866   }
11867 
11868   // Check the deduced type is valid for a variable declaration.
11869   CheckVariableDeclarationType(VDecl);
11870   return VDecl->isInvalidDecl();
11871 }
11872 
11873 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11874                                               SourceLocation Loc) {
11875   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11876     Init = EWC->getSubExpr();
11877 
11878   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11879     Init = CE->getSubExpr();
11880 
11881   QualType InitType = Init->getType();
11882   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11883           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11884          "shouldn't be called if type doesn't have a non-trivial C struct");
11885   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11886     for (auto I : ILE->inits()) {
11887       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11888           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11889         continue;
11890       SourceLocation SL = I->getExprLoc();
11891       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11892     }
11893     return;
11894   }
11895 
11896   if (isa<ImplicitValueInitExpr>(Init)) {
11897     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11898       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11899                             NTCUK_Init);
11900   } else {
11901     // Assume all other explicit initializers involving copying some existing
11902     // object.
11903     // TODO: ignore any explicit initializers where we can guarantee
11904     // copy-elision.
11905     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11906       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11907   }
11908 }
11909 
11910 namespace {
11911 
11912 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11913   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11914   // in the source code or implicitly by the compiler if it is in a union
11915   // defined in a system header and has non-trivial ObjC ownership
11916   // qualifications. We don't want those fields to participate in determining
11917   // whether the containing union is non-trivial.
11918   return FD->hasAttr<UnavailableAttr>();
11919 }
11920 
11921 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11922     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11923                                     void> {
11924   using Super =
11925       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11926                                     void>;
11927 
11928   DiagNonTrivalCUnionDefaultInitializeVisitor(
11929       QualType OrigTy, SourceLocation OrigLoc,
11930       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11931       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11932 
11933   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11934                      const FieldDecl *FD, bool InNonTrivialUnion) {
11935     if (const auto *AT = S.Context.getAsArrayType(QT))
11936       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11937                                      InNonTrivialUnion);
11938     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11939   }
11940 
11941   void visitARCStrong(QualType QT, const FieldDecl *FD,
11942                       bool InNonTrivialUnion) {
11943     if (InNonTrivialUnion)
11944       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11945           << 1 << 0 << QT << FD->getName();
11946   }
11947 
11948   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11949     if (InNonTrivialUnion)
11950       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11951           << 1 << 0 << QT << FD->getName();
11952   }
11953 
11954   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11955     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11956     if (RD->isUnion()) {
11957       if (OrigLoc.isValid()) {
11958         bool IsUnion = false;
11959         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11960           IsUnion = OrigRD->isUnion();
11961         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11962             << 0 << OrigTy << IsUnion << UseContext;
11963         // Reset OrigLoc so that this diagnostic is emitted only once.
11964         OrigLoc = SourceLocation();
11965       }
11966       InNonTrivialUnion = true;
11967     }
11968 
11969     if (InNonTrivialUnion)
11970       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11971           << 0 << 0 << QT.getUnqualifiedType() << "";
11972 
11973     for (const FieldDecl *FD : RD->fields())
11974       if (!shouldIgnoreForRecordTriviality(FD))
11975         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11976   }
11977 
11978   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11979 
11980   // The non-trivial C union type or the struct/union type that contains a
11981   // non-trivial C union.
11982   QualType OrigTy;
11983   SourceLocation OrigLoc;
11984   Sema::NonTrivialCUnionContext UseContext;
11985   Sema &S;
11986 };
11987 
11988 struct DiagNonTrivalCUnionDestructedTypeVisitor
11989     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11990   using Super =
11991       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11992 
11993   DiagNonTrivalCUnionDestructedTypeVisitor(
11994       QualType OrigTy, SourceLocation OrigLoc,
11995       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11996       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11997 
11998   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11999                      const FieldDecl *FD, bool InNonTrivialUnion) {
12000     if (const auto *AT = S.Context.getAsArrayType(QT))
12001       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12002                                      InNonTrivialUnion);
12003     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12004   }
12005 
12006   void visitARCStrong(QualType QT, const FieldDecl *FD,
12007                       bool InNonTrivialUnion) {
12008     if (InNonTrivialUnion)
12009       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12010           << 1 << 1 << QT << FD->getName();
12011   }
12012 
12013   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12014     if (InNonTrivialUnion)
12015       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12016           << 1 << 1 << QT << FD->getName();
12017   }
12018 
12019   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12020     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12021     if (RD->isUnion()) {
12022       if (OrigLoc.isValid()) {
12023         bool IsUnion = false;
12024         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12025           IsUnion = OrigRD->isUnion();
12026         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12027             << 1 << OrigTy << IsUnion << UseContext;
12028         // Reset OrigLoc so that this diagnostic is emitted only once.
12029         OrigLoc = SourceLocation();
12030       }
12031       InNonTrivialUnion = true;
12032     }
12033 
12034     if (InNonTrivialUnion)
12035       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12036           << 0 << 1 << QT.getUnqualifiedType() << "";
12037 
12038     for (const FieldDecl *FD : RD->fields())
12039       if (!shouldIgnoreForRecordTriviality(FD))
12040         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12041   }
12042 
12043   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12044   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12045                           bool InNonTrivialUnion) {}
12046 
12047   // The non-trivial C union type or the struct/union type that contains a
12048   // non-trivial C union.
12049   QualType OrigTy;
12050   SourceLocation OrigLoc;
12051   Sema::NonTrivialCUnionContext UseContext;
12052   Sema &S;
12053 };
12054 
12055 struct DiagNonTrivalCUnionCopyVisitor
12056     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12057   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12058 
12059   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12060                                  Sema::NonTrivialCUnionContext UseContext,
12061                                  Sema &S)
12062       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12063 
12064   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12065                      const FieldDecl *FD, bool InNonTrivialUnion) {
12066     if (const auto *AT = S.Context.getAsArrayType(QT))
12067       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12068                                      InNonTrivialUnion);
12069     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12070   }
12071 
12072   void visitARCStrong(QualType QT, const FieldDecl *FD,
12073                       bool InNonTrivialUnion) {
12074     if (InNonTrivialUnion)
12075       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12076           << 1 << 2 << QT << FD->getName();
12077   }
12078 
12079   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12080     if (InNonTrivialUnion)
12081       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12082           << 1 << 2 << QT << FD->getName();
12083   }
12084 
12085   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12086     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12087     if (RD->isUnion()) {
12088       if (OrigLoc.isValid()) {
12089         bool IsUnion = false;
12090         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12091           IsUnion = OrigRD->isUnion();
12092         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12093             << 2 << OrigTy << IsUnion << UseContext;
12094         // Reset OrigLoc so that this diagnostic is emitted only once.
12095         OrigLoc = SourceLocation();
12096       }
12097       InNonTrivialUnion = true;
12098     }
12099 
12100     if (InNonTrivialUnion)
12101       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12102           << 0 << 2 << QT.getUnqualifiedType() << "";
12103 
12104     for (const FieldDecl *FD : RD->fields())
12105       if (!shouldIgnoreForRecordTriviality(FD))
12106         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12107   }
12108 
12109   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12110                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12111   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12112   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12113                             bool InNonTrivialUnion) {}
12114 
12115   // The non-trivial C union type or the struct/union type that contains a
12116   // non-trivial C union.
12117   QualType OrigTy;
12118   SourceLocation OrigLoc;
12119   Sema::NonTrivialCUnionContext UseContext;
12120   Sema &S;
12121 };
12122 
12123 } // namespace
12124 
12125 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12126                                  NonTrivialCUnionContext UseContext,
12127                                  unsigned NonTrivialKind) {
12128   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12129           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12130           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12131          "shouldn't be called if type doesn't have a non-trivial C union");
12132 
12133   if ((NonTrivialKind & NTCUK_Init) &&
12134       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12135     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12136         .visit(QT, nullptr, false);
12137   if ((NonTrivialKind & NTCUK_Destruct) &&
12138       QT.hasNonTrivialToPrimitiveDestructCUnion())
12139     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12140         .visit(QT, nullptr, false);
12141   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12142     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12143         .visit(QT, nullptr, false);
12144 }
12145 
12146 /// AddInitializerToDecl - Adds the initializer Init to the
12147 /// declaration dcl. If DirectInit is true, this is C++ direct
12148 /// initialization rather than copy initialization.
12149 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12150   // If there is no declaration, there was an error parsing it.  Just ignore
12151   // the initializer.
12152   if (!RealDecl || RealDecl->isInvalidDecl()) {
12153     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12154     return;
12155   }
12156 
12157   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12158     // Pure-specifiers are handled in ActOnPureSpecifier.
12159     Diag(Method->getLocation(), diag::err_member_function_initialization)
12160       << Method->getDeclName() << Init->getSourceRange();
12161     Method->setInvalidDecl();
12162     return;
12163   }
12164 
12165   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12166   if (!VDecl) {
12167     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12168     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12169     RealDecl->setInvalidDecl();
12170     return;
12171   }
12172 
12173   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12174   if (VDecl->getType()->isUndeducedType()) {
12175     // Attempt typo correction early so that the type of the init expression can
12176     // be deduced based on the chosen correction if the original init contains a
12177     // TypoExpr.
12178     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12179     if (!Res.isUsable()) {
12180       // There are unresolved typos in Init, just drop them.
12181       // FIXME: improve the recovery strategy to preserve the Init.
12182       RealDecl->setInvalidDecl();
12183       return;
12184     }
12185     if (Res.get()->containsErrors()) {
12186       // Invalidate the decl as we don't know the type for recovery-expr yet.
12187       RealDecl->setInvalidDecl();
12188       VDecl->setInit(Res.get());
12189       return;
12190     }
12191     Init = Res.get();
12192 
12193     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12194       return;
12195   }
12196 
12197   // dllimport cannot be used on variable definitions.
12198   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12199     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12200     VDecl->setInvalidDecl();
12201     return;
12202   }
12203 
12204   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12205     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12206     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12207     VDecl->setInvalidDecl();
12208     return;
12209   }
12210 
12211   if (!VDecl->getType()->isDependentType()) {
12212     // A definition must end up with a complete type, which means it must be
12213     // complete with the restriction that an array type might be completed by
12214     // the initializer; note that later code assumes this restriction.
12215     QualType BaseDeclType = VDecl->getType();
12216     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12217       BaseDeclType = Array->getElementType();
12218     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12219                             diag::err_typecheck_decl_incomplete_type)) {
12220       RealDecl->setInvalidDecl();
12221       return;
12222     }
12223 
12224     // The variable can not have an abstract class type.
12225     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12226                                diag::err_abstract_type_in_decl,
12227                                AbstractVariableType))
12228       VDecl->setInvalidDecl();
12229   }
12230 
12231   // If adding the initializer will turn this declaration into a definition,
12232   // and we already have a definition for this variable, diagnose or otherwise
12233   // handle the situation.
12234   if (VarDecl *Def = VDecl->getDefinition())
12235     if (Def != VDecl &&
12236         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12237         !VDecl->isThisDeclarationADemotedDefinition() &&
12238         checkVarDeclRedefinition(Def, VDecl))
12239       return;
12240 
12241   if (getLangOpts().CPlusPlus) {
12242     // C++ [class.static.data]p4
12243     //   If a static data member is of const integral or const
12244     //   enumeration type, its declaration in the class definition can
12245     //   specify a constant-initializer which shall be an integral
12246     //   constant expression (5.19). In that case, the member can appear
12247     //   in integral constant expressions. The member shall still be
12248     //   defined in a namespace scope if it is used in the program and the
12249     //   namespace scope definition shall not contain an initializer.
12250     //
12251     // We already performed a redefinition check above, but for static
12252     // data members we also need to check whether there was an in-class
12253     // declaration with an initializer.
12254     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12255       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12256           << VDecl->getDeclName();
12257       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12258            diag::note_previous_initializer)
12259           << 0;
12260       return;
12261     }
12262 
12263     if (VDecl->hasLocalStorage())
12264       setFunctionHasBranchProtectedScope();
12265 
12266     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12267       VDecl->setInvalidDecl();
12268       return;
12269     }
12270   }
12271 
12272   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12273   // a kernel function cannot be initialized."
12274   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12275     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12276     VDecl->setInvalidDecl();
12277     return;
12278   }
12279 
12280   // The LoaderUninitialized attribute acts as a definition (of undef).
12281   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12282     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12283     VDecl->setInvalidDecl();
12284     return;
12285   }
12286 
12287   // Get the decls type and save a reference for later, since
12288   // CheckInitializerTypes may change it.
12289   QualType DclT = VDecl->getType(), SavT = DclT;
12290 
12291   // Expressions default to 'id' when we're in a debugger
12292   // and we are assigning it to a variable of Objective-C pointer type.
12293   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12294       Init->getType() == Context.UnknownAnyTy) {
12295     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12296     if (Result.isInvalid()) {
12297       VDecl->setInvalidDecl();
12298       return;
12299     }
12300     Init = Result.get();
12301   }
12302 
12303   // Perform the initialization.
12304   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12305   if (!VDecl->isInvalidDecl()) {
12306     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12307     InitializationKind Kind = InitializationKind::CreateForInit(
12308         VDecl->getLocation(), DirectInit, Init);
12309 
12310     MultiExprArg Args = Init;
12311     if (CXXDirectInit)
12312       Args = MultiExprArg(CXXDirectInit->getExprs(),
12313                           CXXDirectInit->getNumExprs());
12314 
12315     // Try to correct any TypoExprs in the initialization arguments.
12316     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12317       ExprResult Res = CorrectDelayedTyposInExpr(
12318           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12319           [this, Entity, Kind](Expr *E) {
12320             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12321             return Init.Failed() ? ExprError() : E;
12322           });
12323       if (Res.isInvalid()) {
12324         VDecl->setInvalidDecl();
12325       } else if (Res.get() != Args[Idx]) {
12326         Args[Idx] = Res.get();
12327       }
12328     }
12329     if (VDecl->isInvalidDecl())
12330       return;
12331 
12332     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12333                                    /*TopLevelOfInitList=*/false,
12334                                    /*TreatUnavailableAsInvalid=*/false);
12335     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12336     if (Result.isInvalid()) {
12337       // If the provied initializer fails to initialize the var decl,
12338       // we attach a recovery expr for better recovery.
12339       auto RecoveryExpr =
12340           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12341       if (RecoveryExpr.get())
12342         VDecl->setInit(RecoveryExpr.get());
12343       return;
12344     }
12345 
12346     Init = Result.getAs<Expr>();
12347   }
12348 
12349   // Check for self-references within variable initializers.
12350   // Variables declared within a function/method body (except for references)
12351   // are handled by a dataflow analysis.
12352   // This is undefined behavior in C++, but valid in C.
12353   if (getLangOpts().CPlusPlus)
12354     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12355         VDecl->getType()->isReferenceType())
12356       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12357 
12358   // If the type changed, it means we had an incomplete type that was
12359   // completed by the initializer. For example:
12360   //   int ary[] = { 1, 3, 5 };
12361   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12362   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12363     VDecl->setType(DclT);
12364 
12365   if (!VDecl->isInvalidDecl()) {
12366     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12367 
12368     if (VDecl->hasAttr<BlocksAttr>())
12369       checkRetainCycles(VDecl, Init);
12370 
12371     // It is safe to assign a weak reference into a strong variable.
12372     // Although this code can still have problems:
12373     //   id x = self.weakProp;
12374     //   id y = self.weakProp;
12375     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12376     // paths through the function. This should be revisited if
12377     // -Wrepeated-use-of-weak is made flow-sensitive.
12378     if (FunctionScopeInfo *FSI = getCurFunction())
12379       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12380            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12381           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12382                            Init->getBeginLoc()))
12383         FSI->markSafeWeakUse(Init);
12384   }
12385 
12386   // The initialization is usually a full-expression.
12387   //
12388   // FIXME: If this is a braced initialization of an aggregate, it is not
12389   // an expression, and each individual field initializer is a separate
12390   // full-expression. For instance, in:
12391   //
12392   //   struct Temp { ~Temp(); };
12393   //   struct S { S(Temp); };
12394   //   struct T { S a, b; } t = { Temp(), Temp() }
12395   //
12396   // we should destroy the first Temp before constructing the second.
12397   ExprResult Result =
12398       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12399                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12400   if (Result.isInvalid()) {
12401     VDecl->setInvalidDecl();
12402     return;
12403   }
12404   Init = Result.get();
12405 
12406   // Attach the initializer to the decl.
12407   VDecl->setInit(Init);
12408 
12409   if (VDecl->isLocalVarDecl()) {
12410     // Don't check the initializer if the declaration is malformed.
12411     if (VDecl->isInvalidDecl()) {
12412       // do nothing
12413 
12414     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12415     // This is true even in C++ for OpenCL.
12416     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12417       CheckForConstantInitializer(Init, DclT);
12418 
12419     // Otherwise, C++ does not restrict the initializer.
12420     } else if (getLangOpts().CPlusPlus) {
12421       // do nothing
12422 
12423     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12424     // static storage duration shall be constant expressions or string literals.
12425     } else if (VDecl->getStorageClass() == SC_Static) {
12426       CheckForConstantInitializer(Init, DclT);
12427 
12428     // C89 is stricter than C99 for aggregate initializers.
12429     // C89 6.5.7p3: All the expressions [...] in an initializer list
12430     // for an object that has aggregate or union type shall be
12431     // constant expressions.
12432     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12433                isa<InitListExpr>(Init)) {
12434       const Expr *Culprit;
12435       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12436         Diag(Culprit->getExprLoc(),
12437              diag::ext_aggregate_init_not_constant)
12438           << Culprit->getSourceRange();
12439       }
12440     }
12441 
12442     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12443       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12444         if (VDecl->hasLocalStorage())
12445           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12446   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12447              VDecl->getLexicalDeclContext()->isRecord()) {
12448     // This is an in-class initialization for a static data member, e.g.,
12449     //
12450     // struct S {
12451     //   static const int value = 17;
12452     // };
12453 
12454     // C++ [class.mem]p4:
12455     //   A member-declarator can contain a constant-initializer only
12456     //   if it declares a static member (9.4) of const integral or
12457     //   const enumeration type, see 9.4.2.
12458     //
12459     // C++11 [class.static.data]p3:
12460     //   If a non-volatile non-inline const static data member is of integral
12461     //   or enumeration type, its declaration in the class definition can
12462     //   specify a brace-or-equal-initializer in which every initializer-clause
12463     //   that is an assignment-expression is a constant expression. A static
12464     //   data member of literal type can be declared in the class definition
12465     //   with the constexpr specifier; if so, its declaration shall specify a
12466     //   brace-or-equal-initializer in which every initializer-clause that is
12467     //   an assignment-expression is a constant expression.
12468 
12469     // Do nothing on dependent types.
12470     if (DclT->isDependentType()) {
12471 
12472     // Allow any 'static constexpr' members, whether or not they are of literal
12473     // type. We separately check that every constexpr variable is of literal
12474     // type.
12475     } else if (VDecl->isConstexpr()) {
12476 
12477     // Require constness.
12478     } else if (!DclT.isConstQualified()) {
12479       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12480         << Init->getSourceRange();
12481       VDecl->setInvalidDecl();
12482 
12483     // We allow integer constant expressions in all cases.
12484     } else if (DclT->isIntegralOrEnumerationType()) {
12485       // Check whether the expression is a constant expression.
12486       SourceLocation Loc;
12487       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12488         // In C++11, a non-constexpr const static data member with an
12489         // in-class initializer cannot be volatile.
12490         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12491       else if (Init->isValueDependent())
12492         ; // Nothing to check.
12493       else if (Init->isIntegerConstantExpr(Context, &Loc))
12494         ; // Ok, it's an ICE!
12495       else if (Init->getType()->isScopedEnumeralType() &&
12496                Init->isCXX11ConstantExpr(Context))
12497         ; // Ok, it is a scoped-enum constant expression.
12498       else if (Init->isEvaluatable(Context)) {
12499         // If we can constant fold the initializer through heroics, accept it,
12500         // but report this as a use of an extension for -pedantic.
12501         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12502           << Init->getSourceRange();
12503       } else {
12504         // Otherwise, this is some crazy unknown case.  Report the issue at the
12505         // location provided by the isIntegerConstantExpr failed check.
12506         Diag(Loc, diag::err_in_class_initializer_non_constant)
12507           << Init->getSourceRange();
12508         VDecl->setInvalidDecl();
12509       }
12510 
12511     // We allow foldable floating-point constants as an extension.
12512     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12513       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12514       // it anyway and provide a fixit to add the 'constexpr'.
12515       if (getLangOpts().CPlusPlus11) {
12516         Diag(VDecl->getLocation(),
12517              diag::ext_in_class_initializer_float_type_cxx11)
12518             << DclT << Init->getSourceRange();
12519         Diag(VDecl->getBeginLoc(),
12520              diag::note_in_class_initializer_float_type_cxx11)
12521             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12522       } else {
12523         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12524           << DclT << Init->getSourceRange();
12525 
12526         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12527           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12528             << Init->getSourceRange();
12529           VDecl->setInvalidDecl();
12530         }
12531       }
12532 
12533     // Suggest adding 'constexpr' in C++11 for literal types.
12534     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12535       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12536           << DclT << Init->getSourceRange()
12537           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12538       VDecl->setConstexpr(true);
12539 
12540     } else {
12541       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12542         << DclT << Init->getSourceRange();
12543       VDecl->setInvalidDecl();
12544     }
12545   } else if (VDecl->isFileVarDecl()) {
12546     // In C, extern is typically used to avoid tentative definitions when
12547     // declaring variables in headers, but adding an intializer makes it a
12548     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12549     // In C++, extern is often used to give implictly static const variables
12550     // external linkage, so don't warn in that case. If selectany is present,
12551     // this might be header code intended for C and C++ inclusion, so apply the
12552     // C++ rules.
12553     if (VDecl->getStorageClass() == SC_Extern &&
12554         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12555          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12556         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12557         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12558       Diag(VDecl->getLocation(), diag::warn_extern_init);
12559 
12560     // In Microsoft C++ mode, a const variable defined in namespace scope has
12561     // external linkage by default if the variable is declared with
12562     // __declspec(dllexport).
12563     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12564         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12565         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12566       VDecl->setStorageClass(SC_Extern);
12567 
12568     // C99 6.7.8p4. All file scoped initializers need to be constant.
12569     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12570       CheckForConstantInitializer(Init, DclT);
12571   }
12572 
12573   QualType InitType = Init->getType();
12574   if (!InitType.isNull() &&
12575       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12576        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12577     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12578 
12579   // We will represent direct-initialization similarly to copy-initialization:
12580   //    int x(1);  -as-> int x = 1;
12581   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12582   //
12583   // Clients that want to distinguish between the two forms, can check for
12584   // direct initializer using VarDecl::getInitStyle().
12585   // A major benefit is that clients that don't particularly care about which
12586   // exactly form was it (like the CodeGen) can handle both cases without
12587   // special case code.
12588 
12589   // C++ 8.5p11:
12590   // The form of initialization (using parentheses or '=') is generally
12591   // insignificant, but does matter when the entity being initialized has a
12592   // class type.
12593   if (CXXDirectInit) {
12594     assert(DirectInit && "Call-style initializer must be direct init.");
12595     VDecl->setInitStyle(VarDecl::CallInit);
12596   } else if (DirectInit) {
12597     // This must be list-initialization. No other way is direct-initialization.
12598     VDecl->setInitStyle(VarDecl::ListInit);
12599   }
12600 
12601   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12602     DeclsToCheckForDeferredDiags.insert(VDecl);
12603   CheckCompleteVariableDeclaration(VDecl);
12604 }
12605 
12606 /// ActOnInitializerError - Given that there was an error parsing an
12607 /// initializer for the given declaration, try to return to some form
12608 /// of sanity.
12609 void Sema::ActOnInitializerError(Decl *D) {
12610   // Our main concern here is re-establishing invariants like "a
12611   // variable's type is either dependent or complete".
12612   if (!D || D->isInvalidDecl()) return;
12613 
12614   VarDecl *VD = dyn_cast<VarDecl>(D);
12615   if (!VD) return;
12616 
12617   // Bindings are not usable if we can't make sense of the initializer.
12618   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12619     for (auto *BD : DD->bindings())
12620       BD->setInvalidDecl();
12621 
12622   // Auto types are meaningless if we can't make sense of the initializer.
12623   if (VD->getType()->isUndeducedType()) {
12624     D->setInvalidDecl();
12625     return;
12626   }
12627 
12628   QualType Ty = VD->getType();
12629   if (Ty->isDependentType()) return;
12630 
12631   // Require a complete type.
12632   if (RequireCompleteType(VD->getLocation(),
12633                           Context.getBaseElementType(Ty),
12634                           diag::err_typecheck_decl_incomplete_type)) {
12635     VD->setInvalidDecl();
12636     return;
12637   }
12638 
12639   // Require a non-abstract type.
12640   if (RequireNonAbstractType(VD->getLocation(), Ty,
12641                              diag::err_abstract_type_in_decl,
12642                              AbstractVariableType)) {
12643     VD->setInvalidDecl();
12644     return;
12645   }
12646 
12647   // Don't bother complaining about constructors or destructors,
12648   // though.
12649 }
12650 
12651 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12652   // If there is no declaration, there was an error parsing it. Just ignore it.
12653   if (!RealDecl)
12654     return;
12655 
12656   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12657     QualType Type = Var->getType();
12658 
12659     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12660     if (isa<DecompositionDecl>(RealDecl)) {
12661       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12662       Var->setInvalidDecl();
12663       return;
12664     }
12665 
12666     if (Type->isUndeducedType() &&
12667         DeduceVariableDeclarationType(Var, false, nullptr))
12668       return;
12669 
12670     // C++11 [class.static.data]p3: A static data member can be declared with
12671     // the constexpr specifier; if so, its declaration shall specify
12672     // a brace-or-equal-initializer.
12673     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12674     // the definition of a variable [...] or the declaration of a static data
12675     // member.
12676     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12677         !Var->isThisDeclarationADemotedDefinition()) {
12678       if (Var->isStaticDataMember()) {
12679         // C++1z removes the relevant rule; the in-class declaration is always
12680         // a definition there.
12681         if (!getLangOpts().CPlusPlus17 &&
12682             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12683           Diag(Var->getLocation(),
12684                diag::err_constexpr_static_mem_var_requires_init)
12685               << Var;
12686           Var->setInvalidDecl();
12687           return;
12688         }
12689       } else {
12690         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12691         Var->setInvalidDecl();
12692         return;
12693       }
12694     }
12695 
12696     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12697     // be initialized.
12698     if (!Var->isInvalidDecl() &&
12699         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12700         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12701       bool HasConstExprDefaultConstructor = false;
12702       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12703         for (auto *Ctor : RD->ctors()) {
12704           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12705               Ctor->getMethodQualifiers().getAddressSpace() ==
12706                   LangAS::opencl_constant) {
12707             HasConstExprDefaultConstructor = true;
12708           }
12709         }
12710       }
12711       if (!HasConstExprDefaultConstructor) {
12712         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12713         Var->setInvalidDecl();
12714         return;
12715       }
12716     }
12717 
12718     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12719       if (Var->getStorageClass() == SC_Extern) {
12720         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12721             << Var;
12722         Var->setInvalidDecl();
12723         return;
12724       }
12725       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12726                               diag::err_typecheck_decl_incomplete_type)) {
12727         Var->setInvalidDecl();
12728         return;
12729       }
12730       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12731         if (!RD->hasTrivialDefaultConstructor()) {
12732           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12733           Var->setInvalidDecl();
12734           return;
12735         }
12736       }
12737       // The declaration is unitialized, no need for further checks.
12738       return;
12739     }
12740 
12741     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12742     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12743         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12744       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12745                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12746 
12747 
12748     switch (DefKind) {
12749     case VarDecl::Definition:
12750       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12751         break;
12752 
12753       // We have an out-of-line definition of a static data member
12754       // that has an in-class initializer, so we type-check this like
12755       // a declaration.
12756       //
12757       LLVM_FALLTHROUGH;
12758 
12759     case VarDecl::DeclarationOnly:
12760       // It's only a declaration.
12761 
12762       // Block scope. C99 6.7p7: If an identifier for an object is
12763       // declared with no linkage (C99 6.2.2p6), the type for the
12764       // object shall be complete.
12765       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12766           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12767           RequireCompleteType(Var->getLocation(), Type,
12768                               diag::err_typecheck_decl_incomplete_type))
12769         Var->setInvalidDecl();
12770 
12771       // Make sure that the type is not abstract.
12772       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12773           RequireNonAbstractType(Var->getLocation(), Type,
12774                                  diag::err_abstract_type_in_decl,
12775                                  AbstractVariableType))
12776         Var->setInvalidDecl();
12777       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12778           Var->getStorageClass() == SC_PrivateExtern) {
12779         Diag(Var->getLocation(), diag::warn_private_extern);
12780         Diag(Var->getLocation(), diag::note_private_extern);
12781       }
12782 
12783       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12784           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12785         ExternalDeclarations.push_back(Var);
12786 
12787       return;
12788 
12789     case VarDecl::TentativeDefinition:
12790       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12791       // object that has file scope without an initializer, and without a
12792       // storage-class specifier or with the storage-class specifier "static",
12793       // constitutes a tentative definition. Note: A tentative definition with
12794       // external linkage is valid (C99 6.2.2p5).
12795       if (!Var->isInvalidDecl()) {
12796         if (const IncompleteArrayType *ArrayT
12797                                     = Context.getAsIncompleteArrayType(Type)) {
12798           if (RequireCompleteSizedType(
12799                   Var->getLocation(), ArrayT->getElementType(),
12800                   diag::err_array_incomplete_or_sizeless_type))
12801             Var->setInvalidDecl();
12802         } else if (Var->getStorageClass() == SC_Static) {
12803           // C99 6.9.2p3: If the declaration of an identifier for an object is
12804           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12805           // declared type shall not be an incomplete type.
12806           // NOTE: code such as the following
12807           //     static struct s;
12808           //     struct s { int a; };
12809           // is accepted by gcc. Hence here we issue a warning instead of
12810           // an error and we do not invalidate the static declaration.
12811           // NOTE: to avoid multiple warnings, only check the first declaration.
12812           if (Var->isFirstDecl())
12813             RequireCompleteType(Var->getLocation(), Type,
12814                                 diag::ext_typecheck_decl_incomplete_type);
12815         }
12816       }
12817 
12818       // Record the tentative definition; we're done.
12819       if (!Var->isInvalidDecl())
12820         TentativeDefinitions.push_back(Var);
12821       return;
12822     }
12823 
12824     // Provide a specific diagnostic for uninitialized variable
12825     // definitions with incomplete array type.
12826     if (Type->isIncompleteArrayType()) {
12827       Diag(Var->getLocation(),
12828            diag::err_typecheck_incomplete_array_needs_initializer);
12829       Var->setInvalidDecl();
12830       return;
12831     }
12832 
12833     // Provide a specific diagnostic for uninitialized variable
12834     // definitions with reference type.
12835     if (Type->isReferenceType()) {
12836       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12837           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12838       Var->setInvalidDecl();
12839       return;
12840     }
12841 
12842     // Do not attempt to type-check the default initializer for a
12843     // variable with dependent type.
12844     if (Type->isDependentType())
12845       return;
12846 
12847     if (Var->isInvalidDecl())
12848       return;
12849 
12850     if (!Var->hasAttr<AliasAttr>()) {
12851       if (RequireCompleteType(Var->getLocation(),
12852                               Context.getBaseElementType(Type),
12853                               diag::err_typecheck_decl_incomplete_type)) {
12854         Var->setInvalidDecl();
12855         return;
12856       }
12857     } else {
12858       return;
12859     }
12860 
12861     // The variable can not have an abstract class type.
12862     if (RequireNonAbstractType(Var->getLocation(), Type,
12863                                diag::err_abstract_type_in_decl,
12864                                AbstractVariableType)) {
12865       Var->setInvalidDecl();
12866       return;
12867     }
12868 
12869     // Check for jumps past the implicit initializer.  C++0x
12870     // clarifies that this applies to a "variable with automatic
12871     // storage duration", not a "local variable".
12872     // C++11 [stmt.dcl]p3
12873     //   A program that jumps from a point where a variable with automatic
12874     //   storage duration is not in scope to a point where it is in scope is
12875     //   ill-formed unless the variable has scalar type, class type with a
12876     //   trivial default constructor and a trivial destructor, a cv-qualified
12877     //   version of one of these types, or an array of one of the preceding
12878     //   types and is declared without an initializer.
12879     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12880       if (const RecordType *Record
12881             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12882         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12883         // Mark the function (if we're in one) for further checking even if the
12884         // looser rules of C++11 do not require such checks, so that we can
12885         // diagnose incompatibilities with C++98.
12886         if (!CXXRecord->isPOD())
12887           setFunctionHasBranchProtectedScope();
12888       }
12889     }
12890     // In OpenCL, we can't initialize objects in the __local address space,
12891     // even implicitly, so don't synthesize an implicit initializer.
12892     if (getLangOpts().OpenCL &&
12893         Var->getType().getAddressSpace() == LangAS::opencl_local)
12894       return;
12895     // C++03 [dcl.init]p9:
12896     //   If no initializer is specified for an object, and the
12897     //   object is of (possibly cv-qualified) non-POD class type (or
12898     //   array thereof), the object shall be default-initialized; if
12899     //   the object is of const-qualified type, the underlying class
12900     //   type shall have a user-declared default
12901     //   constructor. Otherwise, if no initializer is specified for
12902     //   a non- static object, the object and its subobjects, if
12903     //   any, have an indeterminate initial value); if the object
12904     //   or any of its subobjects are of const-qualified type, the
12905     //   program is ill-formed.
12906     // C++0x [dcl.init]p11:
12907     //   If no initializer is specified for an object, the object is
12908     //   default-initialized; [...].
12909     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12910     InitializationKind Kind
12911       = InitializationKind::CreateDefault(Var->getLocation());
12912 
12913     InitializationSequence InitSeq(*this, Entity, Kind, None);
12914     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12915 
12916     if (Init.get()) {
12917       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12918       // This is important for template substitution.
12919       Var->setInitStyle(VarDecl::CallInit);
12920     } else if (Init.isInvalid()) {
12921       // If default-init fails, attach a recovery-expr initializer to track
12922       // that initialization was attempted and failed.
12923       auto RecoveryExpr =
12924           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12925       if (RecoveryExpr.get())
12926         Var->setInit(RecoveryExpr.get());
12927     }
12928 
12929     CheckCompleteVariableDeclaration(Var);
12930   }
12931 }
12932 
12933 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12934   // If there is no declaration, there was an error parsing it. Ignore it.
12935   if (!D)
12936     return;
12937 
12938   VarDecl *VD = dyn_cast<VarDecl>(D);
12939   if (!VD) {
12940     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12941     D->setInvalidDecl();
12942     return;
12943   }
12944 
12945   VD->setCXXForRangeDecl(true);
12946 
12947   // for-range-declaration cannot be given a storage class specifier.
12948   int Error = -1;
12949   switch (VD->getStorageClass()) {
12950   case SC_None:
12951     break;
12952   case SC_Extern:
12953     Error = 0;
12954     break;
12955   case SC_Static:
12956     Error = 1;
12957     break;
12958   case SC_PrivateExtern:
12959     Error = 2;
12960     break;
12961   case SC_Auto:
12962     Error = 3;
12963     break;
12964   case SC_Register:
12965     Error = 4;
12966     break;
12967   }
12968 
12969   // for-range-declaration cannot be given a storage class specifier con't.
12970   switch (VD->getTSCSpec()) {
12971   case TSCS_thread_local:
12972     Error = 6;
12973     break;
12974   case TSCS___thread:
12975   case TSCS__Thread_local:
12976   case TSCS_unspecified:
12977     break;
12978   }
12979 
12980   if (Error != -1) {
12981     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12982         << VD << Error;
12983     D->setInvalidDecl();
12984   }
12985 }
12986 
12987 StmtResult
12988 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12989                                  IdentifierInfo *Ident,
12990                                  ParsedAttributes &Attrs,
12991                                  SourceLocation AttrEnd) {
12992   // C++1y [stmt.iter]p1:
12993   //   A range-based for statement of the form
12994   //      for ( for-range-identifier : for-range-initializer ) statement
12995   //   is equivalent to
12996   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12997   DeclSpec DS(Attrs.getPool().getFactory());
12998 
12999   const char *PrevSpec;
13000   unsigned DiagID;
13001   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13002                      getPrintingPolicy());
13003 
13004   Declarator D(DS, DeclaratorContext::ForInit);
13005   D.SetIdentifier(Ident, IdentLoc);
13006   D.takeAttributes(Attrs, AttrEnd);
13007 
13008   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13009                 IdentLoc);
13010   Decl *Var = ActOnDeclarator(S, D);
13011   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13012   FinalizeDeclaration(Var);
13013   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13014                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13015 }
13016 
13017 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13018   if (var->isInvalidDecl()) return;
13019 
13020   MaybeAddCUDAConstantAttr(var);
13021 
13022   if (getLangOpts().OpenCL) {
13023     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13024     // initialiser
13025     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13026         !var->hasInit()) {
13027       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13028           << 1 /*Init*/;
13029       var->setInvalidDecl();
13030       return;
13031     }
13032   }
13033 
13034   // In Objective-C, don't allow jumps past the implicit initialization of a
13035   // local retaining variable.
13036   if (getLangOpts().ObjC &&
13037       var->hasLocalStorage()) {
13038     switch (var->getType().getObjCLifetime()) {
13039     case Qualifiers::OCL_None:
13040     case Qualifiers::OCL_ExplicitNone:
13041     case Qualifiers::OCL_Autoreleasing:
13042       break;
13043 
13044     case Qualifiers::OCL_Weak:
13045     case Qualifiers::OCL_Strong:
13046       setFunctionHasBranchProtectedScope();
13047       break;
13048     }
13049   }
13050 
13051   if (var->hasLocalStorage() &&
13052       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13053     setFunctionHasBranchProtectedScope();
13054 
13055   // Warn about externally-visible variables being defined without a
13056   // prior declaration.  We only want to do this for global
13057   // declarations, but we also specifically need to avoid doing it for
13058   // class members because the linkage of an anonymous class can
13059   // change if it's later given a typedef name.
13060   if (var->isThisDeclarationADefinition() &&
13061       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13062       var->isExternallyVisible() && var->hasLinkage() &&
13063       !var->isInline() && !var->getDescribedVarTemplate() &&
13064       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13065       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13066       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13067                                   var->getLocation())) {
13068     // Find a previous declaration that's not a definition.
13069     VarDecl *prev = var->getPreviousDecl();
13070     while (prev && prev->isThisDeclarationADefinition())
13071       prev = prev->getPreviousDecl();
13072 
13073     if (!prev) {
13074       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13075       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13076           << /* variable */ 0;
13077     }
13078   }
13079 
13080   // Cache the result of checking for constant initialization.
13081   Optional<bool> CacheHasConstInit;
13082   const Expr *CacheCulprit = nullptr;
13083   auto checkConstInit = [&]() mutable {
13084     if (!CacheHasConstInit)
13085       CacheHasConstInit = var->getInit()->isConstantInitializer(
13086             Context, var->getType()->isReferenceType(), &CacheCulprit);
13087     return *CacheHasConstInit;
13088   };
13089 
13090   if (var->getTLSKind() == VarDecl::TLS_Static) {
13091     if (var->getType().isDestructedType()) {
13092       // GNU C++98 edits for __thread, [basic.start.term]p3:
13093       //   The type of an object with thread storage duration shall not
13094       //   have a non-trivial destructor.
13095       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13096       if (getLangOpts().CPlusPlus11)
13097         Diag(var->getLocation(), diag::note_use_thread_local);
13098     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13099       if (!checkConstInit()) {
13100         // GNU C++98 edits for __thread, [basic.start.init]p4:
13101         //   An object of thread storage duration shall not require dynamic
13102         //   initialization.
13103         // FIXME: Need strict checking here.
13104         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13105           << CacheCulprit->getSourceRange();
13106         if (getLangOpts().CPlusPlus11)
13107           Diag(var->getLocation(), diag::note_use_thread_local);
13108       }
13109     }
13110   }
13111 
13112 
13113   if (!var->getType()->isStructureType() && var->hasInit() &&
13114       isa<InitListExpr>(var->getInit())) {
13115     const auto *ILE = cast<InitListExpr>(var->getInit());
13116     unsigned NumInits = ILE->getNumInits();
13117     if (NumInits > 2)
13118       for (unsigned I = 0; I < NumInits; ++I) {
13119         const auto *Init = ILE->getInit(I);
13120         if (!Init)
13121           break;
13122         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13123         if (!SL)
13124           break;
13125 
13126         unsigned NumConcat = SL->getNumConcatenated();
13127         // Diagnose missing comma in string array initialization.
13128         // Do not warn when all the elements in the initializer are concatenated
13129         // together. Do not warn for macros too.
13130         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13131           bool OnlyOneMissingComma = true;
13132           for (unsigned J = I + 1; J < NumInits; ++J) {
13133             const auto *Init = ILE->getInit(J);
13134             if (!Init)
13135               break;
13136             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13137             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13138               OnlyOneMissingComma = false;
13139               break;
13140             }
13141           }
13142 
13143           if (OnlyOneMissingComma) {
13144             SmallVector<FixItHint, 1> Hints;
13145             for (unsigned i = 0; i < NumConcat - 1; ++i)
13146               Hints.push_back(FixItHint::CreateInsertion(
13147                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13148 
13149             Diag(SL->getStrTokenLoc(1),
13150                  diag::warn_concatenated_literal_array_init)
13151                 << Hints;
13152             Diag(SL->getBeginLoc(),
13153                  diag::note_concatenated_string_literal_silence);
13154           }
13155           // In any case, stop now.
13156           break;
13157         }
13158       }
13159   }
13160 
13161 
13162   QualType type = var->getType();
13163 
13164   if (var->hasAttr<BlocksAttr>())
13165     getCurFunction()->addByrefBlockVar(var);
13166 
13167   Expr *Init = var->getInit();
13168   bool GlobalStorage = var->hasGlobalStorage();
13169   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13170   QualType baseType = Context.getBaseElementType(type);
13171   bool HasConstInit = true;
13172 
13173   // Check whether the initializer is sufficiently constant.
13174   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13175       !Init->isValueDependent() &&
13176       (GlobalStorage || var->isConstexpr() ||
13177        var->mightBeUsableInConstantExpressions(Context))) {
13178     // If this variable might have a constant initializer or might be usable in
13179     // constant expressions, check whether or not it actually is now.  We can't
13180     // do this lazily, because the result might depend on things that change
13181     // later, such as which constexpr functions happen to be defined.
13182     SmallVector<PartialDiagnosticAt, 8> Notes;
13183     if (!getLangOpts().CPlusPlus11) {
13184       // Prior to C++11, in contexts where a constant initializer is required,
13185       // the set of valid constant initializers is described by syntactic rules
13186       // in [expr.const]p2-6.
13187       // FIXME: Stricter checking for these rules would be useful for constinit /
13188       // -Wglobal-constructors.
13189       HasConstInit = checkConstInit();
13190 
13191       // Compute and cache the constant value, and remember that we have a
13192       // constant initializer.
13193       if (HasConstInit) {
13194         (void)var->checkForConstantInitialization(Notes);
13195         Notes.clear();
13196       } else if (CacheCulprit) {
13197         Notes.emplace_back(CacheCulprit->getExprLoc(),
13198                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13199         Notes.back().second << CacheCulprit->getSourceRange();
13200       }
13201     } else {
13202       // Evaluate the initializer to see if it's a constant initializer.
13203       HasConstInit = var->checkForConstantInitialization(Notes);
13204     }
13205 
13206     if (HasConstInit) {
13207       // FIXME: Consider replacing the initializer with a ConstantExpr.
13208     } else if (var->isConstexpr()) {
13209       SourceLocation DiagLoc = var->getLocation();
13210       // If the note doesn't add any useful information other than a source
13211       // location, fold it into the primary diagnostic.
13212       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13213                                    diag::note_invalid_subexpr_in_const_expr) {
13214         DiagLoc = Notes[0].first;
13215         Notes.clear();
13216       }
13217       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13218           << var << Init->getSourceRange();
13219       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13220         Diag(Notes[I].first, Notes[I].second);
13221     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13222       auto *Attr = var->getAttr<ConstInitAttr>();
13223       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13224           << Init->getSourceRange();
13225       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13226           << Attr->getRange() << Attr->isConstinit();
13227       for (auto &it : Notes)
13228         Diag(it.first, it.second);
13229     } else if (IsGlobal &&
13230                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13231                                            var->getLocation())) {
13232       // Warn about globals which don't have a constant initializer.  Don't
13233       // warn about globals with a non-trivial destructor because we already
13234       // warned about them.
13235       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13236       if (!(RD && !RD->hasTrivialDestructor())) {
13237         // checkConstInit() here permits trivial default initialization even in
13238         // C++11 onwards, where such an initializer is not a constant initializer
13239         // but nonetheless doesn't require a global constructor.
13240         if (!checkConstInit())
13241           Diag(var->getLocation(), diag::warn_global_constructor)
13242               << Init->getSourceRange();
13243       }
13244     }
13245   }
13246 
13247   // Apply section attributes and pragmas to global variables.
13248   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13249       !inTemplateInstantiation()) {
13250     PragmaStack<StringLiteral *> *Stack = nullptr;
13251     int SectionFlags = ASTContext::PSF_Read;
13252     if (var->getType().isConstQualified()) {
13253       if (HasConstInit)
13254         Stack = &ConstSegStack;
13255       else {
13256         Stack = &BSSSegStack;
13257         SectionFlags |= ASTContext::PSF_Write;
13258       }
13259     } else if (var->hasInit() && HasConstInit) {
13260       Stack = &DataSegStack;
13261       SectionFlags |= ASTContext::PSF_Write;
13262     } else {
13263       Stack = &BSSSegStack;
13264       SectionFlags |= ASTContext::PSF_Write;
13265     }
13266     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13267       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13268         SectionFlags |= ASTContext::PSF_Implicit;
13269       UnifySection(SA->getName(), SectionFlags, var);
13270     } else if (Stack->CurrentValue) {
13271       SectionFlags |= ASTContext::PSF_Implicit;
13272       auto SectionName = Stack->CurrentValue->getString();
13273       var->addAttr(SectionAttr::CreateImplicit(
13274           Context, SectionName, Stack->CurrentPragmaLocation,
13275           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13276       if (UnifySection(SectionName, SectionFlags, var))
13277         var->dropAttr<SectionAttr>();
13278     }
13279 
13280     // Apply the init_seg attribute if this has an initializer.  If the
13281     // initializer turns out to not be dynamic, we'll end up ignoring this
13282     // attribute.
13283     if (CurInitSeg && var->getInit())
13284       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13285                                                CurInitSegLoc,
13286                                                AttributeCommonInfo::AS_Pragma));
13287   }
13288 
13289   // All the following checks are C++ only.
13290   if (!getLangOpts().CPlusPlus) {
13291     // If this variable must be emitted, add it as an initializer for the
13292     // current module.
13293     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13294       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13295     return;
13296   }
13297 
13298   // Require the destructor.
13299   if (!type->isDependentType())
13300     if (const RecordType *recordType = baseType->getAs<RecordType>())
13301       FinalizeVarWithDestructor(var, recordType);
13302 
13303   // If this variable must be emitted, add it as an initializer for the current
13304   // module.
13305   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13306     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13307 
13308   // Build the bindings if this is a structured binding declaration.
13309   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13310     CheckCompleteDecompositionDeclaration(DD);
13311 }
13312 
13313 /// Determines if a variable's alignment is dependent.
13314 static bool hasDependentAlignment(VarDecl *VD) {
13315   if (VD->getType()->isDependentType())
13316     return true;
13317   for (auto *I : VD->specific_attrs<AlignedAttr>())
13318     if (I->isAlignmentDependent())
13319       return true;
13320   return false;
13321 }
13322 
13323 /// Check if VD needs to be dllexport/dllimport due to being in a
13324 /// dllexport/import function.
13325 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13326   assert(VD->isStaticLocal());
13327 
13328   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13329 
13330   // Find outermost function when VD is in lambda function.
13331   while (FD && !getDLLAttr(FD) &&
13332          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13333          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13334     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13335   }
13336 
13337   if (!FD)
13338     return;
13339 
13340   // Static locals inherit dll attributes from their function.
13341   if (Attr *A = getDLLAttr(FD)) {
13342     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13343     NewAttr->setInherited(true);
13344     VD->addAttr(NewAttr);
13345   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13346     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13347     NewAttr->setInherited(true);
13348     VD->addAttr(NewAttr);
13349 
13350     // Export this function to enforce exporting this static variable even
13351     // if it is not used in this compilation unit.
13352     if (!FD->hasAttr<DLLExportAttr>())
13353       FD->addAttr(NewAttr);
13354 
13355   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13356     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13357     NewAttr->setInherited(true);
13358     VD->addAttr(NewAttr);
13359   }
13360 }
13361 
13362 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13363 /// any semantic actions necessary after any initializer has been attached.
13364 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13365   // Note that we are no longer parsing the initializer for this declaration.
13366   ParsingInitForAutoVars.erase(ThisDecl);
13367 
13368   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13369   if (!VD)
13370     return;
13371 
13372   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13373   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13374       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13375     if (PragmaClangBSSSection.Valid)
13376       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13377           Context, PragmaClangBSSSection.SectionName,
13378           PragmaClangBSSSection.PragmaLocation,
13379           AttributeCommonInfo::AS_Pragma));
13380     if (PragmaClangDataSection.Valid)
13381       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13382           Context, PragmaClangDataSection.SectionName,
13383           PragmaClangDataSection.PragmaLocation,
13384           AttributeCommonInfo::AS_Pragma));
13385     if (PragmaClangRodataSection.Valid)
13386       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13387           Context, PragmaClangRodataSection.SectionName,
13388           PragmaClangRodataSection.PragmaLocation,
13389           AttributeCommonInfo::AS_Pragma));
13390     if (PragmaClangRelroSection.Valid)
13391       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13392           Context, PragmaClangRelroSection.SectionName,
13393           PragmaClangRelroSection.PragmaLocation,
13394           AttributeCommonInfo::AS_Pragma));
13395   }
13396 
13397   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13398     for (auto *BD : DD->bindings()) {
13399       FinalizeDeclaration(BD);
13400     }
13401   }
13402 
13403   checkAttributesAfterMerging(*this, *VD);
13404 
13405   // Perform TLS alignment check here after attributes attached to the variable
13406   // which may affect the alignment have been processed. Only perform the check
13407   // if the target has a maximum TLS alignment (zero means no constraints).
13408   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13409     // Protect the check so that it's not performed on dependent types and
13410     // dependent alignments (we can't determine the alignment in that case).
13411     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13412         !VD->isInvalidDecl()) {
13413       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13414       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13415         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13416           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13417           << (unsigned)MaxAlignChars.getQuantity();
13418       }
13419     }
13420   }
13421 
13422   if (VD->isStaticLocal())
13423     CheckStaticLocalForDllExport(VD);
13424 
13425   // Perform check for initializers of device-side global variables.
13426   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13427   // 7.5). We must also apply the same checks to all __shared__
13428   // variables whether they are local or not. CUDA also allows
13429   // constant initializers for __constant__ and __device__ variables.
13430   if (getLangOpts().CUDA)
13431     checkAllowedCUDAInitializer(VD);
13432 
13433   // Grab the dllimport or dllexport attribute off of the VarDecl.
13434   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13435 
13436   // Imported static data members cannot be defined out-of-line.
13437   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13438     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13439         VD->isThisDeclarationADefinition()) {
13440       // We allow definitions of dllimport class template static data members
13441       // with a warning.
13442       CXXRecordDecl *Context =
13443         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13444       bool IsClassTemplateMember =
13445           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13446           Context->getDescribedClassTemplate();
13447 
13448       Diag(VD->getLocation(),
13449            IsClassTemplateMember
13450                ? diag::warn_attribute_dllimport_static_field_definition
13451                : diag::err_attribute_dllimport_static_field_definition);
13452       Diag(IA->getLocation(), diag::note_attribute);
13453       if (!IsClassTemplateMember)
13454         VD->setInvalidDecl();
13455     }
13456   }
13457 
13458   // dllimport/dllexport variables cannot be thread local, their TLS index
13459   // isn't exported with the variable.
13460   if (DLLAttr && VD->getTLSKind()) {
13461     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13462     if (F && getDLLAttr(F)) {
13463       assert(VD->isStaticLocal());
13464       // But if this is a static local in a dlimport/dllexport function, the
13465       // function will never be inlined, which means the var would never be
13466       // imported, so having it marked import/export is safe.
13467     } else {
13468       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13469                                                                     << DLLAttr;
13470       VD->setInvalidDecl();
13471     }
13472   }
13473 
13474   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13475     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13476       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13477           << Attr;
13478       VD->dropAttr<UsedAttr>();
13479     }
13480   }
13481   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13482     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13483       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13484           << Attr;
13485       VD->dropAttr<RetainAttr>();
13486     }
13487   }
13488 
13489   const DeclContext *DC = VD->getDeclContext();
13490   // If there's a #pragma GCC visibility in scope, and this isn't a class
13491   // member, set the visibility of this variable.
13492   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13493     AddPushedVisibilityAttribute(VD);
13494 
13495   // FIXME: Warn on unused var template partial specializations.
13496   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13497     MarkUnusedFileScopedDecl(VD);
13498 
13499   // Now we have parsed the initializer and can update the table of magic
13500   // tag values.
13501   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13502       !VD->getType()->isIntegralOrEnumerationType())
13503     return;
13504 
13505   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13506     const Expr *MagicValueExpr = VD->getInit();
13507     if (!MagicValueExpr) {
13508       continue;
13509     }
13510     Optional<llvm::APSInt> MagicValueInt;
13511     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13512       Diag(I->getRange().getBegin(),
13513            diag::err_type_tag_for_datatype_not_ice)
13514         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13515       continue;
13516     }
13517     if (MagicValueInt->getActiveBits() > 64) {
13518       Diag(I->getRange().getBegin(),
13519            diag::err_type_tag_for_datatype_too_large)
13520         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13521       continue;
13522     }
13523     uint64_t MagicValue = MagicValueInt->getZExtValue();
13524     RegisterTypeTagForDatatype(I->getArgumentKind(),
13525                                MagicValue,
13526                                I->getMatchingCType(),
13527                                I->getLayoutCompatible(),
13528                                I->getMustBeNull());
13529   }
13530 }
13531 
13532 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13533   auto *VD = dyn_cast<VarDecl>(DD);
13534   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13535 }
13536 
13537 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13538                                                    ArrayRef<Decl *> Group) {
13539   SmallVector<Decl*, 8> Decls;
13540 
13541   if (DS.isTypeSpecOwned())
13542     Decls.push_back(DS.getRepAsDecl());
13543 
13544   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13545   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13546   bool DiagnosedMultipleDecomps = false;
13547   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13548   bool DiagnosedNonDeducedAuto = false;
13549 
13550   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13551     if (Decl *D = Group[i]) {
13552       // For declarators, there are some additional syntactic-ish checks we need
13553       // to perform.
13554       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13555         if (!FirstDeclaratorInGroup)
13556           FirstDeclaratorInGroup = DD;
13557         if (!FirstDecompDeclaratorInGroup)
13558           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13559         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13560             !hasDeducedAuto(DD))
13561           FirstNonDeducedAutoInGroup = DD;
13562 
13563         if (FirstDeclaratorInGroup != DD) {
13564           // A decomposition declaration cannot be combined with any other
13565           // declaration in the same group.
13566           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13567             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13568                  diag::err_decomp_decl_not_alone)
13569                 << FirstDeclaratorInGroup->getSourceRange()
13570                 << DD->getSourceRange();
13571             DiagnosedMultipleDecomps = true;
13572           }
13573 
13574           // A declarator that uses 'auto' in any way other than to declare a
13575           // variable with a deduced type cannot be combined with any other
13576           // declarator in the same group.
13577           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13578             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13579                  diag::err_auto_non_deduced_not_alone)
13580                 << FirstNonDeducedAutoInGroup->getType()
13581                        ->hasAutoForTrailingReturnType()
13582                 << FirstDeclaratorInGroup->getSourceRange()
13583                 << DD->getSourceRange();
13584             DiagnosedNonDeducedAuto = true;
13585           }
13586         }
13587       }
13588 
13589       Decls.push_back(D);
13590     }
13591   }
13592 
13593   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13594     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13595       handleTagNumbering(Tag, S);
13596       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13597           getLangOpts().CPlusPlus)
13598         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13599     }
13600   }
13601 
13602   return BuildDeclaratorGroup(Decls);
13603 }
13604 
13605 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13606 /// group, performing any necessary semantic checking.
13607 Sema::DeclGroupPtrTy
13608 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13609   // C++14 [dcl.spec.auto]p7: (DR1347)
13610   //   If the type that replaces the placeholder type is not the same in each
13611   //   deduction, the program is ill-formed.
13612   if (Group.size() > 1) {
13613     QualType Deduced;
13614     VarDecl *DeducedDecl = nullptr;
13615     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13616       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13617       if (!D || D->isInvalidDecl())
13618         break;
13619       DeducedType *DT = D->getType()->getContainedDeducedType();
13620       if (!DT || DT->getDeducedType().isNull())
13621         continue;
13622       if (Deduced.isNull()) {
13623         Deduced = DT->getDeducedType();
13624         DeducedDecl = D;
13625       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13626         auto *AT = dyn_cast<AutoType>(DT);
13627         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13628                         diag::err_auto_different_deductions)
13629                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13630                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13631                    << D->getDeclName();
13632         if (DeducedDecl->hasInit())
13633           Dia << DeducedDecl->getInit()->getSourceRange();
13634         if (D->getInit())
13635           Dia << D->getInit()->getSourceRange();
13636         D->setInvalidDecl();
13637         break;
13638       }
13639     }
13640   }
13641 
13642   ActOnDocumentableDecls(Group);
13643 
13644   return DeclGroupPtrTy::make(
13645       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13646 }
13647 
13648 void Sema::ActOnDocumentableDecl(Decl *D) {
13649   ActOnDocumentableDecls(D);
13650 }
13651 
13652 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13653   // Don't parse the comment if Doxygen diagnostics are ignored.
13654   if (Group.empty() || !Group[0])
13655     return;
13656 
13657   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13658                       Group[0]->getLocation()) &&
13659       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13660                       Group[0]->getLocation()))
13661     return;
13662 
13663   if (Group.size() >= 2) {
13664     // This is a decl group.  Normally it will contain only declarations
13665     // produced from declarator list.  But in case we have any definitions or
13666     // additional declaration references:
13667     //   'typedef struct S {} S;'
13668     //   'typedef struct S *S;'
13669     //   'struct S *pS;'
13670     // FinalizeDeclaratorGroup adds these as separate declarations.
13671     Decl *MaybeTagDecl = Group[0];
13672     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13673       Group = Group.slice(1);
13674     }
13675   }
13676 
13677   // FIMXE: We assume every Decl in the group is in the same file.
13678   // This is false when preprocessor constructs the group from decls in
13679   // different files (e. g. macros or #include).
13680   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13681 }
13682 
13683 /// Common checks for a parameter-declaration that should apply to both function
13684 /// parameters and non-type template parameters.
13685 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13686   // Check that there are no default arguments inside the type of this
13687   // parameter.
13688   if (getLangOpts().CPlusPlus)
13689     CheckExtraCXXDefaultArguments(D);
13690 
13691   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13692   if (D.getCXXScopeSpec().isSet()) {
13693     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13694       << D.getCXXScopeSpec().getRange();
13695   }
13696 
13697   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13698   // simple identifier except [...irrelevant cases...].
13699   switch (D.getName().getKind()) {
13700   case UnqualifiedIdKind::IK_Identifier:
13701     break;
13702 
13703   case UnqualifiedIdKind::IK_OperatorFunctionId:
13704   case UnqualifiedIdKind::IK_ConversionFunctionId:
13705   case UnqualifiedIdKind::IK_LiteralOperatorId:
13706   case UnqualifiedIdKind::IK_ConstructorName:
13707   case UnqualifiedIdKind::IK_DestructorName:
13708   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13709   case UnqualifiedIdKind::IK_DeductionGuideName:
13710     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13711       << GetNameForDeclarator(D).getName();
13712     break;
13713 
13714   case UnqualifiedIdKind::IK_TemplateId:
13715   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13716     // GetNameForDeclarator would not produce a useful name in this case.
13717     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13718     break;
13719   }
13720 }
13721 
13722 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13723 /// to introduce parameters into function prototype scope.
13724 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13725   const DeclSpec &DS = D.getDeclSpec();
13726 
13727   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13728 
13729   // C++03 [dcl.stc]p2 also permits 'auto'.
13730   StorageClass SC = SC_None;
13731   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13732     SC = SC_Register;
13733     // In C++11, the 'register' storage class specifier is deprecated.
13734     // In C++17, it is not allowed, but we tolerate it as an extension.
13735     if (getLangOpts().CPlusPlus11) {
13736       Diag(DS.getStorageClassSpecLoc(),
13737            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13738                                      : diag::warn_deprecated_register)
13739         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13740     }
13741   } else if (getLangOpts().CPlusPlus &&
13742              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13743     SC = SC_Auto;
13744   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13745     Diag(DS.getStorageClassSpecLoc(),
13746          diag::err_invalid_storage_class_in_func_decl);
13747     D.getMutableDeclSpec().ClearStorageClassSpecs();
13748   }
13749 
13750   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13751     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13752       << DeclSpec::getSpecifierName(TSCS);
13753   if (DS.isInlineSpecified())
13754     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13755         << getLangOpts().CPlusPlus17;
13756   if (DS.hasConstexprSpecifier())
13757     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13758         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13759 
13760   DiagnoseFunctionSpecifiers(DS);
13761 
13762   CheckFunctionOrTemplateParamDeclarator(S, D);
13763 
13764   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13765   QualType parmDeclType = TInfo->getType();
13766 
13767   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13768   IdentifierInfo *II = D.getIdentifier();
13769   if (II) {
13770     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13771                    ForVisibleRedeclaration);
13772     LookupName(R, S);
13773     if (R.isSingleResult()) {
13774       NamedDecl *PrevDecl = R.getFoundDecl();
13775       if (PrevDecl->isTemplateParameter()) {
13776         // Maybe we will complain about the shadowed template parameter.
13777         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13778         // Just pretend that we didn't see the previous declaration.
13779         PrevDecl = nullptr;
13780       } else if (S->isDeclScope(PrevDecl)) {
13781         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13782         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13783 
13784         // Recover by removing the name
13785         II = nullptr;
13786         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13787         D.setInvalidType(true);
13788       }
13789     }
13790   }
13791 
13792   // Temporarily put parameter variables in the translation unit, not
13793   // the enclosing context.  This prevents them from accidentally
13794   // looking like class members in C++.
13795   ParmVarDecl *New =
13796       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13797                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13798 
13799   if (D.isInvalidType())
13800     New->setInvalidDecl();
13801 
13802   assert(S->isFunctionPrototypeScope());
13803   assert(S->getFunctionPrototypeDepth() >= 1);
13804   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13805                     S->getNextFunctionPrototypeIndex());
13806 
13807   // Add the parameter declaration into this scope.
13808   S->AddDecl(New);
13809   if (II)
13810     IdResolver.AddDecl(New);
13811 
13812   ProcessDeclAttributes(S, New, D);
13813 
13814   if (D.getDeclSpec().isModulePrivateSpecified())
13815     Diag(New->getLocation(), diag::err_module_private_local)
13816         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13817         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13818 
13819   if (New->hasAttr<BlocksAttr>()) {
13820     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13821   }
13822 
13823   if (getLangOpts().OpenCL)
13824     deduceOpenCLAddressSpace(New);
13825 
13826   return New;
13827 }
13828 
13829 /// Synthesizes a variable for a parameter arising from a
13830 /// typedef.
13831 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13832                                               SourceLocation Loc,
13833                                               QualType T) {
13834   /* FIXME: setting StartLoc == Loc.
13835      Would it be worth to modify callers so as to provide proper source
13836      location for the unnamed parameters, embedding the parameter's type? */
13837   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13838                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13839                                            SC_None, nullptr);
13840   Param->setImplicit();
13841   return Param;
13842 }
13843 
13844 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13845   // Don't diagnose unused-parameter errors in template instantiations; we
13846   // will already have done so in the template itself.
13847   if (inTemplateInstantiation())
13848     return;
13849 
13850   for (const ParmVarDecl *Parameter : Parameters) {
13851     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13852         !Parameter->hasAttr<UnusedAttr>()) {
13853       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13854         << Parameter->getDeclName();
13855     }
13856   }
13857 }
13858 
13859 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13860     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13861   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13862     return;
13863 
13864   // Warn if the return value is pass-by-value and larger than the specified
13865   // threshold.
13866   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13867     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13868     if (Size > LangOpts.NumLargeByValueCopy)
13869       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13870   }
13871 
13872   // Warn if any parameter is pass-by-value and larger than the specified
13873   // threshold.
13874   for (const ParmVarDecl *Parameter : Parameters) {
13875     QualType T = Parameter->getType();
13876     if (T->isDependentType() || !T.isPODType(Context))
13877       continue;
13878     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13879     if (Size > LangOpts.NumLargeByValueCopy)
13880       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13881           << Parameter << Size;
13882   }
13883 }
13884 
13885 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13886                                   SourceLocation NameLoc, IdentifierInfo *Name,
13887                                   QualType T, TypeSourceInfo *TSInfo,
13888                                   StorageClass SC) {
13889   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13890   if (getLangOpts().ObjCAutoRefCount &&
13891       T.getObjCLifetime() == Qualifiers::OCL_None &&
13892       T->isObjCLifetimeType()) {
13893 
13894     Qualifiers::ObjCLifetime lifetime;
13895 
13896     // Special cases for arrays:
13897     //   - if it's const, use __unsafe_unretained
13898     //   - otherwise, it's an error
13899     if (T->isArrayType()) {
13900       if (!T.isConstQualified()) {
13901         if (DelayedDiagnostics.shouldDelayDiagnostics())
13902           DelayedDiagnostics.add(
13903               sema::DelayedDiagnostic::makeForbiddenType(
13904               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13905         else
13906           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13907               << TSInfo->getTypeLoc().getSourceRange();
13908       }
13909       lifetime = Qualifiers::OCL_ExplicitNone;
13910     } else {
13911       lifetime = T->getObjCARCImplicitLifetime();
13912     }
13913     T = Context.getLifetimeQualifiedType(T, lifetime);
13914   }
13915 
13916   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13917                                          Context.getAdjustedParameterType(T),
13918                                          TSInfo, SC, nullptr);
13919 
13920   // Make a note if we created a new pack in the scope of a lambda, so that
13921   // we know that references to that pack must also be expanded within the
13922   // lambda scope.
13923   if (New->isParameterPack())
13924     if (auto *LSI = getEnclosingLambda())
13925       LSI->LocalPacks.push_back(New);
13926 
13927   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13928       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13929     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13930                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13931 
13932   // Parameters can not be abstract class types.
13933   // For record types, this is done by the AbstractClassUsageDiagnoser once
13934   // the class has been completely parsed.
13935   if (!CurContext->isRecord() &&
13936       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13937                              AbstractParamType))
13938     New->setInvalidDecl();
13939 
13940   // Parameter declarators cannot be interface types. All ObjC objects are
13941   // passed by reference.
13942   if (T->isObjCObjectType()) {
13943     SourceLocation TypeEndLoc =
13944         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13945     Diag(NameLoc,
13946          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13947       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13948     T = Context.getObjCObjectPointerType(T);
13949     New->setType(T);
13950   }
13951 
13952   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13953   // duration shall not be qualified by an address-space qualifier."
13954   // Since all parameters have automatic store duration, they can not have
13955   // an address space.
13956   if (T.getAddressSpace() != LangAS::Default &&
13957       // OpenCL allows function arguments declared to be an array of a type
13958       // to be qualified with an address space.
13959       !(getLangOpts().OpenCL &&
13960         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13961     Diag(NameLoc, diag::err_arg_with_address_space);
13962     New->setInvalidDecl();
13963   }
13964 
13965   // PPC MMA non-pointer types are not allowed as function argument types.
13966   if (Context.getTargetInfo().getTriple().isPPC64() &&
13967       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13968     New->setInvalidDecl();
13969   }
13970 
13971   return New;
13972 }
13973 
13974 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13975                                            SourceLocation LocAfterDecls) {
13976   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13977 
13978   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13979   // for a K&R function.
13980   if (!FTI.hasPrototype) {
13981     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13982       --i;
13983       if (FTI.Params[i].Param == nullptr) {
13984         SmallString<256> Code;
13985         llvm::raw_svector_ostream(Code)
13986             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13987         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13988             << FTI.Params[i].Ident
13989             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13990 
13991         // Implicitly declare the argument as type 'int' for lack of a better
13992         // type.
13993         AttributeFactory attrs;
13994         DeclSpec DS(attrs);
13995         const char* PrevSpec; // unused
13996         unsigned DiagID; // unused
13997         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13998                            DiagID, Context.getPrintingPolicy());
13999         // Use the identifier location for the type source range.
14000         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14001         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14002         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14003         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14004         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14005       }
14006     }
14007   }
14008 }
14009 
14010 Decl *
14011 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14012                               MultiTemplateParamsArg TemplateParameterLists,
14013                               SkipBodyInfo *SkipBody) {
14014   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14015   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14016   Scope *ParentScope = FnBodyScope->getParent();
14017 
14018   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14019   // we define a non-templated function definition, we will create a declaration
14020   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14021   // The base function declaration will have the equivalent of an `omp declare
14022   // variant` annotation which specifies the mangled definition as a
14023   // specialization function under the OpenMP context defined as part of the
14024   // `omp begin declare variant`.
14025   SmallVector<FunctionDecl *, 4> Bases;
14026   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14027     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14028         ParentScope, D, TemplateParameterLists, Bases);
14029 
14030   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14031   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14032   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14033 
14034   if (!Bases.empty())
14035     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14036 
14037   return Dcl;
14038 }
14039 
14040 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14041   Consumer.HandleInlineFunctionDefinition(D);
14042 }
14043 
14044 static bool
14045 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14046                                 const FunctionDecl *&PossiblePrototype) {
14047   // Don't warn about invalid declarations.
14048   if (FD->isInvalidDecl())
14049     return false;
14050 
14051   // Or declarations that aren't global.
14052   if (!FD->isGlobal())
14053     return false;
14054 
14055   // Don't warn about C++ member functions.
14056   if (isa<CXXMethodDecl>(FD))
14057     return false;
14058 
14059   // Don't warn about 'main'.
14060   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14061     if (IdentifierInfo *II = FD->getIdentifier())
14062       if (II->isStr("main") || II->isStr("efi_main"))
14063         return false;
14064 
14065   // Don't warn about inline functions.
14066   if (FD->isInlined())
14067     return false;
14068 
14069   // Don't warn about function templates.
14070   if (FD->getDescribedFunctionTemplate())
14071     return false;
14072 
14073   // Don't warn about function template specializations.
14074   if (FD->isFunctionTemplateSpecialization())
14075     return false;
14076 
14077   // Don't warn for OpenCL kernels.
14078   if (FD->hasAttr<OpenCLKernelAttr>())
14079     return false;
14080 
14081   // Don't warn on explicitly deleted functions.
14082   if (FD->isDeleted())
14083     return false;
14084 
14085   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14086        Prev; Prev = Prev->getPreviousDecl()) {
14087     // Ignore any declarations that occur in function or method
14088     // scope, because they aren't visible from the header.
14089     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14090       continue;
14091 
14092     PossiblePrototype = Prev;
14093     return Prev->getType()->isFunctionNoProtoType();
14094   }
14095 
14096   return true;
14097 }
14098 
14099 void
14100 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14101                                    const FunctionDecl *EffectiveDefinition,
14102                                    SkipBodyInfo *SkipBody) {
14103   const FunctionDecl *Definition = EffectiveDefinition;
14104   if (!Definition &&
14105       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14106     return;
14107 
14108   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14109     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14110       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14111         // A merged copy of the same function, instantiated as a member of
14112         // the same class, is OK.
14113         if (declaresSameEntity(OrigFD, OrigDef) &&
14114             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14115                                cast<Decl>(FD->getLexicalDeclContext())))
14116           return;
14117       }
14118     }
14119   }
14120 
14121   if (canRedefineFunction(Definition, getLangOpts()))
14122     return;
14123 
14124   // Don't emit an error when this is redefinition of a typo-corrected
14125   // definition.
14126   if (TypoCorrectedFunctionDefinitions.count(Definition))
14127     return;
14128 
14129   // If we don't have a visible definition of the function, and it's inline or
14130   // a template, skip the new definition.
14131   if (SkipBody && !hasVisibleDefinition(Definition) &&
14132       (Definition->getFormalLinkage() == InternalLinkage ||
14133        Definition->isInlined() ||
14134        Definition->getDescribedFunctionTemplate() ||
14135        Definition->getNumTemplateParameterLists())) {
14136     SkipBody->ShouldSkip = true;
14137     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14138     if (auto *TD = Definition->getDescribedFunctionTemplate())
14139       makeMergedDefinitionVisible(TD);
14140     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14141     return;
14142   }
14143 
14144   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14145       Definition->getStorageClass() == SC_Extern)
14146     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14147         << FD << getLangOpts().CPlusPlus;
14148   else
14149     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14150 
14151   Diag(Definition->getLocation(), diag::note_previous_definition);
14152   FD->setInvalidDecl();
14153 }
14154 
14155 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14156                                    Sema &S) {
14157   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14158 
14159   LambdaScopeInfo *LSI = S.PushLambdaScope();
14160   LSI->CallOperator = CallOperator;
14161   LSI->Lambda = LambdaClass;
14162   LSI->ReturnType = CallOperator->getReturnType();
14163   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14164 
14165   if (LCD == LCD_None)
14166     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14167   else if (LCD == LCD_ByCopy)
14168     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14169   else if (LCD == LCD_ByRef)
14170     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14171   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14172 
14173   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14174   LSI->Mutable = !CallOperator->isConst();
14175 
14176   // Add the captures to the LSI so they can be noted as already
14177   // captured within tryCaptureVar.
14178   auto I = LambdaClass->field_begin();
14179   for (const auto &C : LambdaClass->captures()) {
14180     if (C.capturesVariable()) {
14181       VarDecl *VD = C.getCapturedVar();
14182       if (VD->isInitCapture())
14183         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14184       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14185       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14186           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14187           /*EllipsisLoc*/C.isPackExpansion()
14188                          ? C.getEllipsisLoc() : SourceLocation(),
14189           I->getType(), /*Invalid*/false);
14190 
14191     } else if (C.capturesThis()) {
14192       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14193                           C.getCaptureKind() == LCK_StarThis);
14194     } else {
14195       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14196                              I->getType());
14197     }
14198     ++I;
14199   }
14200 }
14201 
14202 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14203                                     SkipBodyInfo *SkipBody) {
14204   if (!D) {
14205     // Parsing the function declaration failed in some way. Push on a fake scope
14206     // anyway so we can try to parse the function body.
14207     PushFunctionScope();
14208     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14209     return D;
14210   }
14211 
14212   FunctionDecl *FD = nullptr;
14213 
14214   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14215     FD = FunTmpl->getTemplatedDecl();
14216   else
14217     FD = cast<FunctionDecl>(D);
14218 
14219   // Do not push if it is a lambda because one is already pushed when building
14220   // the lambda in ActOnStartOfLambdaDefinition().
14221   if (!isLambdaCallOperator(FD))
14222     PushExpressionEvaluationContext(
14223         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14224                           : ExprEvalContexts.back().Context);
14225 
14226   // Check for defining attributes before the check for redefinition.
14227   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14228     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14229     FD->dropAttr<AliasAttr>();
14230     FD->setInvalidDecl();
14231   }
14232   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14233     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14234     FD->dropAttr<IFuncAttr>();
14235     FD->setInvalidDecl();
14236   }
14237 
14238   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14239     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14240         Ctor->isDefaultConstructor() &&
14241         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14242       // If this is an MS ABI dllexport default constructor, instantiate any
14243       // default arguments.
14244       InstantiateDefaultCtorDefaultArgs(Ctor);
14245     }
14246   }
14247 
14248   // See if this is a redefinition. If 'will have body' (or similar) is already
14249   // set, then these checks were already performed when it was set.
14250   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14251       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14252     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14253 
14254     // If we're skipping the body, we're done. Don't enter the scope.
14255     if (SkipBody && SkipBody->ShouldSkip)
14256       return D;
14257   }
14258 
14259   // Mark this function as "will have a body eventually".  This lets users to
14260   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14261   // this function.
14262   FD->setWillHaveBody();
14263 
14264   // If we are instantiating a generic lambda call operator, push
14265   // a LambdaScopeInfo onto the function stack.  But use the information
14266   // that's already been calculated (ActOnLambdaExpr) to prime the current
14267   // LambdaScopeInfo.
14268   // When the template operator is being specialized, the LambdaScopeInfo,
14269   // has to be properly restored so that tryCaptureVariable doesn't try
14270   // and capture any new variables. In addition when calculating potential
14271   // captures during transformation of nested lambdas, it is necessary to
14272   // have the LSI properly restored.
14273   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14274     assert(inTemplateInstantiation() &&
14275            "There should be an active template instantiation on the stack "
14276            "when instantiating a generic lambda!");
14277     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14278   } else {
14279     // Enter a new function scope
14280     PushFunctionScope();
14281   }
14282 
14283   // Builtin functions cannot be defined.
14284   if (unsigned BuiltinID = FD->getBuiltinID()) {
14285     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14286         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14287       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14288       FD->setInvalidDecl();
14289     }
14290   }
14291 
14292   // The return type of a function definition must be complete
14293   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14294   QualType ResultType = FD->getReturnType();
14295   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14296       !FD->isInvalidDecl() &&
14297       RequireCompleteType(FD->getLocation(), ResultType,
14298                           diag::err_func_def_incomplete_result))
14299     FD->setInvalidDecl();
14300 
14301   if (FnBodyScope)
14302     PushDeclContext(FnBodyScope, FD);
14303 
14304   // Check the validity of our function parameters
14305   CheckParmsForFunctionDef(FD->parameters(),
14306                            /*CheckParameterNames=*/true);
14307 
14308   // Add non-parameter declarations already in the function to the current
14309   // scope.
14310   if (FnBodyScope) {
14311     for (Decl *NPD : FD->decls()) {
14312       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14313       if (!NonParmDecl)
14314         continue;
14315       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14316              "parameters should not be in newly created FD yet");
14317 
14318       // If the decl has a name, make it accessible in the current scope.
14319       if (NonParmDecl->getDeclName())
14320         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14321 
14322       // Similarly, dive into enums and fish their constants out, making them
14323       // accessible in this scope.
14324       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14325         for (auto *EI : ED->enumerators())
14326           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14327       }
14328     }
14329   }
14330 
14331   // Introduce our parameters into the function scope
14332   for (auto Param : FD->parameters()) {
14333     Param->setOwningFunction(FD);
14334 
14335     // If this has an identifier, add it to the scope stack.
14336     if (Param->getIdentifier() && FnBodyScope) {
14337       CheckShadow(FnBodyScope, Param);
14338 
14339       PushOnScopeChains(Param, FnBodyScope);
14340     }
14341   }
14342 
14343   // Ensure that the function's exception specification is instantiated.
14344   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14345     ResolveExceptionSpec(D->getLocation(), FPT);
14346 
14347   // dllimport cannot be applied to non-inline function definitions.
14348   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14349       !FD->isTemplateInstantiation()) {
14350     assert(!FD->hasAttr<DLLExportAttr>());
14351     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14352     FD->setInvalidDecl();
14353     return D;
14354   }
14355   // We want to attach documentation to original Decl (which might be
14356   // a function template).
14357   ActOnDocumentableDecl(D);
14358   if (getCurLexicalContext()->isObjCContainer() &&
14359       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14360       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14361     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14362 
14363   return D;
14364 }
14365 
14366 /// Given the set of return statements within a function body,
14367 /// compute the variables that are subject to the named return value
14368 /// optimization.
14369 ///
14370 /// Each of the variables that is subject to the named return value
14371 /// optimization will be marked as NRVO variables in the AST, and any
14372 /// return statement that has a marked NRVO variable as its NRVO candidate can
14373 /// use the named return value optimization.
14374 ///
14375 /// This function applies a very simplistic algorithm for NRVO: if every return
14376 /// statement in the scope of a variable has the same NRVO candidate, that
14377 /// candidate is an NRVO variable.
14378 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14379   ReturnStmt **Returns = Scope->Returns.data();
14380 
14381   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14382     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14383       if (!NRVOCandidate->isNRVOVariable())
14384         Returns[I]->setNRVOCandidate(nullptr);
14385     }
14386   }
14387 }
14388 
14389 bool Sema::canDelayFunctionBody(const Declarator &D) {
14390   // We can't delay parsing the body of a constexpr function template (yet).
14391   if (D.getDeclSpec().hasConstexprSpecifier())
14392     return false;
14393 
14394   // We can't delay parsing the body of a function template with a deduced
14395   // return type (yet).
14396   if (D.getDeclSpec().hasAutoTypeSpec()) {
14397     // If the placeholder introduces a non-deduced trailing return type,
14398     // we can still delay parsing it.
14399     if (D.getNumTypeObjects()) {
14400       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14401       if (Outer.Kind == DeclaratorChunk::Function &&
14402           Outer.Fun.hasTrailingReturnType()) {
14403         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14404         return Ty.isNull() || !Ty->isUndeducedType();
14405       }
14406     }
14407     return false;
14408   }
14409 
14410   return true;
14411 }
14412 
14413 bool Sema::canSkipFunctionBody(Decl *D) {
14414   // We cannot skip the body of a function (or function template) which is
14415   // constexpr, since we may need to evaluate its body in order to parse the
14416   // rest of the file.
14417   // We cannot skip the body of a function with an undeduced return type,
14418   // because any callers of that function need to know the type.
14419   if (const FunctionDecl *FD = D->getAsFunction()) {
14420     if (FD->isConstexpr())
14421       return false;
14422     // We can't simply call Type::isUndeducedType here, because inside template
14423     // auto can be deduced to a dependent type, which is not considered
14424     // "undeduced".
14425     if (FD->getReturnType()->getContainedDeducedType())
14426       return false;
14427   }
14428   return Consumer.shouldSkipFunctionBody(D);
14429 }
14430 
14431 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14432   if (!Decl)
14433     return nullptr;
14434   if (FunctionDecl *FD = Decl->getAsFunction())
14435     FD->setHasSkippedBody();
14436   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14437     MD->setHasSkippedBody();
14438   return Decl;
14439 }
14440 
14441 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14442   return ActOnFinishFunctionBody(D, BodyArg, false);
14443 }
14444 
14445 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14446 /// body.
14447 class ExitFunctionBodyRAII {
14448 public:
14449   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14450   ~ExitFunctionBodyRAII() {
14451     if (!IsLambda)
14452       S.PopExpressionEvaluationContext();
14453   }
14454 
14455 private:
14456   Sema &S;
14457   bool IsLambda = false;
14458 };
14459 
14460 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14461   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14462 
14463   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14464     if (EscapeInfo.count(BD))
14465       return EscapeInfo[BD];
14466 
14467     bool R = false;
14468     const BlockDecl *CurBD = BD;
14469 
14470     do {
14471       R = !CurBD->doesNotEscape();
14472       if (R)
14473         break;
14474       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14475     } while (CurBD);
14476 
14477     return EscapeInfo[BD] = R;
14478   };
14479 
14480   // If the location where 'self' is implicitly retained is inside a escaping
14481   // block, emit a diagnostic.
14482   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14483        S.ImplicitlyRetainedSelfLocs)
14484     if (IsOrNestedInEscapingBlock(P.second))
14485       S.Diag(P.first, diag::warn_implicitly_retains_self)
14486           << FixItHint::CreateInsertion(P.first, "self->");
14487 }
14488 
14489 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14490                                     bool IsInstantiation) {
14491   FunctionScopeInfo *FSI = getCurFunction();
14492   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14493 
14494   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14495     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14496 
14497   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14498   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14499 
14500   if (getLangOpts().Coroutines && FSI->isCoroutine())
14501     CheckCompletedCoroutineBody(FD, Body);
14502 
14503   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14504   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14505   // meant to pop the context added in ActOnStartOfFunctionDef().
14506   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14507 
14508   if (FD) {
14509     FD->setBody(Body);
14510     FD->setWillHaveBody(false);
14511 
14512     if (getLangOpts().CPlusPlus14) {
14513       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14514           FD->getReturnType()->isUndeducedType()) {
14515         // If the function has a deduced result type but contains no 'return'
14516         // statements, the result type as written must be exactly 'auto', and
14517         // the deduced result type is 'void'.
14518         if (!FD->getReturnType()->getAs<AutoType>()) {
14519           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14520               << FD->getReturnType();
14521           FD->setInvalidDecl();
14522         } else {
14523           // Substitute 'void' for the 'auto' in the type.
14524           TypeLoc ResultType = getReturnTypeLoc(FD);
14525           Context.adjustDeducedFunctionResultType(
14526               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14527         }
14528       }
14529     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14530       // In C++11, we don't use 'auto' deduction rules for lambda call
14531       // operators because we don't support return type deduction.
14532       auto *LSI = getCurLambda();
14533       if (LSI->HasImplicitReturnType) {
14534         deduceClosureReturnType(*LSI);
14535 
14536         // C++11 [expr.prim.lambda]p4:
14537         //   [...] if there are no return statements in the compound-statement
14538         //   [the deduced type is] the type void
14539         QualType RetType =
14540             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14541 
14542         // Update the return type to the deduced type.
14543         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14544         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14545                                             Proto->getExtProtoInfo()));
14546       }
14547     }
14548 
14549     // If the function implicitly returns zero (like 'main') or is naked,
14550     // don't complain about missing return statements.
14551     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14552       WP.disableCheckFallThrough();
14553 
14554     // MSVC permits the use of pure specifier (=0) on function definition,
14555     // defined at class scope, warn about this non-standard construct.
14556     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14557       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14558 
14559     if (!FD->isInvalidDecl()) {
14560       // Don't diagnose unused parameters of defaulted or deleted functions.
14561       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14562         DiagnoseUnusedParameters(FD->parameters());
14563       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14564                                              FD->getReturnType(), FD);
14565 
14566       // If this is a structor, we need a vtable.
14567       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14568         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14569       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14570         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14571 
14572       // Try to apply the named return value optimization. We have to check
14573       // if we can do this here because lambdas keep return statements around
14574       // to deduce an implicit return type.
14575       if (FD->getReturnType()->isRecordType() &&
14576           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14577         computeNRVO(Body, FSI);
14578     }
14579 
14580     // GNU warning -Wmissing-prototypes:
14581     //   Warn if a global function is defined without a previous
14582     //   prototype declaration. This warning is issued even if the
14583     //   definition itself provides a prototype. The aim is to detect
14584     //   global functions that fail to be declared in header files.
14585     const FunctionDecl *PossiblePrototype = nullptr;
14586     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14587       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14588 
14589       if (PossiblePrototype) {
14590         // We found a declaration that is not a prototype,
14591         // but that could be a zero-parameter prototype
14592         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14593           TypeLoc TL = TI->getTypeLoc();
14594           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14595             Diag(PossiblePrototype->getLocation(),
14596                  diag::note_declaration_not_a_prototype)
14597                 << (FD->getNumParams() != 0)
14598                 << (FD->getNumParams() == 0
14599                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14600                         : FixItHint{});
14601         }
14602       } else {
14603         // Returns true if the token beginning at this Loc is `const`.
14604         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14605                                 const LangOptions &LangOpts) {
14606           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14607           if (LocInfo.first.isInvalid())
14608             return false;
14609 
14610           bool Invalid = false;
14611           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14612           if (Invalid)
14613             return false;
14614 
14615           if (LocInfo.second > Buffer.size())
14616             return false;
14617 
14618           const char *LexStart = Buffer.data() + LocInfo.second;
14619           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14620 
14621           return StartTok.consume_front("const") &&
14622                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14623                   StartTok.startswith("/*") || StartTok.startswith("//"));
14624         };
14625 
14626         auto findBeginLoc = [&]() {
14627           // If the return type has `const` qualifier, we want to insert
14628           // `static` before `const` (and not before the typename).
14629           if ((FD->getReturnType()->isAnyPointerType() &&
14630                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14631               FD->getReturnType().isConstQualified()) {
14632             // But only do this if we can determine where the `const` is.
14633 
14634             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14635                              getLangOpts()))
14636 
14637               return FD->getBeginLoc();
14638           }
14639           return FD->getTypeSpecStartLoc();
14640         };
14641         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14642             << /* function */ 1
14643             << (FD->getStorageClass() == SC_None
14644                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14645                     : FixItHint{});
14646       }
14647 
14648       // GNU warning -Wstrict-prototypes
14649       //   Warn if K&R function is defined without a previous declaration.
14650       //   This warning is issued only if the definition itself does not provide
14651       //   a prototype. Only K&R definitions do not provide a prototype.
14652       if (!FD->hasWrittenPrototype()) {
14653         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14654         TypeLoc TL = TI->getTypeLoc();
14655         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14656         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14657       }
14658     }
14659 
14660     // Warn on CPUDispatch with an actual body.
14661     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14662       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14663         if (!CmpndBody->body_empty())
14664           Diag(CmpndBody->body_front()->getBeginLoc(),
14665                diag::warn_dispatch_body_ignored);
14666 
14667     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14668       const CXXMethodDecl *KeyFunction;
14669       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14670           MD->isVirtual() &&
14671           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14672           MD == KeyFunction->getCanonicalDecl()) {
14673         // Update the key-function state if necessary for this ABI.
14674         if (FD->isInlined() &&
14675             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14676           Context.setNonKeyFunction(MD);
14677 
14678           // If the newly-chosen key function is already defined, then we
14679           // need to mark the vtable as used retroactively.
14680           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14681           const FunctionDecl *Definition;
14682           if (KeyFunction && KeyFunction->isDefined(Definition))
14683             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14684         } else {
14685           // We just defined they key function; mark the vtable as used.
14686           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14687         }
14688       }
14689     }
14690 
14691     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14692            "Function parsing confused");
14693   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14694     assert(MD == getCurMethodDecl() && "Method parsing confused");
14695     MD->setBody(Body);
14696     if (!MD->isInvalidDecl()) {
14697       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14698                                              MD->getReturnType(), MD);
14699 
14700       if (Body)
14701         computeNRVO(Body, FSI);
14702     }
14703     if (FSI->ObjCShouldCallSuper) {
14704       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14705           << MD->getSelector().getAsString();
14706       FSI->ObjCShouldCallSuper = false;
14707     }
14708     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14709       const ObjCMethodDecl *InitMethod = nullptr;
14710       bool isDesignated =
14711           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14712       assert(isDesignated && InitMethod);
14713       (void)isDesignated;
14714 
14715       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14716         auto IFace = MD->getClassInterface();
14717         if (!IFace)
14718           return false;
14719         auto SuperD = IFace->getSuperClass();
14720         if (!SuperD)
14721           return false;
14722         return SuperD->getIdentifier() ==
14723             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14724       };
14725       // Don't issue this warning for unavailable inits or direct subclasses
14726       // of NSObject.
14727       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14728         Diag(MD->getLocation(),
14729              diag::warn_objc_designated_init_missing_super_call);
14730         Diag(InitMethod->getLocation(),
14731              diag::note_objc_designated_init_marked_here);
14732       }
14733       FSI->ObjCWarnForNoDesignatedInitChain = false;
14734     }
14735     if (FSI->ObjCWarnForNoInitDelegation) {
14736       // Don't issue this warning for unavaialable inits.
14737       if (!MD->isUnavailable())
14738         Diag(MD->getLocation(),
14739              diag::warn_objc_secondary_init_missing_init_call);
14740       FSI->ObjCWarnForNoInitDelegation = false;
14741     }
14742 
14743     diagnoseImplicitlyRetainedSelf(*this);
14744   } else {
14745     // Parsing the function declaration failed in some way. Pop the fake scope
14746     // we pushed on.
14747     PopFunctionScopeInfo(ActivePolicy, dcl);
14748     return nullptr;
14749   }
14750 
14751   if (Body && FSI->HasPotentialAvailabilityViolations)
14752     DiagnoseUnguardedAvailabilityViolations(dcl);
14753 
14754   assert(!FSI->ObjCShouldCallSuper &&
14755          "This should only be set for ObjC methods, which should have been "
14756          "handled in the block above.");
14757 
14758   // Verify and clean out per-function state.
14759   if (Body && (!FD || !FD->isDefaulted())) {
14760     // C++ constructors that have function-try-blocks can't have return
14761     // statements in the handlers of that block. (C++ [except.handle]p14)
14762     // Verify this.
14763     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14764       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14765 
14766     // Verify that gotos and switch cases don't jump into scopes illegally.
14767     if (FSI->NeedsScopeChecking() &&
14768         !PP.isCodeCompletionEnabled())
14769       DiagnoseInvalidJumps(Body);
14770 
14771     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14772       if (!Destructor->getParent()->isDependentType())
14773         CheckDestructor(Destructor);
14774 
14775       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14776                                              Destructor->getParent());
14777     }
14778 
14779     // If any errors have occurred, clear out any temporaries that may have
14780     // been leftover. This ensures that these temporaries won't be picked up for
14781     // deletion in some later function.
14782     if (hasUncompilableErrorOccurred() ||
14783         getDiagnostics().getSuppressAllDiagnostics()) {
14784       DiscardCleanupsInEvaluationContext();
14785     }
14786     if (!hasUncompilableErrorOccurred() &&
14787         !isa<FunctionTemplateDecl>(dcl)) {
14788       // Since the body is valid, issue any analysis-based warnings that are
14789       // enabled.
14790       ActivePolicy = &WP;
14791     }
14792 
14793     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14794         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14795       FD->setInvalidDecl();
14796 
14797     if (FD && FD->hasAttr<NakedAttr>()) {
14798       for (const Stmt *S : Body->children()) {
14799         // Allow local register variables without initializer as they don't
14800         // require prologue.
14801         bool RegisterVariables = false;
14802         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14803           for (const auto *Decl : DS->decls()) {
14804             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14805               RegisterVariables =
14806                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14807               if (!RegisterVariables)
14808                 break;
14809             }
14810           }
14811         }
14812         if (RegisterVariables)
14813           continue;
14814         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14815           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14816           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14817           FD->setInvalidDecl();
14818           break;
14819         }
14820       }
14821     }
14822 
14823     assert(ExprCleanupObjects.size() ==
14824                ExprEvalContexts.back().NumCleanupObjects &&
14825            "Leftover temporaries in function");
14826     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14827     assert(MaybeODRUseExprs.empty() &&
14828            "Leftover expressions for odr-use checking");
14829   }
14830 
14831   if (!IsInstantiation)
14832     PopDeclContext();
14833 
14834   PopFunctionScopeInfo(ActivePolicy, dcl);
14835   // If any errors have occurred, clear out any temporaries that may have
14836   // been leftover. This ensures that these temporaries won't be picked up for
14837   // deletion in some later function.
14838   if (hasUncompilableErrorOccurred()) {
14839     DiscardCleanupsInEvaluationContext();
14840   }
14841 
14842   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14843     auto ES = getEmissionStatus(FD);
14844     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14845         ES == Sema::FunctionEmissionStatus::Unknown)
14846       DeclsToCheckForDeferredDiags.insert(FD);
14847   }
14848 
14849   return dcl;
14850 }
14851 
14852 /// When we finish delayed parsing of an attribute, we must attach it to the
14853 /// relevant Decl.
14854 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14855                                        ParsedAttributes &Attrs) {
14856   // Always attach attributes to the underlying decl.
14857   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14858     D = TD->getTemplatedDecl();
14859   ProcessDeclAttributeList(S, D, Attrs);
14860 
14861   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14862     if (Method->isStatic())
14863       checkThisInStaticMemberFunctionAttributes(Method);
14864 }
14865 
14866 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14867 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14868 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14869                                           IdentifierInfo &II, Scope *S) {
14870   // Find the scope in which the identifier is injected and the corresponding
14871   // DeclContext.
14872   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14873   // In that case, we inject the declaration into the translation unit scope
14874   // instead.
14875   Scope *BlockScope = S;
14876   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14877     BlockScope = BlockScope->getParent();
14878 
14879   Scope *ContextScope = BlockScope;
14880   while (!ContextScope->getEntity())
14881     ContextScope = ContextScope->getParent();
14882   ContextRAII SavedContext(*this, ContextScope->getEntity());
14883 
14884   // Before we produce a declaration for an implicitly defined
14885   // function, see whether there was a locally-scoped declaration of
14886   // this name as a function or variable. If so, use that
14887   // (non-visible) declaration, and complain about it.
14888   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14889   if (ExternCPrev) {
14890     // We still need to inject the function into the enclosing block scope so
14891     // that later (non-call) uses can see it.
14892     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14893 
14894     // C89 footnote 38:
14895     //   If in fact it is not defined as having type "function returning int",
14896     //   the behavior is undefined.
14897     if (!isa<FunctionDecl>(ExternCPrev) ||
14898         !Context.typesAreCompatible(
14899             cast<FunctionDecl>(ExternCPrev)->getType(),
14900             Context.getFunctionNoProtoType(Context.IntTy))) {
14901       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14902           << ExternCPrev << !getLangOpts().C99;
14903       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14904       return ExternCPrev;
14905     }
14906   }
14907 
14908   // Extension in C99.  Legal in C90, but warn about it.
14909   unsigned diag_id;
14910   if (II.getName().startswith("__builtin_"))
14911     diag_id = diag::warn_builtin_unknown;
14912   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14913   else if (getLangOpts().OpenCL)
14914     diag_id = diag::err_opencl_implicit_function_decl;
14915   else if (getLangOpts().C99)
14916     diag_id = diag::ext_implicit_function_decl;
14917   else
14918     diag_id = diag::warn_implicit_function_decl;
14919   Diag(Loc, diag_id) << &II;
14920 
14921   // If we found a prior declaration of this function, don't bother building
14922   // another one. We've already pushed that one into scope, so there's nothing
14923   // more to do.
14924   if (ExternCPrev)
14925     return ExternCPrev;
14926 
14927   // Because typo correction is expensive, only do it if the implicit
14928   // function declaration is going to be treated as an error.
14929   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14930     TypoCorrection Corrected;
14931     DeclFilterCCC<FunctionDecl> CCC{};
14932     if (S && (Corrected =
14933                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14934                               S, nullptr, CCC, CTK_NonError)))
14935       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14936                    /*ErrorRecovery*/false);
14937   }
14938 
14939   // Set a Declarator for the implicit definition: int foo();
14940   const char *Dummy;
14941   AttributeFactory attrFactory;
14942   DeclSpec DS(attrFactory);
14943   unsigned DiagID;
14944   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14945                                   Context.getPrintingPolicy());
14946   (void)Error; // Silence warning.
14947   assert(!Error && "Error setting up implicit decl!");
14948   SourceLocation NoLoc;
14949   Declarator D(DS, DeclaratorContext::Block);
14950   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14951                                              /*IsAmbiguous=*/false,
14952                                              /*LParenLoc=*/NoLoc,
14953                                              /*Params=*/nullptr,
14954                                              /*NumParams=*/0,
14955                                              /*EllipsisLoc=*/NoLoc,
14956                                              /*RParenLoc=*/NoLoc,
14957                                              /*RefQualifierIsLvalueRef=*/true,
14958                                              /*RefQualifierLoc=*/NoLoc,
14959                                              /*MutableLoc=*/NoLoc, EST_None,
14960                                              /*ESpecRange=*/SourceRange(),
14961                                              /*Exceptions=*/nullptr,
14962                                              /*ExceptionRanges=*/nullptr,
14963                                              /*NumExceptions=*/0,
14964                                              /*NoexceptExpr=*/nullptr,
14965                                              /*ExceptionSpecTokens=*/nullptr,
14966                                              /*DeclsInPrototype=*/None, Loc,
14967                                              Loc, D),
14968                 std::move(DS.getAttributes()), SourceLocation());
14969   D.SetIdentifier(&II, Loc);
14970 
14971   // Insert this function into the enclosing block scope.
14972   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14973   FD->setImplicit();
14974 
14975   AddKnownFunctionAttributes(FD);
14976 
14977   return FD;
14978 }
14979 
14980 /// If this function is a C++ replaceable global allocation function
14981 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14982 /// adds any function attributes that we know a priori based on the standard.
14983 ///
14984 /// We need to check for duplicate attributes both here and where user-written
14985 /// attributes are applied to declarations.
14986 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14987     FunctionDecl *FD) {
14988   if (FD->isInvalidDecl())
14989     return;
14990 
14991   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14992       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14993     return;
14994 
14995   Optional<unsigned> AlignmentParam;
14996   bool IsNothrow = false;
14997   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14998     return;
14999 
15000   // C++2a [basic.stc.dynamic.allocation]p4:
15001   //   An allocation function that has a non-throwing exception specification
15002   //   indicates failure by returning a null pointer value. Any other allocation
15003   //   function never returns a null pointer value and indicates failure only by
15004   //   throwing an exception [...]
15005   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15006     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15007 
15008   // C++2a [basic.stc.dynamic.allocation]p2:
15009   //   An allocation function attempts to allocate the requested amount of
15010   //   storage. [...] If the request succeeds, the value returned by a
15011   //   replaceable allocation function is a [...] pointer value p0 different
15012   //   from any previously returned value p1 [...]
15013   //
15014   // However, this particular information is being added in codegen,
15015   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15016 
15017   // C++2a [basic.stc.dynamic.allocation]p2:
15018   //   An allocation function attempts to allocate the requested amount of
15019   //   storage. If it is successful, it returns the address of the start of a
15020   //   block of storage whose length in bytes is at least as large as the
15021   //   requested size.
15022   if (!FD->hasAttr<AllocSizeAttr>()) {
15023     FD->addAttr(AllocSizeAttr::CreateImplicit(
15024         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15025         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15026   }
15027 
15028   // C++2a [basic.stc.dynamic.allocation]p3:
15029   //   For an allocation function [...], the pointer returned on a successful
15030   //   call shall represent the address of storage that is aligned as follows:
15031   //   (3.1) If the allocation function takes an argument of type
15032   //         std​::​align_­val_­t, the storage will have the alignment
15033   //         specified by the value of this argument.
15034   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15035     FD->addAttr(AllocAlignAttr::CreateImplicit(
15036         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15037   }
15038 
15039   // FIXME:
15040   // C++2a [basic.stc.dynamic.allocation]p3:
15041   //   For an allocation function [...], the pointer returned on a successful
15042   //   call shall represent the address of storage that is aligned as follows:
15043   //   (3.2) Otherwise, if the allocation function is named operator new[],
15044   //         the storage is aligned for any object that does not have
15045   //         new-extended alignment ([basic.align]) and is no larger than the
15046   //         requested size.
15047   //   (3.3) Otherwise, the storage is aligned for any object that does not
15048   //         have new-extended alignment and is of the requested size.
15049 }
15050 
15051 /// Adds any function attributes that we know a priori based on
15052 /// the declaration of this function.
15053 ///
15054 /// These attributes can apply both to implicitly-declared builtins
15055 /// (like __builtin___printf_chk) or to library-declared functions
15056 /// like NSLog or printf.
15057 ///
15058 /// We need to check for duplicate attributes both here and where user-written
15059 /// attributes are applied to declarations.
15060 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15061   if (FD->isInvalidDecl())
15062     return;
15063 
15064   // If this is a built-in function, map its builtin attributes to
15065   // actual attributes.
15066   if (unsigned BuiltinID = FD->getBuiltinID()) {
15067     // Handle printf-formatting attributes.
15068     unsigned FormatIdx;
15069     bool HasVAListArg;
15070     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15071       if (!FD->hasAttr<FormatAttr>()) {
15072         const char *fmt = "printf";
15073         unsigned int NumParams = FD->getNumParams();
15074         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15075             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15076           fmt = "NSString";
15077         FD->addAttr(FormatAttr::CreateImplicit(Context,
15078                                                &Context.Idents.get(fmt),
15079                                                FormatIdx+1,
15080                                                HasVAListArg ? 0 : FormatIdx+2,
15081                                                FD->getLocation()));
15082       }
15083     }
15084     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15085                                              HasVAListArg)) {
15086      if (!FD->hasAttr<FormatAttr>())
15087        FD->addAttr(FormatAttr::CreateImplicit(Context,
15088                                               &Context.Idents.get("scanf"),
15089                                               FormatIdx+1,
15090                                               HasVAListArg ? 0 : FormatIdx+2,
15091                                               FD->getLocation()));
15092     }
15093 
15094     // Handle automatically recognized callbacks.
15095     SmallVector<int, 4> Encoding;
15096     if (!FD->hasAttr<CallbackAttr>() &&
15097         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15098       FD->addAttr(CallbackAttr::CreateImplicit(
15099           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15100 
15101     // Mark const if we don't care about errno and that is the only thing
15102     // preventing the function from being const. This allows IRgen to use LLVM
15103     // intrinsics for such functions.
15104     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15105         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15106       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15107 
15108     // We make "fma" on some platforms const because we know it does not set
15109     // errno in those environments even though it could set errno based on the
15110     // C standard.
15111     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15112     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15113         !FD->hasAttr<ConstAttr>()) {
15114       switch (BuiltinID) {
15115       case Builtin::BI__builtin_fma:
15116       case Builtin::BI__builtin_fmaf:
15117       case Builtin::BI__builtin_fmal:
15118       case Builtin::BIfma:
15119       case Builtin::BIfmaf:
15120       case Builtin::BIfmal:
15121         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15122         break;
15123       default:
15124         break;
15125       }
15126     }
15127 
15128     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15129         !FD->hasAttr<ReturnsTwiceAttr>())
15130       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15131                                          FD->getLocation()));
15132     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15133       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15134     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15135       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15136     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15137       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15138     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15139         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15140       // Add the appropriate attribute, depending on the CUDA compilation mode
15141       // and which target the builtin belongs to. For example, during host
15142       // compilation, aux builtins are __device__, while the rest are __host__.
15143       if (getLangOpts().CUDAIsDevice !=
15144           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15145         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15146       else
15147         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15148     }
15149   }
15150 
15151   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15152 
15153   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15154   // throw, add an implicit nothrow attribute to any extern "C" function we come
15155   // across.
15156   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15157       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15158     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15159     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15160       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15161   }
15162 
15163   IdentifierInfo *Name = FD->getIdentifier();
15164   if (!Name)
15165     return;
15166   if ((!getLangOpts().CPlusPlus &&
15167        FD->getDeclContext()->isTranslationUnit()) ||
15168       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15169        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15170        LinkageSpecDecl::lang_c)) {
15171     // Okay: this could be a libc/libm/Objective-C function we know
15172     // about.
15173   } else
15174     return;
15175 
15176   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15177     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15178     // target-specific builtins, perhaps?
15179     if (!FD->hasAttr<FormatAttr>())
15180       FD->addAttr(FormatAttr::CreateImplicit(Context,
15181                                              &Context.Idents.get("printf"), 2,
15182                                              Name->isStr("vasprintf") ? 0 : 3,
15183                                              FD->getLocation()));
15184   }
15185 
15186   if (Name->isStr("__CFStringMakeConstantString")) {
15187     // We already have a __builtin___CFStringMakeConstantString,
15188     // but builds that use -fno-constant-cfstrings don't go through that.
15189     if (!FD->hasAttr<FormatArgAttr>())
15190       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15191                                                 FD->getLocation()));
15192   }
15193 }
15194 
15195 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15196                                     TypeSourceInfo *TInfo) {
15197   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15198   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15199 
15200   if (!TInfo) {
15201     assert(D.isInvalidType() && "no declarator info for valid type");
15202     TInfo = Context.getTrivialTypeSourceInfo(T);
15203   }
15204 
15205   // Scope manipulation handled by caller.
15206   TypedefDecl *NewTD =
15207       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15208                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15209 
15210   // Bail out immediately if we have an invalid declaration.
15211   if (D.isInvalidType()) {
15212     NewTD->setInvalidDecl();
15213     return NewTD;
15214   }
15215 
15216   if (D.getDeclSpec().isModulePrivateSpecified()) {
15217     if (CurContext->isFunctionOrMethod())
15218       Diag(NewTD->getLocation(), diag::err_module_private_local)
15219           << 2 << NewTD
15220           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15221           << FixItHint::CreateRemoval(
15222                  D.getDeclSpec().getModulePrivateSpecLoc());
15223     else
15224       NewTD->setModulePrivate();
15225   }
15226 
15227   // C++ [dcl.typedef]p8:
15228   //   If the typedef declaration defines an unnamed class (or
15229   //   enum), the first typedef-name declared by the declaration
15230   //   to be that class type (or enum type) is used to denote the
15231   //   class type (or enum type) for linkage purposes only.
15232   // We need to check whether the type was declared in the declaration.
15233   switch (D.getDeclSpec().getTypeSpecType()) {
15234   case TST_enum:
15235   case TST_struct:
15236   case TST_interface:
15237   case TST_union:
15238   case TST_class: {
15239     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15240     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15241     break;
15242   }
15243 
15244   default:
15245     break;
15246   }
15247 
15248   return NewTD;
15249 }
15250 
15251 /// Check that this is a valid underlying type for an enum declaration.
15252 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15253   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15254   QualType T = TI->getType();
15255 
15256   if (T->isDependentType())
15257     return false;
15258 
15259   // This doesn't use 'isIntegralType' despite the error message mentioning
15260   // integral type because isIntegralType would also allow enum types in C.
15261   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15262     if (BT->isInteger())
15263       return false;
15264 
15265   if (T->isExtIntType())
15266     return false;
15267 
15268   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15269 }
15270 
15271 /// Check whether this is a valid redeclaration of a previous enumeration.
15272 /// \return true if the redeclaration was invalid.
15273 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15274                                   QualType EnumUnderlyingTy, bool IsFixed,
15275                                   const EnumDecl *Prev) {
15276   if (IsScoped != Prev->isScoped()) {
15277     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15278       << Prev->isScoped();
15279     Diag(Prev->getLocation(), diag::note_previous_declaration);
15280     return true;
15281   }
15282 
15283   if (IsFixed && Prev->isFixed()) {
15284     if (!EnumUnderlyingTy->isDependentType() &&
15285         !Prev->getIntegerType()->isDependentType() &&
15286         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15287                                         Prev->getIntegerType())) {
15288       // TODO: Highlight the underlying type of the redeclaration.
15289       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15290         << EnumUnderlyingTy << Prev->getIntegerType();
15291       Diag(Prev->getLocation(), diag::note_previous_declaration)
15292           << Prev->getIntegerTypeRange();
15293       return true;
15294     }
15295   } else if (IsFixed != Prev->isFixed()) {
15296     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15297       << Prev->isFixed();
15298     Diag(Prev->getLocation(), diag::note_previous_declaration);
15299     return true;
15300   }
15301 
15302   return false;
15303 }
15304 
15305 /// Get diagnostic %select index for tag kind for
15306 /// redeclaration diagnostic message.
15307 /// WARNING: Indexes apply to particular diagnostics only!
15308 ///
15309 /// \returns diagnostic %select index.
15310 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15311   switch (Tag) {
15312   case TTK_Struct: return 0;
15313   case TTK_Interface: return 1;
15314   case TTK_Class:  return 2;
15315   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15316   }
15317 }
15318 
15319 /// Determine if tag kind is a class-key compatible with
15320 /// class for redeclaration (class, struct, or __interface).
15321 ///
15322 /// \returns true iff the tag kind is compatible.
15323 static bool isClassCompatTagKind(TagTypeKind Tag)
15324 {
15325   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15326 }
15327 
15328 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15329                                              TagTypeKind TTK) {
15330   if (isa<TypedefDecl>(PrevDecl))
15331     return NTK_Typedef;
15332   else if (isa<TypeAliasDecl>(PrevDecl))
15333     return NTK_TypeAlias;
15334   else if (isa<ClassTemplateDecl>(PrevDecl))
15335     return NTK_Template;
15336   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15337     return NTK_TypeAliasTemplate;
15338   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15339     return NTK_TemplateTemplateArgument;
15340   switch (TTK) {
15341   case TTK_Struct:
15342   case TTK_Interface:
15343   case TTK_Class:
15344     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15345   case TTK_Union:
15346     return NTK_NonUnion;
15347   case TTK_Enum:
15348     return NTK_NonEnum;
15349   }
15350   llvm_unreachable("invalid TTK");
15351 }
15352 
15353 /// Determine whether a tag with a given kind is acceptable
15354 /// as a redeclaration of the given tag declaration.
15355 ///
15356 /// \returns true if the new tag kind is acceptable, false otherwise.
15357 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15358                                         TagTypeKind NewTag, bool isDefinition,
15359                                         SourceLocation NewTagLoc,
15360                                         const IdentifierInfo *Name) {
15361   // C++ [dcl.type.elab]p3:
15362   //   The class-key or enum keyword present in the
15363   //   elaborated-type-specifier shall agree in kind with the
15364   //   declaration to which the name in the elaborated-type-specifier
15365   //   refers. This rule also applies to the form of
15366   //   elaborated-type-specifier that declares a class-name or
15367   //   friend class since it can be construed as referring to the
15368   //   definition of the class. Thus, in any
15369   //   elaborated-type-specifier, the enum keyword shall be used to
15370   //   refer to an enumeration (7.2), the union class-key shall be
15371   //   used to refer to a union (clause 9), and either the class or
15372   //   struct class-key shall be used to refer to a class (clause 9)
15373   //   declared using the class or struct class-key.
15374   TagTypeKind OldTag = Previous->getTagKind();
15375   if (OldTag != NewTag &&
15376       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15377     return false;
15378 
15379   // Tags are compatible, but we might still want to warn on mismatched tags.
15380   // Non-class tags can't be mismatched at this point.
15381   if (!isClassCompatTagKind(NewTag))
15382     return true;
15383 
15384   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15385   // by our warning analysis. We don't want to warn about mismatches with (eg)
15386   // declarations in system headers that are designed to be specialized, but if
15387   // a user asks us to warn, we should warn if their code contains mismatched
15388   // declarations.
15389   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15390     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15391                                       Loc);
15392   };
15393   if (IsIgnoredLoc(NewTagLoc))
15394     return true;
15395 
15396   auto IsIgnored = [&](const TagDecl *Tag) {
15397     return IsIgnoredLoc(Tag->getLocation());
15398   };
15399   while (IsIgnored(Previous)) {
15400     Previous = Previous->getPreviousDecl();
15401     if (!Previous)
15402       return true;
15403     OldTag = Previous->getTagKind();
15404   }
15405 
15406   bool isTemplate = false;
15407   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15408     isTemplate = Record->getDescribedClassTemplate();
15409 
15410   if (inTemplateInstantiation()) {
15411     if (OldTag != NewTag) {
15412       // In a template instantiation, do not offer fix-its for tag mismatches
15413       // since they usually mess up the template instead of fixing the problem.
15414       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15415         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15416         << getRedeclDiagFromTagKind(OldTag);
15417       // FIXME: Note previous location?
15418     }
15419     return true;
15420   }
15421 
15422   if (isDefinition) {
15423     // On definitions, check all previous tags and issue a fix-it for each
15424     // one that doesn't match the current tag.
15425     if (Previous->getDefinition()) {
15426       // Don't suggest fix-its for redefinitions.
15427       return true;
15428     }
15429 
15430     bool previousMismatch = false;
15431     for (const TagDecl *I : Previous->redecls()) {
15432       if (I->getTagKind() != NewTag) {
15433         // Ignore previous declarations for which the warning was disabled.
15434         if (IsIgnored(I))
15435           continue;
15436 
15437         if (!previousMismatch) {
15438           previousMismatch = true;
15439           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15440             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15441             << getRedeclDiagFromTagKind(I->getTagKind());
15442         }
15443         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15444           << getRedeclDiagFromTagKind(NewTag)
15445           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15446                TypeWithKeyword::getTagTypeKindName(NewTag));
15447       }
15448     }
15449     return true;
15450   }
15451 
15452   // Identify the prevailing tag kind: this is the kind of the definition (if
15453   // there is a non-ignored definition), or otherwise the kind of the prior
15454   // (non-ignored) declaration.
15455   const TagDecl *PrevDef = Previous->getDefinition();
15456   if (PrevDef && IsIgnored(PrevDef))
15457     PrevDef = nullptr;
15458   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15459   if (Redecl->getTagKind() != NewTag) {
15460     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15461       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15462       << getRedeclDiagFromTagKind(OldTag);
15463     Diag(Redecl->getLocation(), diag::note_previous_use);
15464 
15465     // If there is a previous definition, suggest a fix-it.
15466     if (PrevDef) {
15467       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15468         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15469         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15470              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15471     }
15472   }
15473 
15474   return true;
15475 }
15476 
15477 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15478 /// from an outer enclosing namespace or file scope inside a friend declaration.
15479 /// This should provide the commented out code in the following snippet:
15480 ///   namespace N {
15481 ///     struct X;
15482 ///     namespace M {
15483 ///       struct Y { friend struct /*N::*/ X; };
15484 ///     }
15485 ///   }
15486 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15487                                          SourceLocation NameLoc) {
15488   // While the decl is in a namespace, do repeated lookup of that name and see
15489   // if we get the same namespace back.  If we do not, continue until
15490   // translation unit scope, at which point we have a fully qualified NNS.
15491   SmallVector<IdentifierInfo *, 4> Namespaces;
15492   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15493   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15494     // This tag should be declared in a namespace, which can only be enclosed by
15495     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15496     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15497     if (!Namespace || Namespace->isAnonymousNamespace())
15498       return FixItHint();
15499     IdentifierInfo *II = Namespace->getIdentifier();
15500     Namespaces.push_back(II);
15501     NamedDecl *Lookup = SemaRef.LookupSingleName(
15502         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15503     if (Lookup == Namespace)
15504       break;
15505   }
15506 
15507   // Once we have all the namespaces, reverse them to go outermost first, and
15508   // build an NNS.
15509   SmallString<64> Insertion;
15510   llvm::raw_svector_ostream OS(Insertion);
15511   if (DC->isTranslationUnit())
15512     OS << "::";
15513   std::reverse(Namespaces.begin(), Namespaces.end());
15514   for (auto *II : Namespaces)
15515     OS << II->getName() << "::";
15516   return FixItHint::CreateInsertion(NameLoc, Insertion);
15517 }
15518 
15519 /// Determine whether a tag originally declared in context \p OldDC can
15520 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15521 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15522 /// using-declaration).
15523 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15524                                          DeclContext *NewDC) {
15525   OldDC = OldDC->getRedeclContext();
15526   NewDC = NewDC->getRedeclContext();
15527 
15528   if (OldDC->Equals(NewDC))
15529     return true;
15530 
15531   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15532   // encloses the other).
15533   if (S.getLangOpts().MSVCCompat &&
15534       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15535     return true;
15536 
15537   return false;
15538 }
15539 
15540 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15541 /// former case, Name will be non-null.  In the later case, Name will be null.
15542 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15543 /// reference/declaration/definition of a tag.
15544 ///
15545 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15546 /// trailing-type-specifier) other than one in an alias-declaration.
15547 ///
15548 /// \param SkipBody If non-null, will be set to indicate if the caller should
15549 /// skip the definition of this tag and treat it as if it were a declaration.
15550 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15551                      SourceLocation KWLoc, CXXScopeSpec &SS,
15552                      IdentifierInfo *Name, SourceLocation NameLoc,
15553                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15554                      SourceLocation ModulePrivateLoc,
15555                      MultiTemplateParamsArg TemplateParameterLists,
15556                      bool &OwnedDecl, bool &IsDependent,
15557                      SourceLocation ScopedEnumKWLoc,
15558                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15559                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15560                      SkipBodyInfo *SkipBody) {
15561   // If this is not a definition, it must have a name.
15562   IdentifierInfo *OrigName = Name;
15563   assert((Name != nullptr || TUK == TUK_Definition) &&
15564          "Nameless record must be a definition!");
15565   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15566 
15567   OwnedDecl = false;
15568   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15569   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15570 
15571   // FIXME: Check member specializations more carefully.
15572   bool isMemberSpecialization = false;
15573   bool Invalid = false;
15574 
15575   // We only need to do this matching if we have template parameters
15576   // or a scope specifier, which also conveniently avoids this work
15577   // for non-C++ cases.
15578   if (TemplateParameterLists.size() > 0 ||
15579       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15580     if (TemplateParameterList *TemplateParams =
15581             MatchTemplateParametersToScopeSpecifier(
15582                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15583                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15584       if (Kind == TTK_Enum) {
15585         Diag(KWLoc, diag::err_enum_template);
15586         return nullptr;
15587       }
15588 
15589       if (TemplateParams->size() > 0) {
15590         // This is a declaration or definition of a class template (which may
15591         // be a member of another template).
15592 
15593         if (Invalid)
15594           return nullptr;
15595 
15596         OwnedDecl = false;
15597         DeclResult Result = CheckClassTemplate(
15598             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15599             AS, ModulePrivateLoc,
15600             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15601             TemplateParameterLists.data(), SkipBody);
15602         return Result.get();
15603       } else {
15604         // The "template<>" header is extraneous.
15605         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15606           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15607         isMemberSpecialization = true;
15608       }
15609     }
15610 
15611     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15612         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15613       return nullptr;
15614   }
15615 
15616   // Figure out the underlying type if this a enum declaration. We need to do
15617   // this early, because it's needed to detect if this is an incompatible
15618   // redeclaration.
15619   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15620   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15621 
15622   if (Kind == TTK_Enum) {
15623     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15624       // No underlying type explicitly specified, or we failed to parse the
15625       // type, default to int.
15626       EnumUnderlying = Context.IntTy.getTypePtr();
15627     } else if (UnderlyingType.get()) {
15628       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15629       // integral type; any cv-qualification is ignored.
15630       TypeSourceInfo *TI = nullptr;
15631       GetTypeFromParser(UnderlyingType.get(), &TI);
15632       EnumUnderlying = TI;
15633 
15634       if (CheckEnumUnderlyingType(TI))
15635         // Recover by falling back to int.
15636         EnumUnderlying = Context.IntTy.getTypePtr();
15637 
15638       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15639                                           UPPC_FixedUnderlyingType))
15640         EnumUnderlying = Context.IntTy.getTypePtr();
15641 
15642     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15643       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15644       // of 'int'. However, if this is an unfixed forward declaration, don't set
15645       // the underlying type unless the user enables -fms-compatibility. This
15646       // makes unfixed forward declared enums incomplete and is more conforming.
15647       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15648         EnumUnderlying = Context.IntTy.getTypePtr();
15649     }
15650   }
15651 
15652   DeclContext *SearchDC = CurContext;
15653   DeclContext *DC = CurContext;
15654   bool isStdBadAlloc = false;
15655   bool isStdAlignValT = false;
15656 
15657   RedeclarationKind Redecl = forRedeclarationInCurContext();
15658   if (TUK == TUK_Friend || TUK == TUK_Reference)
15659     Redecl = NotForRedeclaration;
15660 
15661   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15662   /// implemented asks for structural equivalence checking, the returned decl
15663   /// here is passed back to the parser, allowing the tag body to be parsed.
15664   auto createTagFromNewDecl = [&]() -> TagDecl * {
15665     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15666     // If there is an identifier, use the location of the identifier as the
15667     // location of the decl, otherwise use the location of the struct/union
15668     // keyword.
15669     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15670     TagDecl *New = nullptr;
15671 
15672     if (Kind == TTK_Enum) {
15673       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15674                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15675       // If this is an undefined enum, bail.
15676       if (TUK != TUK_Definition && !Invalid)
15677         return nullptr;
15678       if (EnumUnderlying) {
15679         EnumDecl *ED = cast<EnumDecl>(New);
15680         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15681           ED->setIntegerTypeSourceInfo(TI);
15682         else
15683           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15684         ED->setPromotionType(ED->getIntegerType());
15685       }
15686     } else { // struct/union
15687       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15688                                nullptr);
15689     }
15690 
15691     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15692       // Add alignment attributes if necessary; these attributes are checked
15693       // when the ASTContext lays out the structure.
15694       //
15695       // It is important for implementing the correct semantics that this
15696       // happen here (in ActOnTag). The #pragma pack stack is
15697       // maintained as a result of parser callbacks which can occur at
15698       // many points during the parsing of a struct declaration (because
15699       // the #pragma tokens are effectively skipped over during the
15700       // parsing of the struct).
15701       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15702         AddAlignmentAttributesForRecord(RD);
15703         AddMsStructLayoutForRecord(RD);
15704       }
15705     }
15706     New->setLexicalDeclContext(CurContext);
15707     return New;
15708   };
15709 
15710   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15711   if (Name && SS.isNotEmpty()) {
15712     // We have a nested-name tag ('struct foo::bar').
15713 
15714     // Check for invalid 'foo::'.
15715     if (SS.isInvalid()) {
15716       Name = nullptr;
15717       goto CreateNewDecl;
15718     }
15719 
15720     // If this is a friend or a reference to a class in a dependent
15721     // context, don't try to make a decl for it.
15722     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15723       DC = computeDeclContext(SS, false);
15724       if (!DC) {
15725         IsDependent = true;
15726         return nullptr;
15727       }
15728     } else {
15729       DC = computeDeclContext(SS, true);
15730       if (!DC) {
15731         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15732           << SS.getRange();
15733         return nullptr;
15734       }
15735     }
15736 
15737     if (RequireCompleteDeclContext(SS, DC))
15738       return nullptr;
15739 
15740     SearchDC = DC;
15741     // Look-up name inside 'foo::'.
15742     LookupQualifiedName(Previous, DC);
15743 
15744     if (Previous.isAmbiguous())
15745       return nullptr;
15746 
15747     if (Previous.empty()) {
15748       // Name lookup did not find anything. However, if the
15749       // nested-name-specifier refers to the current instantiation,
15750       // and that current instantiation has any dependent base
15751       // classes, we might find something at instantiation time: treat
15752       // this as a dependent elaborated-type-specifier.
15753       // But this only makes any sense for reference-like lookups.
15754       if (Previous.wasNotFoundInCurrentInstantiation() &&
15755           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15756         IsDependent = true;
15757         return nullptr;
15758       }
15759 
15760       // A tag 'foo::bar' must already exist.
15761       Diag(NameLoc, diag::err_not_tag_in_scope)
15762         << Kind << Name << DC << SS.getRange();
15763       Name = nullptr;
15764       Invalid = true;
15765       goto CreateNewDecl;
15766     }
15767   } else if (Name) {
15768     // C++14 [class.mem]p14:
15769     //   If T is the name of a class, then each of the following shall have a
15770     //   name different from T:
15771     //    -- every member of class T that is itself a type
15772     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15773         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15774       return nullptr;
15775 
15776     // If this is a named struct, check to see if there was a previous forward
15777     // declaration or definition.
15778     // FIXME: We're looking into outer scopes here, even when we
15779     // shouldn't be. Doing so can result in ambiguities that we
15780     // shouldn't be diagnosing.
15781     LookupName(Previous, S);
15782 
15783     // When declaring or defining a tag, ignore ambiguities introduced
15784     // by types using'ed into this scope.
15785     if (Previous.isAmbiguous() &&
15786         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15787       LookupResult::Filter F = Previous.makeFilter();
15788       while (F.hasNext()) {
15789         NamedDecl *ND = F.next();
15790         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15791                 SearchDC->getRedeclContext()))
15792           F.erase();
15793       }
15794       F.done();
15795     }
15796 
15797     // C++11 [namespace.memdef]p3:
15798     //   If the name in a friend declaration is neither qualified nor
15799     //   a template-id and the declaration is a function or an
15800     //   elaborated-type-specifier, the lookup to determine whether
15801     //   the entity has been previously declared shall not consider
15802     //   any scopes outside the innermost enclosing namespace.
15803     //
15804     // MSVC doesn't implement the above rule for types, so a friend tag
15805     // declaration may be a redeclaration of a type declared in an enclosing
15806     // scope.  They do implement this rule for friend functions.
15807     //
15808     // Does it matter that this should be by scope instead of by
15809     // semantic context?
15810     if (!Previous.empty() && TUK == TUK_Friend) {
15811       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15812       LookupResult::Filter F = Previous.makeFilter();
15813       bool FriendSawTagOutsideEnclosingNamespace = false;
15814       while (F.hasNext()) {
15815         NamedDecl *ND = F.next();
15816         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15817         if (DC->isFileContext() &&
15818             !EnclosingNS->Encloses(ND->getDeclContext())) {
15819           if (getLangOpts().MSVCCompat)
15820             FriendSawTagOutsideEnclosingNamespace = true;
15821           else
15822             F.erase();
15823         }
15824       }
15825       F.done();
15826 
15827       // Diagnose this MSVC extension in the easy case where lookup would have
15828       // unambiguously found something outside the enclosing namespace.
15829       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15830         NamedDecl *ND = Previous.getFoundDecl();
15831         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15832             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15833       }
15834     }
15835 
15836     // Note:  there used to be some attempt at recovery here.
15837     if (Previous.isAmbiguous())
15838       return nullptr;
15839 
15840     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15841       // FIXME: This makes sure that we ignore the contexts associated
15842       // with C structs, unions, and enums when looking for a matching
15843       // tag declaration or definition. See the similar lookup tweak
15844       // in Sema::LookupName; is there a better way to deal with this?
15845       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15846         SearchDC = SearchDC->getParent();
15847     }
15848   }
15849 
15850   if (Previous.isSingleResult() &&
15851       Previous.getFoundDecl()->isTemplateParameter()) {
15852     // Maybe we will complain about the shadowed template parameter.
15853     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15854     // Just pretend that we didn't see the previous declaration.
15855     Previous.clear();
15856   }
15857 
15858   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15859       DC->Equals(getStdNamespace())) {
15860     if (Name->isStr("bad_alloc")) {
15861       // This is a declaration of or a reference to "std::bad_alloc".
15862       isStdBadAlloc = true;
15863 
15864       // If std::bad_alloc has been implicitly declared (but made invisible to
15865       // name lookup), fill in this implicit declaration as the previous
15866       // declaration, so that the declarations get chained appropriately.
15867       if (Previous.empty() && StdBadAlloc)
15868         Previous.addDecl(getStdBadAlloc());
15869     } else if (Name->isStr("align_val_t")) {
15870       isStdAlignValT = true;
15871       if (Previous.empty() && StdAlignValT)
15872         Previous.addDecl(getStdAlignValT());
15873     }
15874   }
15875 
15876   // If we didn't find a previous declaration, and this is a reference
15877   // (or friend reference), move to the correct scope.  In C++, we
15878   // also need to do a redeclaration lookup there, just in case
15879   // there's a shadow friend decl.
15880   if (Name && Previous.empty() &&
15881       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15882     if (Invalid) goto CreateNewDecl;
15883     assert(SS.isEmpty());
15884 
15885     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15886       // C++ [basic.scope.pdecl]p5:
15887       //   -- for an elaborated-type-specifier of the form
15888       //
15889       //          class-key identifier
15890       //
15891       //      if the elaborated-type-specifier is used in the
15892       //      decl-specifier-seq or parameter-declaration-clause of a
15893       //      function defined in namespace scope, the identifier is
15894       //      declared as a class-name in the namespace that contains
15895       //      the declaration; otherwise, except as a friend
15896       //      declaration, the identifier is declared in the smallest
15897       //      non-class, non-function-prototype scope that contains the
15898       //      declaration.
15899       //
15900       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15901       // C structs and unions.
15902       //
15903       // It is an error in C++ to declare (rather than define) an enum
15904       // type, including via an elaborated type specifier.  We'll
15905       // diagnose that later; for now, declare the enum in the same
15906       // scope as we would have picked for any other tag type.
15907       //
15908       // GNU C also supports this behavior as part of its incomplete
15909       // enum types extension, while GNU C++ does not.
15910       //
15911       // Find the context where we'll be declaring the tag.
15912       // FIXME: We would like to maintain the current DeclContext as the
15913       // lexical context,
15914       SearchDC = getTagInjectionContext(SearchDC);
15915 
15916       // Find the scope where we'll be declaring the tag.
15917       S = getTagInjectionScope(S, getLangOpts());
15918     } else {
15919       assert(TUK == TUK_Friend);
15920       // C++ [namespace.memdef]p3:
15921       //   If a friend declaration in a non-local class first declares a
15922       //   class or function, the friend class or function is a member of
15923       //   the innermost enclosing namespace.
15924       SearchDC = SearchDC->getEnclosingNamespaceContext();
15925     }
15926 
15927     // In C++, we need to do a redeclaration lookup to properly
15928     // diagnose some problems.
15929     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15930     // hidden declaration so that we don't get ambiguity errors when using a
15931     // type declared by an elaborated-type-specifier.  In C that is not correct
15932     // and we should instead merge compatible types found by lookup.
15933     if (getLangOpts().CPlusPlus) {
15934       // FIXME: This can perform qualified lookups into function contexts,
15935       // which are meaningless.
15936       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15937       LookupQualifiedName(Previous, SearchDC);
15938     } else {
15939       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15940       LookupName(Previous, S);
15941     }
15942   }
15943 
15944   // If we have a known previous declaration to use, then use it.
15945   if (Previous.empty() && SkipBody && SkipBody->Previous)
15946     Previous.addDecl(SkipBody->Previous);
15947 
15948   if (!Previous.empty()) {
15949     NamedDecl *PrevDecl = Previous.getFoundDecl();
15950     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15951 
15952     // It's okay to have a tag decl in the same scope as a typedef
15953     // which hides a tag decl in the same scope.  Finding this
15954     // insanity with a redeclaration lookup can only actually happen
15955     // in C++.
15956     //
15957     // This is also okay for elaborated-type-specifiers, which is
15958     // technically forbidden by the current standard but which is
15959     // okay according to the likely resolution of an open issue;
15960     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15961     if (getLangOpts().CPlusPlus) {
15962       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15963         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15964           TagDecl *Tag = TT->getDecl();
15965           if (Tag->getDeclName() == Name &&
15966               Tag->getDeclContext()->getRedeclContext()
15967                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15968             PrevDecl = Tag;
15969             Previous.clear();
15970             Previous.addDecl(Tag);
15971             Previous.resolveKind();
15972           }
15973         }
15974       }
15975     }
15976 
15977     // If this is a redeclaration of a using shadow declaration, it must
15978     // declare a tag in the same context. In MSVC mode, we allow a
15979     // redefinition if either context is within the other.
15980     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15981       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15982       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15983           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15984           !(OldTag && isAcceptableTagRedeclContext(
15985                           *this, OldTag->getDeclContext(), SearchDC))) {
15986         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15987         Diag(Shadow->getTargetDecl()->getLocation(),
15988              diag::note_using_decl_target);
15989         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
15990             << 0;
15991         // Recover by ignoring the old declaration.
15992         Previous.clear();
15993         goto CreateNewDecl;
15994       }
15995     }
15996 
15997     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15998       // If this is a use of a previous tag, or if the tag is already declared
15999       // in the same scope (so that the definition/declaration completes or
16000       // rementions the tag), reuse the decl.
16001       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16002           isDeclInScope(DirectPrevDecl, SearchDC, S,
16003                         SS.isNotEmpty() || isMemberSpecialization)) {
16004         // Make sure that this wasn't declared as an enum and now used as a
16005         // struct or something similar.
16006         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16007                                           TUK == TUK_Definition, KWLoc,
16008                                           Name)) {
16009           bool SafeToContinue
16010             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16011                Kind != TTK_Enum);
16012           if (SafeToContinue)
16013             Diag(KWLoc, diag::err_use_with_wrong_tag)
16014               << Name
16015               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16016                                               PrevTagDecl->getKindName());
16017           else
16018             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16019           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16020 
16021           if (SafeToContinue)
16022             Kind = PrevTagDecl->getTagKind();
16023           else {
16024             // Recover by making this an anonymous redefinition.
16025             Name = nullptr;
16026             Previous.clear();
16027             Invalid = true;
16028           }
16029         }
16030 
16031         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16032           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16033           if (TUK == TUK_Reference || TUK == TUK_Friend)
16034             return PrevTagDecl;
16035 
16036           QualType EnumUnderlyingTy;
16037           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16038             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16039           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16040             EnumUnderlyingTy = QualType(T, 0);
16041 
16042           // All conflicts with previous declarations are recovered by
16043           // returning the previous declaration, unless this is a definition,
16044           // in which case we want the caller to bail out.
16045           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16046                                      ScopedEnum, EnumUnderlyingTy,
16047                                      IsFixed, PrevEnum))
16048             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16049         }
16050 
16051         // C++11 [class.mem]p1:
16052         //   A member shall not be declared twice in the member-specification,
16053         //   except that a nested class or member class template can be declared
16054         //   and then later defined.
16055         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16056             S->isDeclScope(PrevDecl)) {
16057           Diag(NameLoc, diag::ext_member_redeclared);
16058           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16059         }
16060 
16061         if (!Invalid) {
16062           // If this is a use, just return the declaration we found, unless
16063           // we have attributes.
16064           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16065             if (!Attrs.empty()) {
16066               // FIXME: Diagnose these attributes. For now, we create a new
16067               // declaration to hold them.
16068             } else if (TUK == TUK_Reference &&
16069                        (PrevTagDecl->getFriendObjectKind() ==
16070                             Decl::FOK_Undeclared ||
16071                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16072                        SS.isEmpty()) {
16073               // This declaration is a reference to an existing entity, but
16074               // has different visibility from that entity: it either makes
16075               // a friend visible or it makes a type visible in a new module.
16076               // In either case, create a new declaration. We only do this if
16077               // the declaration would have meant the same thing if no prior
16078               // declaration were found, that is, if it was found in the same
16079               // scope where we would have injected a declaration.
16080               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16081                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16082                 return PrevTagDecl;
16083               // This is in the injected scope, create a new declaration in
16084               // that scope.
16085               S = getTagInjectionScope(S, getLangOpts());
16086             } else {
16087               return PrevTagDecl;
16088             }
16089           }
16090 
16091           // Diagnose attempts to redefine a tag.
16092           if (TUK == TUK_Definition) {
16093             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16094               // If we're defining a specialization and the previous definition
16095               // is from an implicit instantiation, don't emit an error
16096               // here; we'll catch this in the general case below.
16097               bool IsExplicitSpecializationAfterInstantiation = false;
16098               if (isMemberSpecialization) {
16099                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16100                   IsExplicitSpecializationAfterInstantiation =
16101                     RD->getTemplateSpecializationKind() !=
16102                     TSK_ExplicitSpecialization;
16103                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16104                   IsExplicitSpecializationAfterInstantiation =
16105                     ED->getTemplateSpecializationKind() !=
16106                     TSK_ExplicitSpecialization;
16107               }
16108 
16109               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16110               // not keep more that one definition around (merge them). However,
16111               // ensure the decl passes the structural compatibility check in
16112               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16113               NamedDecl *Hidden = nullptr;
16114               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16115                 // There is a definition of this tag, but it is not visible. We
16116                 // explicitly make use of C++'s one definition rule here, and
16117                 // assume that this definition is identical to the hidden one
16118                 // we already have. Make the existing definition visible and
16119                 // use it in place of this one.
16120                 if (!getLangOpts().CPlusPlus) {
16121                   // Postpone making the old definition visible until after we
16122                   // complete parsing the new one and do the structural
16123                   // comparison.
16124                   SkipBody->CheckSameAsPrevious = true;
16125                   SkipBody->New = createTagFromNewDecl();
16126                   SkipBody->Previous = Def;
16127                   return Def;
16128                 } else {
16129                   SkipBody->ShouldSkip = true;
16130                   SkipBody->Previous = Def;
16131                   makeMergedDefinitionVisible(Hidden);
16132                   // Carry on and handle it like a normal definition. We'll
16133                   // skip starting the definitiion later.
16134                 }
16135               } else if (!IsExplicitSpecializationAfterInstantiation) {
16136                 // A redeclaration in function prototype scope in C isn't
16137                 // visible elsewhere, so merely issue a warning.
16138                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16139                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16140                 else
16141                   Diag(NameLoc, diag::err_redefinition) << Name;
16142                 notePreviousDefinition(Def,
16143                                        NameLoc.isValid() ? NameLoc : KWLoc);
16144                 // If this is a redefinition, recover by making this
16145                 // struct be anonymous, which will make any later
16146                 // references get the previous definition.
16147                 Name = nullptr;
16148                 Previous.clear();
16149                 Invalid = true;
16150               }
16151             } else {
16152               // If the type is currently being defined, complain
16153               // about a nested redefinition.
16154               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16155               if (TD->isBeingDefined()) {
16156                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16157                 Diag(PrevTagDecl->getLocation(),
16158                      diag::note_previous_definition);
16159                 Name = nullptr;
16160                 Previous.clear();
16161                 Invalid = true;
16162               }
16163             }
16164 
16165             // Okay, this is definition of a previously declared or referenced
16166             // tag. We're going to create a new Decl for it.
16167           }
16168 
16169           // Okay, we're going to make a redeclaration.  If this is some kind
16170           // of reference, make sure we build the redeclaration in the same DC
16171           // as the original, and ignore the current access specifier.
16172           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16173             SearchDC = PrevTagDecl->getDeclContext();
16174             AS = AS_none;
16175           }
16176         }
16177         // If we get here we have (another) forward declaration or we
16178         // have a definition.  Just create a new decl.
16179 
16180       } else {
16181         // If we get here, this is a definition of a new tag type in a nested
16182         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16183         // new decl/type.  We set PrevDecl to NULL so that the entities
16184         // have distinct types.
16185         Previous.clear();
16186       }
16187       // If we get here, we're going to create a new Decl. If PrevDecl
16188       // is non-NULL, it's a definition of the tag declared by
16189       // PrevDecl. If it's NULL, we have a new definition.
16190 
16191     // Otherwise, PrevDecl is not a tag, but was found with tag
16192     // lookup.  This is only actually possible in C++, where a few
16193     // things like templates still live in the tag namespace.
16194     } else {
16195       // Use a better diagnostic if an elaborated-type-specifier
16196       // found the wrong kind of type on the first
16197       // (non-redeclaration) lookup.
16198       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16199           !Previous.isForRedeclaration()) {
16200         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16201         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16202                                                        << Kind;
16203         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16204         Invalid = true;
16205 
16206       // Otherwise, only diagnose if the declaration is in scope.
16207       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16208                                 SS.isNotEmpty() || isMemberSpecialization)) {
16209         // do nothing
16210 
16211       // Diagnose implicit declarations introduced by elaborated types.
16212       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16213         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16214         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16215         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16216         Invalid = true;
16217 
16218       // Otherwise it's a declaration.  Call out a particularly common
16219       // case here.
16220       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16221         unsigned Kind = 0;
16222         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16223         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16224           << Name << Kind << TND->getUnderlyingType();
16225         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16226         Invalid = true;
16227 
16228       // Otherwise, diagnose.
16229       } else {
16230         // The tag name clashes with something else in the target scope,
16231         // issue an error and recover by making this tag be anonymous.
16232         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16233         notePreviousDefinition(PrevDecl, NameLoc);
16234         Name = nullptr;
16235         Invalid = true;
16236       }
16237 
16238       // The existing declaration isn't relevant to us; we're in a
16239       // new scope, so clear out the previous declaration.
16240       Previous.clear();
16241     }
16242   }
16243 
16244 CreateNewDecl:
16245 
16246   TagDecl *PrevDecl = nullptr;
16247   if (Previous.isSingleResult())
16248     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16249 
16250   // If there is an identifier, use the location of the identifier as the
16251   // location of the decl, otherwise use the location of the struct/union
16252   // keyword.
16253   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16254 
16255   // Otherwise, create a new declaration. If there is a previous
16256   // declaration of the same entity, the two will be linked via
16257   // PrevDecl.
16258   TagDecl *New;
16259 
16260   if (Kind == TTK_Enum) {
16261     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16262     // enum X { A, B, C } D;    D should chain to X.
16263     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16264                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16265                            ScopedEnumUsesClassTag, IsFixed);
16266 
16267     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16268       StdAlignValT = cast<EnumDecl>(New);
16269 
16270     // If this is an undefined enum, warn.
16271     if (TUK != TUK_Definition && !Invalid) {
16272       TagDecl *Def;
16273       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16274         // C++0x: 7.2p2: opaque-enum-declaration.
16275         // Conflicts are diagnosed above. Do nothing.
16276       }
16277       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16278         Diag(Loc, diag::ext_forward_ref_enum_def)
16279           << New;
16280         Diag(Def->getLocation(), diag::note_previous_definition);
16281       } else {
16282         unsigned DiagID = diag::ext_forward_ref_enum;
16283         if (getLangOpts().MSVCCompat)
16284           DiagID = diag::ext_ms_forward_ref_enum;
16285         else if (getLangOpts().CPlusPlus)
16286           DiagID = diag::err_forward_ref_enum;
16287         Diag(Loc, DiagID);
16288       }
16289     }
16290 
16291     if (EnumUnderlying) {
16292       EnumDecl *ED = cast<EnumDecl>(New);
16293       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16294         ED->setIntegerTypeSourceInfo(TI);
16295       else
16296         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16297       ED->setPromotionType(ED->getIntegerType());
16298       assert(ED->isComplete() && "enum with type should be complete");
16299     }
16300   } else {
16301     // struct/union/class
16302 
16303     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16304     // struct X { int A; } D;    D should chain to X.
16305     if (getLangOpts().CPlusPlus) {
16306       // FIXME: Look for a way to use RecordDecl for simple structs.
16307       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16308                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16309 
16310       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16311         StdBadAlloc = cast<CXXRecordDecl>(New);
16312     } else
16313       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16314                                cast_or_null<RecordDecl>(PrevDecl));
16315   }
16316 
16317   // C++11 [dcl.type]p3:
16318   //   A type-specifier-seq shall not define a class or enumeration [...].
16319   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16320       TUK == TUK_Definition) {
16321     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16322       << Context.getTagDeclType(New);
16323     Invalid = true;
16324   }
16325 
16326   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16327       DC->getDeclKind() == Decl::Enum) {
16328     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16329       << Context.getTagDeclType(New);
16330     Invalid = true;
16331   }
16332 
16333   // Maybe add qualifier info.
16334   if (SS.isNotEmpty()) {
16335     if (SS.isSet()) {
16336       // If this is either a declaration or a definition, check the
16337       // nested-name-specifier against the current context.
16338       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16339           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16340                                        isMemberSpecialization))
16341         Invalid = true;
16342 
16343       New->setQualifierInfo(SS.getWithLocInContext(Context));
16344       if (TemplateParameterLists.size() > 0) {
16345         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16346       }
16347     }
16348     else
16349       Invalid = true;
16350   }
16351 
16352   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16353     // Add alignment attributes if necessary; these attributes are checked when
16354     // the ASTContext lays out the structure.
16355     //
16356     // It is important for implementing the correct semantics that this
16357     // happen here (in ActOnTag). The #pragma pack stack is
16358     // maintained as a result of parser callbacks which can occur at
16359     // many points during the parsing of a struct declaration (because
16360     // the #pragma tokens are effectively skipped over during the
16361     // parsing of the struct).
16362     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16363       AddAlignmentAttributesForRecord(RD);
16364       AddMsStructLayoutForRecord(RD);
16365     }
16366   }
16367 
16368   if (ModulePrivateLoc.isValid()) {
16369     if (isMemberSpecialization)
16370       Diag(New->getLocation(), diag::err_module_private_specialization)
16371         << 2
16372         << FixItHint::CreateRemoval(ModulePrivateLoc);
16373     // __module_private__ does not apply to local classes. However, we only
16374     // diagnose this as an error when the declaration specifiers are
16375     // freestanding. Here, we just ignore the __module_private__.
16376     else if (!SearchDC->isFunctionOrMethod())
16377       New->setModulePrivate();
16378   }
16379 
16380   // If this is a specialization of a member class (of a class template),
16381   // check the specialization.
16382   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16383     Invalid = true;
16384 
16385   // If we're declaring or defining a tag in function prototype scope in C,
16386   // note that this type can only be used within the function and add it to
16387   // the list of decls to inject into the function definition scope.
16388   if ((Name || Kind == TTK_Enum) &&
16389       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16390     if (getLangOpts().CPlusPlus) {
16391       // C++ [dcl.fct]p6:
16392       //   Types shall not be defined in return or parameter types.
16393       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16394         Diag(Loc, diag::err_type_defined_in_param_type)
16395             << Name;
16396         Invalid = true;
16397       }
16398     } else if (!PrevDecl) {
16399       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16400     }
16401   }
16402 
16403   if (Invalid)
16404     New->setInvalidDecl();
16405 
16406   // Set the lexical context. If the tag has a C++ scope specifier, the
16407   // lexical context will be different from the semantic context.
16408   New->setLexicalDeclContext(CurContext);
16409 
16410   // Mark this as a friend decl if applicable.
16411   // In Microsoft mode, a friend declaration also acts as a forward
16412   // declaration so we always pass true to setObjectOfFriendDecl to make
16413   // the tag name visible.
16414   if (TUK == TUK_Friend)
16415     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16416 
16417   // Set the access specifier.
16418   if (!Invalid && SearchDC->isRecord())
16419     SetMemberAccessSpecifier(New, PrevDecl, AS);
16420 
16421   if (PrevDecl)
16422     CheckRedeclarationModuleOwnership(New, PrevDecl);
16423 
16424   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16425     New->startDefinition();
16426 
16427   ProcessDeclAttributeList(S, New, Attrs);
16428   AddPragmaAttributes(S, New);
16429 
16430   // If this has an identifier, add it to the scope stack.
16431   if (TUK == TUK_Friend) {
16432     // We might be replacing an existing declaration in the lookup tables;
16433     // if so, borrow its access specifier.
16434     if (PrevDecl)
16435       New->setAccess(PrevDecl->getAccess());
16436 
16437     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16438     DC->makeDeclVisibleInContext(New);
16439     if (Name) // can be null along some error paths
16440       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16441         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16442   } else if (Name) {
16443     S = getNonFieldDeclScope(S);
16444     PushOnScopeChains(New, S, true);
16445   } else {
16446     CurContext->addDecl(New);
16447   }
16448 
16449   // If this is the C FILE type, notify the AST context.
16450   if (IdentifierInfo *II = New->getIdentifier())
16451     if (!New->isInvalidDecl() &&
16452         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16453         II->isStr("FILE"))
16454       Context.setFILEDecl(New);
16455 
16456   if (PrevDecl)
16457     mergeDeclAttributes(New, PrevDecl);
16458 
16459   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16460     inferGslOwnerPointerAttribute(CXXRD);
16461 
16462   // If there's a #pragma GCC visibility in scope, set the visibility of this
16463   // record.
16464   AddPushedVisibilityAttribute(New);
16465 
16466   if (isMemberSpecialization && !New->isInvalidDecl())
16467     CompleteMemberSpecialization(New, Previous);
16468 
16469   OwnedDecl = true;
16470   // In C++, don't return an invalid declaration. We can't recover well from
16471   // the cases where we make the type anonymous.
16472   if (Invalid && getLangOpts().CPlusPlus) {
16473     if (New->isBeingDefined())
16474       if (auto RD = dyn_cast<RecordDecl>(New))
16475         RD->completeDefinition();
16476     return nullptr;
16477   } else if (SkipBody && SkipBody->ShouldSkip) {
16478     return SkipBody->Previous;
16479   } else {
16480     return New;
16481   }
16482 }
16483 
16484 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16485   AdjustDeclIfTemplate(TagD);
16486   TagDecl *Tag = cast<TagDecl>(TagD);
16487 
16488   // Enter the tag context.
16489   PushDeclContext(S, Tag);
16490 
16491   ActOnDocumentableDecl(TagD);
16492 
16493   // If there's a #pragma GCC visibility in scope, set the visibility of this
16494   // record.
16495   AddPushedVisibilityAttribute(Tag);
16496 }
16497 
16498 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16499                                     SkipBodyInfo &SkipBody) {
16500   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16501     return false;
16502 
16503   // Make the previous decl visible.
16504   makeMergedDefinitionVisible(SkipBody.Previous);
16505   return true;
16506 }
16507 
16508 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16509   assert(isa<ObjCContainerDecl>(IDecl) &&
16510          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16511   DeclContext *OCD = cast<DeclContext>(IDecl);
16512   assert(OCD->getLexicalParent() == CurContext &&
16513       "The next DeclContext should be lexically contained in the current one.");
16514   CurContext = OCD;
16515   return IDecl;
16516 }
16517 
16518 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16519                                            SourceLocation FinalLoc,
16520                                            bool IsFinalSpelledSealed,
16521                                            bool IsAbstract,
16522                                            SourceLocation LBraceLoc) {
16523   AdjustDeclIfTemplate(TagD);
16524   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16525 
16526   FieldCollector->StartClass();
16527 
16528   if (!Record->getIdentifier())
16529     return;
16530 
16531   if (IsAbstract)
16532     Record->markAbstract();
16533 
16534   if (FinalLoc.isValid()) {
16535     Record->addAttr(FinalAttr::Create(
16536         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16537         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16538   }
16539   // C++ [class]p2:
16540   //   [...] The class-name is also inserted into the scope of the
16541   //   class itself; this is known as the injected-class-name. For
16542   //   purposes of access checking, the injected-class-name is treated
16543   //   as if it were a public member name.
16544   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16545       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16546       Record->getLocation(), Record->getIdentifier(),
16547       /*PrevDecl=*/nullptr,
16548       /*DelayTypeCreation=*/true);
16549   Context.getTypeDeclType(InjectedClassName, Record);
16550   InjectedClassName->setImplicit();
16551   InjectedClassName->setAccess(AS_public);
16552   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16553       InjectedClassName->setDescribedClassTemplate(Template);
16554   PushOnScopeChains(InjectedClassName, S);
16555   assert(InjectedClassName->isInjectedClassName() &&
16556          "Broken injected-class-name");
16557 }
16558 
16559 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16560                                     SourceRange BraceRange) {
16561   AdjustDeclIfTemplate(TagD);
16562   TagDecl *Tag = cast<TagDecl>(TagD);
16563   Tag->setBraceRange(BraceRange);
16564 
16565   // Make sure we "complete" the definition even it is invalid.
16566   if (Tag->isBeingDefined()) {
16567     assert(Tag->isInvalidDecl() && "We should already have completed it");
16568     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16569       RD->completeDefinition();
16570   }
16571 
16572   if (isa<CXXRecordDecl>(Tag)) {
16573     FieldCollector->FinishClass();
16574   }
16575 
16576   // Exit this scope of this tag's definition.
16577   PopDeclContext();
16578 
16579   if (getCurLexicalContext()->isObjCContainer() &&
16580       Tag->getDeclContext()->isFileContext())
16581     Tag->setTopLevelDeclInObjCContainer();
16582 
16583   // Notify the consumer that we've defined a tag.
16584   if (!Tag->isInvalidDecl())
16585     Consumer.HandleTagDeclDefinition(Tag);
16586 }
16587 
16588 void Sema::ActOnObjCContainerFinishDefinition() {
16589   // Exit this scope of this interface definition.
16590   PopDeclContext();
16591 }
16592 
16593 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16594   assert(DC == CurContext && "Mismatch of container contexts");
16595   OriginalLexicalContext = DC;
16596   ActOnObjCContainerFinishDefinition();
16597 }
16598 
16599 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16600   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16601   OriginalLexicalContext = nullptr;
16602 }
16603 
16604 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16605   AdjustDeclIfTemplate(TagD);
16606   TagDecl *Tag = cast<TagDecl>(TagD);
16607   Tag->setInvalidDecl();
16608 
16609   // Make sure we "complete" the definition even it is invalid.
16610   if (Tag->isBeingDefined()) {
16611     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16612       RD->completeDefinition();
16613   }
16614 
16615   // We're undoing ActOnTagStartDefinition here, not
16616   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16617   // the FieldCollector.
16618 
16619   PopDeclContext();
16620 }
16621 
16622 // Note that FieldName may be null for anonymous bitfields.
16623 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16624                                 IdentifierInfo *FieldName,
16625                                 QualType FieldTy, bool IsMsStruct,
16626                                 Expr *BitWidth, bool *ZeroWidth) {
16627   assert(BitWidth);
16628   if (BitWidth->containsErrors())
16629     return ExprError();
16630 
16631   // Default to true; that shouldn't confuse checks for emptiness
16632   if (ZeroWidth)
16633     *ZeroWidth = true;
16634 
16635   // C99 6.7.2.1p4 - verify the field type.
16636   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16637   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16638     // Handle incomplete and sizeless types with a specific error.
16639     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16640                                  diag::err_field_incomplete_or_sizeless))
16641       return ExprError();
16642     if (FieldName)
16643       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16644         << FieldName << FieldTy << BitWidth->getSourceRange();
16645     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16646       << FieldTy << BitWidth->getSourceRange();
16647   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16648                                              UPPC_BitFieldWidth))
16649     return ExprError();
16650 
16651   // If the bit-width is type- or value-dependent, don't try to check
16652   // it now.
16653   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16654     return BitWidth;
16655 
16656   llvm::APSInt Value;
16657   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16658   if (ICE.isInvalid())
16659     return ICE;
16660   BitWidth = ICE.get();
16661 
16662   if (Value != 0 && ZeroWidth)
16663     *ZeroWidth = false;
16664 
16665   // Zero-width bitfield is ok for anonymous field.
16666   if (Value == 0 && FieldName)
16667     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16668 
16669   if (Value.isSigned() && Value.isNegative()) {
16670     if (FieldName)
16671       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16672                << FieldName << toString(Value, 10);
16673     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16674       << toString(Value, 10);
16675   }
16676 
16677   // The size of the bit-field must not exceed our maximum permitted object
16678   // size.
16679   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16680     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16681            << !FieldName << FieldName << toString(Value, 10);
16682   }
16683 
16684   if (!FieldTy->isDependentType()) {
16685     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16686     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16687     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16688 
16689     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16690     // ABI.
16691     bool CStdConstraintViolation =
16692         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16693     bool MSBitfieldViolation =
16694         Value.ugt(TypeStorageSize) &&
16695         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16696     if (CStdConstraintViolation || MSBitfieldViolation) {
16697       unsigned DiagWidth =
16698           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16699       if (FieldName)
16700         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16701                << FieldName << toString(Value, 10)
16702                << !CStdConstraintViolation << DiagWidth;
16703 
16704       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16705              << toString(Value, 10) << !CStdConstraintViolation
16706              << DiagWidth;
16707     }
16708 
16709     // Warn on types where the user might conceivably expect to get all
16710     // specified bits as value bits: that's all integral types other than
16711     // 'bool'.
16712     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16713       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16714           << FieldName << toString(Value, 10)
16715           << (unsigned)TypeWidth;
16716     }
16717   }
16718 
16719   return BitWidth;
16720 }
16721 
16722 /// ActOnField - Each field of a C struct/union is passed into this in order
16723 /// to create a FieldDecl object for it.
16724 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16725                        Declarator &D, Expr *BitfieldWidth) {
16726   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16727                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16728                                /*InitStyle=*/ICIS_NoInit, AS_public);
16729   return Res;
16730 }
16731 
16732 /// HandleField - Analyze a field of a C struct or a C++ data member.
16733 ///
16734 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16735                              SourceLocation DeclStart,
16736                              Declarator &D, Expr *BitWidth,
16737                              InClassInitStyle InitStyle,
16738                              AccessSpecifier AS) {
16739   if (D.isDecompositionDeclarator()) {
16740     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16741     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16742       << Decomp.getSourceRange();
16743     return nullptr;
16744   }
16745 
16746   IdentifierInfo *II = D.getIdentifier();
16747   SourceLocation Loc = DeclStart;
16748   if (II) Loc = D.getIdentifierLoc();
16749 
16750   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16751   QualType T = TInfo->getType();
16752   if (getLangOpts().CPlusPlus) {
16753     CheckExtraCXXDefaultArguments(D);
16754 
16755     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16756                                         UPPC_DataMemberType)) {
16757       D.setInvalidType();
16758       T = Context.IntTy;
16759       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16760     }
16761   }
16762 
16763   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16764 
16765   if (D.getDeclSpec().isInlineSpecified())
16766     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16767         << getLangOpts().CPlusPlus17;
16768   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16769     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16770          diag::err_invalid_thread)
16771       << DeclSpec::getSpecifierName(TSCS);
16772 
16773   // Check to see if this name was declared as a member previously
16774   NamedDecl *PrevDecl = nullptr;
16775   LookupResult Previous(*this, II, Loc, LookupMemberName,
16776                         ForVisibleRedeclaration);
16777   LookupName(Previous, S);
16778   switch (Previous.getResultKind()) {
16779     case LookupResult::Found:
16780     case LookupResult::FoundUnresolvedValue:
16781       PrevDecl = Previous.getAsSingle<NamedDecl>();
16782       break;
16783 
16784     case LookupResult::FoundOverloaded:
16785       PrevDecl = Previous.getRepresentativeDecl();
16786       break;
16787 
16788     case LookupResult::NotFound:
16789     case LookupResult::NotFoundInCurrentInstantiation:
16790     case LookupResult::Ambiguous:
16791       break;
16792   }
16793   Previous.suppressDiagnostics();
16794 
16795   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16796     // Maybe we will complain about the shadowed template parameter.
16797     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16798     // Just pretend that we didn't see the previous declaration.
16799     PrevDecl = nullptr;
16800   }
16801 
16802   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16803     PrevDecl = nullptr;
16804 
16805   bool Mutable
16806     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16807   SourceLocation TSSL = D.getBeginLoc();
16808   FieldDecl *NewFD
16809     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16810                      TSSL, AS, PrevDecl, &D);
16811 
16812   if (NewFD->isInvalidDecl())
16813     Record->setInvalidDecl();
16814 
16815   if (D.getDeclSpec().isModulePrivateSpecified())
16816     NewFD->setModulePrivate();
16817 
16818   if (NewFD->isInvalidDecl() && PrevDecl) {
16819     // Don't introduce NewFD into scope; there's already something
16820     // with the same name in the same scope.
16821   } else if (II) {
16822     PushOnScopeChains(NewFD, S);
16823   } else
16824     Record->addDecl(NewFD);
16825 
16826   return NewFD;
16827 }
16828 
16829 /// Build a new FieldDecl and check its well-formedness.
16830 ///
16831 /// This routine builds a new FieldDecl given the fields name, type,
16832 /// record, etc. \p PrevDecl should refer to any previous declaration
16833 /// with the same name and in the same scope as the field to be
16834 /// created.
16835 ///
16836 /// \returns a new FieldDecl.
16837 ///
16838 /// \todo The Declarator argument is a hack. It will be removed once
16839 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16840                                 TypeSourceInfo *TInfo,
16841                                 RecordDecl *Record, SourceLocation Loc,
16842                                 bool Mutable, Expr *BitWidth,
16843                                 InClassInitStyle InitStyle,
16844                                 SourceLocation TSSL,
16845                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16846                                 Declarator *D) {
16847   IdentifierInfo *II = Name.getAsIdentifierInfo();
16848   bool InvalidDecl = false;
16849   if (D) InvalidDecl = D->isInvalidType();
16850 
16851   // If we receive a broken type, recover by assuming 'int' and
16852   // marking this declaration as invalid.
16853   if (T.isNull() || T->containsErrors()) {
16854     InvalidDecl = true;
16855     T = Context.IntTy;
16856   }
16857 
16858   QualType EltTy = Context.getBaseElementType(T);
16859   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16860     if (RequireCompleteSizedType(Loc, EltTy,
16861                                  diag::err_field_incomplete_or_sizeless)) {
16862       // Fields of incomplete type force their record to be invalid.
16863       Record->setInvalidDecl();
16864       InvalidDecl = true;
16865     } else {
16866       NamedDecl *Def;
16867       EltTy->isIncompleteType(&Def);
16868       if (Def && Def->isInvalidDecl()) {
16869         Record->setInvalidDecl();
16870         InvalidDecl = true;
16871       }
16872     }
16873   }
16874 
16875   // TR 18037 does not allow fields to be declared with address space
16876   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16877       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16878     Diag(Loc, diag::err_field_with_address_space);
16879     Record->setInvalidDecl();
16880     InvalidDecl = true;
16881   }
16882 
16883   if (LangOpts.OpenCL) {
16884     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16885     // used as structure or union field: image, sampler, event or block types.
16886     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16887         T->isBlockPointerType()) {
16888       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16889       Record->setInvalidDecl();
16890       InvalidDecl = true;
16891     }
16892     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16893     // is enabled.
16894     if (BitWidth && !getOpenCLOptions().isAvailableOption(
16895                         "__cl_clang_bitfields", LangOpts)) {
16896       Diag(Loc, diag::err_opencl_bitfields);
16897       InvalidDecl = true;
16898     }
16899   }
16900 
16901   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16902   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16903       T.hasQualifiers()) {
16904     InvalidDecl = true;
16905     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16906   }
16907 
16908   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16909   // than a variably modified type.
16910   if (!InvalidDecl && T->isVariablyModifiedType()) {
16911     if (!tryToFixVariablyModifiedVarType(
16912             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16913       InvalidDecl = true;
16914   }
16915 
16916   // Fields can not have abstract class types
16917   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16918                                              diag::err_abstract_type_in_decl,
16919                                              AbstractFieldType))
16920     InvalidDecl = true;
16921 
16922   bool ZeroWidth = false;
16923   if (InvalidDecl)
16924     BitWidth = nullptr;
16925   // If this is declared as a bit-field, check the bit-field.
16926   if (BitWidth) {
16927     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16928                               &ZeroWidth).get();
16929     if (!BitWidth) {
16930       InvalidDecl = true;
16931       BitWidth = nullptr;
16932       ZeroWidth = false;
16933     }
16934   }
16935 
16936   // Check that 'mutable' is consistent with the type of the declaration.
16937   if (!InvalidDecl && Mutable) {
16938     unsigned DiagID = 0;
16939     if (T->isReferenceType())
16940       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16941                                         : diag::err_mutable_reference;
16942     else if (T.isConstQualified())
16943       DiagID = diag::err_mutable_const;
16944 
16945     if (DiagID) {
16946       SourceLocation ErrLoc = Loc;
16947       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16948         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16949       Diag(ErrLoc, DiagID);
16950       if (DiagID != diag::ext_mutable_reference) {
16951         Mutable = false;
16952         InvalidDecl = true;
16953       }
16954     }
16955   }
16956 
16957   // C++11 [class.union]p8 (DR1460):
16958   //   At most one variant member of a union may have a
16959   //   brace-or-equal-initializer.
16960   if (InitStyle != ICIS_NoInit)
16961     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16962 
16963   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16964                                        BitWidth, Mutable, InitStyle);
16965   if (InvalidDecl)
16966     NewFD->setInvalidDecl();
16967 
16968   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16969     Diag(Loc, diag::err_duplicate_member) << II;
16970     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16971     NewFD->setInvalidDecl();
16972   }
16973 
16974   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16975     if (Record->isUnion()) {
16976       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16977         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16978         if (RDecl->getDefinition()) {
16979           // C++ [class.union]p1: An object of a class with a non-trivial
16980           // constructor, a non-trivial copy constructor, a non-trivial
16981           // destructor, or a non-trivial copy assignment operator
16982           // cannot be a member of a union, nor can an array of such
16983           // objects.
16984           if (CheckNontrivialField(NewFD))
16985             NewFD->setInvalidDecl();
16986         }
16987       }
16988 
16989       // C++ [class.union]p1: If a union contains a member of reference type,
16990       // the program is ill-formed, except when compiling with MSVC extensions
16991       // enabled.
16992       if (EltTy->isReferenceType()) {
16993         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16994                                     diag::ext_union_member_of_reference_type :
16995                                     diag::err_union_member_of_reference_type)
16996           << NewFD->getDeclName() << EltTy;
16997         if (!getLangOpts().MicrosoftExt)
16998           NewFD->setInvalidDecl();
16999       }
17000     }
17001   }
17002 
17003   // FIXME: We need to pass in the attributes given an AST
17004   // representation, not a parser representation.
17005   if (D) {
17006     // FIXME: The current scope is almost... but not entirely... correct here.
17007     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17008 
17009     if (NewFD->hasAttrs())
17010       CheckAlignasUnderalignment(NewFD);
17011   }
17012 
17013   // In auto-retain/release, infer strong retension for fields of
17014   // retainable type.
17015   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17016     NewFD->setInvalidDecl();
17017 
17018   if (T.isObjCGCWeak())
17019     Diag(Loc, diag::warn_attribute_weak_on_field);
17020 
17021   // PPC MMA non-pointer types are not allowed as field types.
17022   if (Context.getTargetInfo().getTriple().isPPC64() &&
17023       CheckPPCMMAType(T, NewFD->getLocation()))
17024     NewFD->setInvalidDecl();
17025 
17026   NewFD->setAccess(AS);
17027   return NewFD;
17028 }
17029 
17030 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17031   assert(FD);
17032   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17033 
17034   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17035     return false;
17036 
17037   QualType EltTy = Context.getBaseElementType(FD->getType());
17038   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17039     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17040     if (RDecl->getDefinition()) {
17041       // We check for copy constructors before constructors
17042       // because otherwise we'll never get complaints about
17043       // copy constructors.
17044 
17045       CXXSpecialMember member = CXXInvalid;
17046       // We're required to check for any non-trivial constructors. Since the
17047       // implicit default constructor is suppressed if there are any
17048       // user-declared constructors, we just need to check that there is a
17049       // trivial default constructor and a trivial copy constructor. (We don't
17050       // worry about move constructors here, since this is a C++98 check.)
17051       if (RDecl->hasNonTrivialCopyConstructor())
17052         member = CXXCopyConstructor;
17053       else if (!RDecl->hasTrivialDefaultConstructor())
17054         member = CXXDefaultConstructor;
17055       else if (RDecl->hasNonTrivialCopyAssignment())
17056         member = CXXCopyAssignment;
17057       else if (RDecl->hasNonTrivialDestructor())
17058         member = CXXDestructor;
17059 
17060       if (member != CXXInvalid) {
17061         if (!getLangOpts().CPlusPlus11 &&
17062             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17063           // Objective-C++ ARC: it is an error to have a non-trivial field of
17064           // a union. However, system headers in Objective-C programs
17065           // occasionally have Objective-C lifetime objects within unions,
17066           // and rather than cause the program to fail, we make those
17067           // members unavailable.
17068           SourceLocation Loc = FD->getLocation();
17069           if (getSourceManager().isInSystemHeader(Loc)) {
17070             if (!FD->hasAttr<UnavailableAttr>())
17071               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17072                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17073             return false;
17074           }
17075         }
17076 
17077         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17078                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17079                diag::err_illegal_union_or_anon_struct_member)
17080           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17081         DiagnoseNontrivial(RDecl, member);
17082         return !getLangOpts().CPlusPlus11;
17083       }
17084     }
17085   }
17086 
17087   return false;
17088 }
17089 
17090 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17091 ///  AST enum value.
17092 static ObjCIvarDecl::AccessControl
17093 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17094   switch (ivarVisibility) {
17095   default: llvm_unreachable("Unknown visitibility kind");
17096   case tok::objc_private: return ObjCIvarDecl::Private;
17097   case tok::objc_public: return ObjCIvarDecl::Public;
17098   case tok::objc_protected: return ObjCIvarDecl::Protected;
17099   case tok::objc_package: return ObjCIvarDecl::Package;
17100   }
17101 }
17102 
17103 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17104 /// in order to create an IvarDecl object for it.
17105 Decl *Sema::ActOnIvar(Scope *S,
17106                                 SourceLocation DeclStart,
17107                                 Declarator &D, Expr *BitfieldWidth,
17108                                 tok::ObjCKeywordKind Visibility) {
17109 
17110   IdentifierInfo *II = D.getIdentifier();
17111   Expr *BitWidth = (Expr*)BitfieldWidth;
17112   SourceLocation Loc = DeclStart;
17113   if (II) Loc = D.getIdentifierLoc();
17114 
17115   // FIXME: Unnamed fields can be handled in various different ways, for
17116   // example, unnamed unions inject all members into the struct namespace!
17117 
17118   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17119   QualType T = TInfo->getType();
17120 
17121   if (BitWidth) {
17122     // 6.7.2.1p3, 6.7.2.1p4
17123     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17124     if (!BitWidth)
17125       D.setInvalidType();
17126   } else {
17127     // Not a bitfield.
17128 
17129     // validate II.
17130 
17131   }
17132   if (T->isReferenceType()) {
17133     Diag(Loc, diag::err_ivar_reference_type);
17134     D.setInvalidType();
17135   }
17136   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17137   // than a variably modified type.
17138   else if (T->isVariablyModifiedType()) {
17139     if (!tryToFixVariablyModifiedVarType(
17140             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17141       D.setInvalidType();
17142   }
17143 
17144   // Get the visibility (access control) for this ivar.
17145   ObjCIvarDecl::AccessControl ac =
17146     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17147                                         : ObjCIvarDecl::None;
17148   // Must set ivar's DeclContext to its enclosing interface.
17149   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17150   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17151     return nullptr;
17152   ObjCContainerDecl *EnclosingContext;
17153   if (ObjCImplementationDecl *IMPDecl =
17154       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17155     if (LangOpts.ObjCRuntime.isFragile()) {
17156     // Case of ivar declared in an implementation. Context is that of its class.
17157       EnclosingContext = IMPDecl->getClassInterface();
17158       assert(EnclosingContext && "Implementation has no class interface!");
17159     }
17160     else
17161       EnclosingContext = EnclosingDecl;
17162   } else {
17163     if (ObjCCategoryDecl *CDecl =
17164         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17165       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17166         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17167         return nullptr;
17168       }
17169     }
17170     EnclosingContext = EnclosingDecl;
17171   }
17172 
17173   // Construct the decl.
17174   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17175                                              DeclStart, Loc, II, T,
17176                                              TInfo, ac, (Expr *)BitfieldWidth);
17177 
17178   if (II) {
17179     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17180                                            ForVisibleRedeclaration);
17181     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17182         && !isa<TagDecl>(PrevDecl)) {
17183       Diag(Loc, diag::err_duplicate_member) << II;
17184       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17185       NewID->setInvalidDecl();
17186     }
17187   }
17188 
17189   // Process attributes attached to the ivar.
17190   ProcessDeclAttributes(S, NewID, D);
17191 
17192   if (D.isInvalidType())
17193     NewID->setInvalidDecl();
17194 
17195   // In ARC, infer 'retaining' for ivars of retainable type.
17196   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17197     NewID->setInvalidDecl();
17198 
17199   if (D.getDeclSpec().isModulePrivateSpecified())
17200     NewID->setModulePrivate();
17201 
17202   if (II) {
17203     // FIXME: When interfaces are DeclContexts, we'll need to add
17204     // these to the interface.
17205     S->AddDecl(NewID);
17206     IdResolver.AddDecl(NewID);
17207   }
17208 
17209   if (LangOpts.ObjCRuntime.isNonFragile() &&
17210       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17211     Diag(Loc, diag::warn_ivars_in_interface);
17212 
17213   return NewID;
17214 }
17215 
17216 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17217 /// class and class extensions. For every class \@interface and class
17218 /// extension \@interface, if the last ivar is a bitfield of any type,
17219 /// then add an implicit `char :0` ivar to the end of that interface.
17220 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17221                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17222   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17223     return;
17224 
17225   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17226   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17227 
17228   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17229     return;
17230   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17231   if (!ID) {
17232     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17233       if (!CD->IsClassExtension())
17234         return;
17235     }
17236     // No need to add this to end of @implementation.
17237     else
17238       return;
17239   }
17240   // All conditions are met. Add a new bitfield to the tail end of ivars.
17241   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17242   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17243 
17244   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17245                               DeclLoc, DeclLoc, nullptr,
17246                               Context.CharTy,
17247                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17248                                                                DeclLoc),
17249                               ObjCIvarDecl::Private, BW,
17250                               true);
17251   AllIvarDecls.push_back(Ivar);
17252 }
17253 
17254 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17255                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17256                        SourceLocation RBrac,
17257                        const ParsedAttributesView &Attrs) {
17258   assert(EnclosingDecl && "missing record or interface decl");
17259 
17260   // If this is an Objective-C @implementation or category and we have
17261   // new fields here we should reset the layout of the interface since
17262   // it will now change.
17263   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17264     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17265     switch (DC->getKind()) {
17266     default: break;
17267     case Decl::ObjCCategory:
17268       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17269       break;
17270     case Decl::ObjCImplementation:
17271       Context.
17272         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17273       break;
17274     }
17275   }
17276 
17277   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17278   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17279 
17280   // Start counting up the number of named members; make sure to include
17281   // members of anonymous structs and unions in the total.
17282   unsigned NumNamedMembers = 0;
17283   if (Record) {
17284     for (const auto *I : Record->decls()) {
17285       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17286         if (IFD->getDeclName())
17287           ++NumNamedMembers;
17288     }
17289   }
17290 
17291   // Verify that all the fields are okay.
17292   SmallVector<FieldDecl*, 32> RecFields;
17293 
17294   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17295        i != end; ++i) {
17296     FieldDecl *FD = cast<FieldDecl>(*i);
17297 
17298     // Get the type for the field.
17299     const Type *FDTy = FD->getType().getTypePtr();
17300 
17301     if (!FD->isAnonymousStructOrUnion()) {
17302       // Remember all fields written by the user.
17303       RecFields.push_back(FD);
17304     }
17305 
17306     // If the field is already invalid for some reason, don't emit more
17307     // diagnostics about it.
17308     if (FD->isInvalidDecl()) {
17309       EnclosingDecl->setInvalidDecl();
17310       continue;
17311     }
17312 
17313     // C99 6.7.2.1p2:
17314     //   A structure or union shall not contain a member with
17315     //   incomplete or function type (hence, a structure shall not
17316     //   contain an instance of itself, but may contain a pointer to
17317     //   an instance of itself), except that the last member of a
17318     //   structure with more than one named member may have incomplete
17319     //   array type; such a structure (and any union containing,
17320     //   possibly recursively, a member that is such a structure)
17321     //   shall not be a member of a structure or an element of an
17322     //   array.
17323     bool IsLastField = (i + 1 == Fields.end());
17324     if (FDTy->isFunctionType()) {
17325       // Field declared as a function.
17326       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17327         << FD->getDeclName();
17328       FD->setInvalidDecl();
17329       EnclosingDecl->setInvalidDecl();
17330       continue;
17331     } else if (FDTy->isIncompleteArrayType() &&
17332                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17333       if (Record) {
17334         // Flexible array member.
17335         // Microsoft and g++ is more permissive regarding flexible array.
17336         // It will accept flexible array in union and also
17337         // as the sole element of a struct/class.
17338         unsigned DiagID = 0;
17339         if (!Record->isUnion() && !IsLastField) {
17340           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17341             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17342           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17343           FD->setInvalidDecl();
17344           EnclosingDecl->setInvalidDecl();
17345           continue;
17346         } else if (Record->isUnion())
17347           DiagID = getLangOpts().MicrosoftExt
17348                        ? diag::ext_flexible_array_union_ms
17349                        : getLangOpts().CPlusPlus
17350                              ? diag::ext_flexible_array_union_gnu
17351                              : diag::err_flexible_array_union;
17352         else if (NumNamedMembers < 1)
17353           DiagID = getLangOpts().MicrosoftExt
17354                        ? diag::ext_flexible_array_empty_aggregate_ms
17355                        : getLangOpts().CPlusPlus
17356                              ? diag::ext_flexible_array_empty_aggregate_gnu
17357                              : diag::err_flexible_array_empty_aggregate;
17358 
17359         if (DiagID)
17360           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17361                                           << Record->getTagKind();
17362         // While the layout of types that contain virtual bases is not specified
17363         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17364         // virtual bases after the derived members.  This would make a flexible
17365         // array member declared at the end of an object not adjacent to the end
17366         // of the type.
17367         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17368           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17369               << FD->getDeclName() << Record->getTagKind();
17370         if (!getLangOpts().C99)
17371           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17372             << FD->getDeclName() << Record->getTagKind();
17373 
17374         // If the element type has a non-trivial destructor, we would not
17375         // implicitly destroy the elements, so disallow it for now.
17376         //
17377         // FIXME: GCC allows this. We should probably either implicitly delete
17378         // the destructor of the containing class, or just allow this.
17379         QualType BaseElem = Context.getBaseElementType(FD->getType());
17380         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17381           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17382             << FD->getDeclName() << FD->getType();
17383           FD->setInvalidDecl();
17384           EnclosingDecl->setInvalidDecl();
17385           continue;
17386         }
17387         // Okay, we have a legal flexible array member at the end of the struct.
17388         Record->setHasFlexibleArrayMember(true);
17389       } else {
17390         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17391         // unless they are followed by another ivar. That check is done
17392         // elsewhere, after synthesized ivars are known.
17393       }
17394     } else if (!FDTy->isDependentType() &&
17395                RequireCompleteSizedType(
17396                    FD->getLocation(), FD->getType(),
17397                    diag::err_field_incomplete_or_sizeless)) {
17398       // Incomplete type
17399       FD->setInvalidDecl();
17400       EnclosingDecl->setInvalidDecl();
17401       continue;
17402     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17403       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17404         // A type which contains a flexible array member is considered to be a
17405         // flexible array member.
17406         Record->setHasFlexibleArrayMember(true);
17407         if (!Record->isUnion()) {
17408           // If this is a struct/class and this is not the last element, reject
17409           // it.  Note that GCC supports variable sized arrays in the middle of
17410           // structures.
17411           if (!IsLastField)
17412             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17413               << FD->getDeclName() << FD->getType();
17414           else {
17415             // We support flexible arrays at the end of structs in
17416             // other structs as an extension.
17417             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17418               << FD->getDeclName();
17419           }
17420         }
17421       }
17422       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17423           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17424                                  diag::err_abstract_type_in_decl,
17425                                  AbstractIvarType)) {
17426         // Ivars can not have abstract class types
17427         FD->setInvalidDecl();
17428       }
17429       if (Record && FDTTy->getDecl()->hasObjectMember())
17430         Record->setHasObjectMember(true);
17431       if (Record && FDTTy->getDecl()->hasVolatileMember())
17432         Record->setHasVolatileMember(true);
17433     } else if (FDTy->isObjCObjectType()) {
17434       /// A field cannot be an Objective-c object
17435       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17436         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17437       QualType T = Context.getObjCObjectPointerType(FD->getType());
17438       FD->setType(T);
17439     } else if (Record && Record->isUnion() &&
17440                FD->getType().hasNonTrivialObjCLifetime() &&
17441                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17442                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17443                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17444                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17445       // For backward compatibility, fields of C unions declared in system
17446       // headers that have non-trivial ObjC ownership qualifications are marked
17447       // as unavailable unless the qualifier is explicit and __strong. This can
17448       // break ABI compatibility between programs compiled with ARC and MRR, but
17449       // is a better option than rejecting programs using those unions under
17450       // ARC.
17451       FD->addAttr(UnavailableAttr::CreateImplicit(
17452           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17453           FD->getLocation()));
17454     } else if (getLangOpts().ObjC &&
17455                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17456                !Record->hasObjectMember()) {
17457       if (FD->getType()->isObjCObjectPointerType() ||
17458           FD->getType().isObjCGCStrong())
17459         Record->setHasObjectMember(true);
17460       else if (Context.getAsArrayType(FD->getType())) {
17461         QualType BaseType = Context.getBaseElementType(FD->getType());
17462         if (BaseType->isRecordType() &&
17463             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17464           Record->setHasObjectMember(true);
17465         else if (BaseType->isObjCObjectPointerType() ||
17466                  BaseType.isObjCGCStrong())
17467                Record->setHasObjectMember(true);
17468       }
17469     }
17470 
17471     if (Record && !getLangOpts().CPlusPlus &&
17472         !shouldIgnoreForRecordTriviality(FD)) {
17473       QualType FT = FD->getType();
17474       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17475         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17476         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17477             Record->isUnion())
17478           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17479       }
17480       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17481       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17482         Record->setNonTrivialToPrimitiveCopy(true);
17483         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17484           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17485       }
17486       if (FT.isDestructedType()) {
17487         Record->setNonTrivialToPrimitiveDestroy(true);
17488         Record->setParamDestroyedInCallee(true);
17489         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17490           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17491       }
17492 
17493       if (const auto *RT = FT->getAs<RecordType>()) {
17494         if (RT->getDecl()->getArgPassingRestrictions() ==
17495             RecordDecl::APK_CanNeverPassInRegs)
17496           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17497       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17498         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17499     }
17500 
17501     if (Record && FD->getType().isVolatileQualified())
17502       Record->setHasVolatileMember(true);
17503     // Keep track of the number of named members.
17504     if (FD->getIdentifier())
17505       ++NumNamedMembers;
17506   }
17507 
17508   // Okay, we successfully defined 'Record'.
17509   if (Record) {
17510     bool Completed = false;
17511     if (CXXRecord) {
17512       if (!CXXRecord->isInvalidDecl()) {
17513         // Set access bits correctly on the directly-declared conversions.
17514         for (CXXRecordDecl::conversion_iterator
17515                I = CXXRecord->conversion_begin(),
17516                E = CXXRecord->conversion_end(); I != E; ++I)
17517           I.setAccess((*I)->getAccess());
17518       }
17519 
17520       // Add any implicitly-declared members to this class.
17521       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17522 
17523       if (!CXXRecord->isDependentType()) {
17524         if (!CXXRecord->isInvalidDecl()) {
17525           // If we have virtual base classes, we may end up finding multiple
17526           // final overriders for a given virtual function. Check for this
17527           // problem now.
17528           if (CXXRecord->getNumVBases()) {
17529             CXXFinalOverriderMap FinalOverriders;
17530             CXXRecord->getFinalOverriders(FinalOverriders);
17531 
17532             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17533                                              MEnd = FinalOverriders.end();
17534                  M != MEnd; ++M) {
17535               for (OverridingMethods::iterator SO = M->second.begin(),
17536                                             SOEnd = M->second.end();
17537                    SO != SOEnd; ++SO) {
17538                 assert(SO->second.size() > 0 &&
17539                        "Virtual function without overriding functions?");
17540                 if (SO->second.size() == 1)
17541                   continue;
17542 
17543                 // C++ [class.virtual]p2:
17544                 //   In a derived class, if a virtual member function of a base
17545                 //   class subobject has more than one final overrider the
17546                 //   program is ill-formed.
17547                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17548                   << (const NamedDecl *)M->first << Record;
17549                 Diag(M->first->getLocation(),
17550                      diag::note_overridden_virtual_function);
17551                 for (OverridingMethods::overriding_iterator
17552                           OM = SO->second.begin(),
17553                        OMEnd = SO->second.end();
17554                      OM != OMEnd; ++OM)
17555                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17556                     << (const NamedDecl *)M->first << OM->Method->getParent();
17557 
17558                 Record->setInvalidDecl();
17559               }
17560             }
17561             CXXRecord->completeDefinition(&FinalOverriders);
17562             Completed = true;
17563           }
17564         }
17565       }
17566     }
17567 
17568     if (!Completed)
17569       Record->completeDefinition();
17570 
17571     // Handle attributes before checking the layout.
17572     ProcessDeclAttributeList(S, Record, Attrs);
17573 
17574     // We may have deferred checking for a deleted destructor. Check now.
17575     if (CXXRecord) {
17576       auto *Dtor = CXXRecord->getDestructor();
17577       if (Dtor && Dtor->isImplicit() &&
17578           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17579         CXXRecord->setImplicitDestructorIsDeleted();
17580         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17581       }
17582     }
17583 
17584     if (Record->hasAttrs()) {
17585       CheckAlignasUnderalignment(Record);
17586 
17587       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17588         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17589                                            IA->getRange(), IA->getBestCase(),
17590                                            IA->getInheritanceModel());
17591     }
17592 
17593     // Check if the structure/union declaration is a type that can have zero
17594     // size in C. For C this is a language extension, for C++ it may cause
17595     // compatibility problems.
17596     bool CheckForZeroSize;
17597     if (!getLangOpts().CPlusPlus) {
17598       CheckForZeroSize = true;
17599     } else {
17600       // For C++ filter out types that cannot be referenced in C code.
17601       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17602       CheckForZeroSize =
17603           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17604           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17605           CXXRecord->isCLike();
17606     }
17607     if (CheckForZeroSize) {
17608       bool ZeroSize = true;
17609       bool IsEmpty = true;
17610       unsigned NonBitFields = 0;
17611       for (RecordDecl::field_iterator I = Record->field_begin(),
17612                                       E = Record->field_end();
17613            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17614         IsEmpty = false;
17615         if (I->isUnnamedBitfield()) {
17616           if (!I->isZeroLengthBitField(Context))
17617             ZeroSize = false;
17618         } else {
17619           ++NonBitFields;
17620           QualType FieldType = I->getType();
17621           if (FieldType->isIncompleteType() ||
17622               !Context.getTypeSizeInChars(FieldType).isZero())
17623             ZeroSize = false;
17624         }
17625       }
17626 
17627       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17628       // allowed in C++, but warn if its declaration is inside
17629       // extern "C" block.
17630       if (ZeroSize) {
17631         Diag(RecLoc, getLangOpts().CPlusPlus ?
17632                          diag::warn_zero_size_struct_union_in_extern_c :
17633                          diag::warn_zero_size_struct_union_compat)
17634           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17635       }
17636 
17637       // Structs without named members are extension in C (C99 6.7.2.1p7),
17638       // but are accepted by GCC.
17639       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17640         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17641                                diag::ext_no_named_members_in_struct_union)
17642           << Record->isUnion();
17643       }
17644     }
17645   } else {
17646     ObjCIvarDecl **ClsFields =
17647       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17648     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17649       ID->setEndOfDefinitionLoc(RBrac);
17650       // Add ivar's to class's DeclContext.
17651       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17652         ClsFields[i]->setLexicalDeclContext(ID);
17653         ID->addDecl(ClsFields[i]);
17654       }
17655       // Must enforce the rule that ivars in the base classes may not be
17656       // duplicates.
17657       if (ID->getSuperClass())
17658         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17659     } else if (ObjCImplementationDecl *IMPDecl =
17660                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17661       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17662       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17663         // Ivar declared in @implementation never belongs to the implementation.
17664         // Only it is in implementation's lexical context.
17665         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17666       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17667       IMPDecl->setIvarLBraceLoc(LBrac);
17668       IMPDecl->setIvarRBraceLoc(RBrac);
17669     } else if (ObjCCategoryDecl *CDecl =
17670                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17671       // case of ivars in class extension; all other cases have been
17672       // reported as errors elsewhere.
17673       // FIXME. Class extension does not have a LocEnd field.
17674       // CDecl->setLocEnd(RBrac);
17675       // Add ivar's to class extension's DeclContext.
17676       // Diagnose redeclaration of private ivars.
17677       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17678       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17679         if (IDecl) {
17680           if (const ObjCIvarDecl *ClsIvar =
17681               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17682             Diag(ClsFields[i]->getLocation(),
17683                  diag::err_duplicate_ivar_declaration);
17684             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17685             continue;
17686           }
17687           for (const auto *Ext : IDecl->known_extensions()) {
17688             if (const ObjCIvarDecl *ClsExtIvar
17689                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17690               Diag(ClsFields[i]->getLocation(),
17691                    diag::err_duplicate_ivar_declaration);
17692               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17693               continue;
17694             }
17695           }
17696         }
17697         ClsFields[i]->setLexicalDeclContext(CDecl);
17698         CDecl->addDecl(ClsFields[i]);
17699       }
17700       CDecl->setIvarLBraceLoc(LBrac);
17701       CDecl->setIvarRBraceLoc(RBrac);
17702     }
17703   }
17704 }
17705 
17706 /// Determine whether the given integral value is representable within
17707 /// the given type T.
17708 static bool isRepresentableIntegerValue(ASTContext &Context,
17709                                         llvm::APSInt &Value,
17710                                         QualType T) {
17711   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17712          "Integral type required!");
17713   unsigned BitWidth = Context.getIntWidth(T);
17714 
17715   if (Value.isUnsigned() || Value.isNonNegative()) {
17716     if (T->isSignedIntegerOrEnumerationType())
17717       --BitWidth;
17718     return Value.getActiveBits() <= BitWidth;
17719   }
17720   return Value.getMinSignedBits() <= BitWidth;
17721 }
17722 
17723 // Given an integral type, return the next larger integral type
17724 // (or a NULL type of no such type exists).
17725 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17726   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17727   // enum checking below.
17728   assert((T->isIntegralType(Context) ||
17729          T->isEnumeralType()) && "Integral type required!");
17730   const unsigned NumTypes = 4;
17731   QualType SignedIntegralTypes[NumTypes] = {
17732     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17733   };
17734   QualType UnsignedIntegralTypes[NumTypes] = {
17735     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17736     Context.UnsignedLongLongTy
17737   };
17738 
17739   unsigned BitWidth = Context.getTypeSize(T);
17740   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17741                                                         : UnsignedIntegralTypes;
17742   for (unsigned I = 0; I != NumTypes; ++I)
17743     if (Context.getTypeSize(Types[I]) > BitWidth)
17744       return Types[I];
17745 
17746   return QualType();
17747 }
17748 
17749 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17750                                           EnumConstantDecl *LastEnumConst,
17751                                           SourceLocation IdLoc,
17752                                           IdentifierInfo *Id,
17753                                           Expr *Val) {
17754   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17755   llvm::APSInt EnumVal(IntWidth);
17756   QualType EltTy;
17757 
17758   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17759     Val = nullptr;
17760 
17761   if (Val)
17762     Val = DefaultLvalueConversion(Val).get();
17763 
17764   if (Val) {
17765     if (Enum->isDependentType() || Val->isTypeDependent())
17766       EltTy = Context.DependentTy;
17767     else {
17768       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17769       // underlying type, but do allow it in all other contexts.
17770       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17771         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17772         // constant-expression in the enumerator-definition shall be a converted
17773         // constant expression of the underlying type.
17774         EltTy = Enum->getIntegerType();
17775         ExprResult Converted =
17776           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17777                                            CCEK_Enumerator);
17778         if (Converted.isInvalid())
17779           Val = nullptr;
17780         else
17781           Val = Converted.get();
17782       } else if (!Val->isValueDependent() &&
17783                  !(Val =
17784                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17785                            .get())) {
17786         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17787       } else {
17788         if (Enum->isComplete()) {
17789           EltTy = Enum->getIntegerType();
17790 
17791           // In Obj-C and Microsoft mode, require the enumeration value to be
17792           // representable in the underlying type of the enumeration. In C++11,
17793           // we perform a non-narrowing conversion as part of converted constant
17794           // expression checking.
17795           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17796             if (Context.getTargetInfo()
17797                     .getTriple()
17798                     .isWindowsMSVCEnvironment()) {
17799               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17800             } else {
17801               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17802             }
17803           }
17804 
17805           // Cast to the underlying type.
17806           Val = ImpCastExprToType(Val, EltTy,
17807                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17808                                                          : CK_IntegralCast)
17809                     .get();
17810         } else if (getLangOpts().CPlusPlus) {
17811           // C++11 [dcl.enum]p5:
17812           //   If the underlying type is not fixed, the type of each enumerator
17813           //   is the type of its initializing value:
17814           //     - If an initializer is specified for an enumerator, the
17815           //       initializing value has the same type as the expression.
17816           EltTy = Val->getType();
17817         } else {
17818           // C99 6.7.2.2p2:
17819           //   The expression that defines the value of an enumeration constant
17820           //   shall be an integer constant expression that has a value
17821           //   representable as an int.
17822 
17823           // Complain if the value is not representable in an int.
17824           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17825             Diag(IdLoc, diag::ext_enum_value_not_int)
17826               << toString(EnumVal, 10) << Val->getSourceRange()
17827               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17828           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17829             // Force the type of the expression to 'int'.
17830             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17831           }
17832           EltTy = Val->getType();
17833         }
17834       }
17835     }
17836   }
17837 
17838   if (!Val) {
17839     if (Enum->isDependentType())
17840       EltTy = Context.DependentTy;
17841     else if (!LastEnumConst) {
17842       // C++0x [dcl.enum]p5:
17843       //   If the underlying type is not fixed, the type of each enumerator
17844       //   is the type of its initializing value:
17845       //     - If no initializer is specified for the first enumerator, the
17846       //       initializing value has an unspecified integral type.
17847       //
17848       // GCC uses 'int' for its unspecified integral type, as does
17849       // C99 6.7.2.2p3.
17850       if (Enum->isFixed()) {
17851         EltTy = Enum->getIntegerType();
17852       }
17853       else {
17854         EltTy = Context.IntTy;
17855       }
17856     } else {
17857       // Assign the last value + 1.
17858       EnumVal = LastEnumConst->getInitVal();
17859       ++EnumVal;
17860       EltTy = LastEnumConst->getType();
17861 
17862       // Check for overflow on increment.
17863       if (EnumVal < LastEnumConst->getInitVal()) {
17864         // C++0x [dcl.enum]p5:
17865         //   If the underlying type is not fixed, the type of each enumerator
17866         //   is the type of its initializing value:
17867         //
17868         //     - Otherwise the type of the initializing value is the same as
17869         //       the type of the initializing value of the preceding enumerator
17870         //       unless the incremented value is not representable in that type,
17871         //       in which case the type is an unspecified integral type
17872         //       sufficient to contain the incremented value. If no such type
17873         //       exists, the program is ill-formed.
17874         QualType T = getNextLargerIntegralType(Context, EltTy);
17875         if (T.isNull() || Enum->isFixed()) {
17876           // There is no integral type larger enough to represent this
17877           // value. Complain, then allow the value to wrap around.
17878           EnumVal = LastEnumConst->getInitVal();
17879           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17880           ++EnumVal;
17881           if (Enum->isFixed())
17882             // When the underlying type is fixed, this is ill-formed.
17883             Diag(IdLoc, diag::err_enumerator_wrapped)
17884               << toString(EnumVal, 10)
17885               << EltTy;
17886           else
17887             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17888               << toString(EnumVal, 10);
17889         } else {
17890           EltTy = T;
17891         }
17892 
17893         // Retrieve the last enumerator's value, extent that type to the
17894         // type that is supposed to be large enough to represent the incremented
17895         // value, then increment.
17896         EnumVal = LastEnumConst->getInitVal();
17897         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17898         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17899         ++EnumVal;
17900 
17901         // If we're not in C++, diagnose the overflow of enumerator values,
17902         // which in C99 means that the enumerator value is not representable in
17903         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17904         // permits enumerator values that are representable in some larger
17905         // integral type.
17906         if (!getLangOpts().CPlusPlus && !T.isNull())
17907           Diag(IdLoc, diag::warn_enum_value_overflow);
17908       } else if (!getLangOpts().CPlusPlus &&
17909                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17910         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17911         Diag(IdLoc, diag::ext_enum_value_not_int)
17912           << toString(EnumVal, 10) << 1;
17913       }
17914     }
17915   }
17916 
17917   if (!EltTy->isDependentType()) {
17918     // Make the enumerator value match the signedness and size of the
17919     // enumerator's type.
17920     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17921     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17922   }
17923 
17924   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17925                                   Val, EnumVal);
17926 }
17927 
17928 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17929                                                 SourceLocation IILoc) {
17930   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17931       !getLangOpts().CPlusPlus)
17932     return SkipBodyInfo();
17933 
17934   // We have an anonymous enum definition. Look up the first enumerator to
17935   // determine if we should merge the definition with an existing one and
17936   // skip the body.
17937   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17938                                          forRedeclarationInCurContext());
17939   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17940   if (!PrevECD)
17941     return SkipBodyInfo();
17942 
17943   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17944   NamedDecl *Hidden;
17945   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17946     SkipBodyInfo Skip;
17947     Skip.Previous = Hidden;
17948     return Skip;
17949   }
17950 
17951   return SkipBodyInfo();
17952 }
17953 
17954 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17955                               SourceLocation IdLoc, IdentifierInfo *Id,
17956                               const ParsedAttributesView &Attrs,
17957                               SourceLocation EqualLoc, Expr *Val) {
17958   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17959   EnumConstantDecl *LastEnumConst =
17960     cast_or_null<EnumConstantDecl>(lastEnumConst);
17961 
17962   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17963   // we find one that is.
17964   S = getNonFieldDeclScope(S);
17965 
17966   // Verify that there isn't already something declared with this name in this
17967   // scope.
17968   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17969   LookupName(R, S);
17970   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17971 
17972   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17973     // Maybe we will complain about the shadowed template parameter.
17974     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17975     // Just pretend that we didn't see the previous declaration.
17976     PrevDecl = nullptr;
17977   }
17978 
17979   // C++ [class.mem]p15:
17980   // If T is the name of a class, then each of the following shall have a name
17981   // different from T:
17982   // - every enumerator of every member of class T that is an unscoped
17983   // enumerated type
17984   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17985     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17986                             DeclarationNameInfo(Id, IdLoc));
17987 
17988   EnumConstantDecl *New =
17989     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17990   if (!New)
17991     return nullptr;
17992 
17993   if (PrevDecl) {
17994     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17995       // Check for other kinds of shadowing not already handled.
17996       CheckShadow(New, PrevDecl, R);
17997     }
17998 
17999     // When in C++, we may get a TagDecl with the same name; in this case the
18000     // enum constant will 'hide' the tag.
18001     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18002            "Received TagDecl when not in C++!");
18003     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18004       if (isa<EnumConstantDecl>(PrevDecl))
18005         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18006       else
18007         Diag(IdLoc, diag::err_redefinition) << Id;
18008       notePreviousDefinition(PrevDecl, IdLoc);
18009       return nullptr;
18010     }
18011   }
18012 
18013   // Process attributes.
18014   ProcessDeclAttributeList(S, New, Attrs);
18015   AddPragmaAttributes(S, New);
18016 
18017   // Register this decl in the current scope stack.
18018   New->setAccess(TheEnumDecl->getAccess());
18019   PushOnScopeChains(New, S);
18020 
18021   ActOnDocumentableDecl(New);
18022 
18023   return New;
18024 }
18025 
18026 // Returns true when the enum initial expression does not trigger the
18027 // duplicate enum warning.  A few common cases are exempted as follows:
18028 // Element2 = Element1
18029 // Element2 = Element1 + 1
18030 // Element2 = Element1 - 1
18031 // Where Element2 and Element1 are from the same enum.
18032 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18033   Expr *InitExpr = ECD->getInitExpr();
18034   if (!InitExpr)
18035     return true;
18036   InitExpr = InitExpr->IgnoreImpCasts();
18037 
18038   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18039     if (!BO->isAdditiveOp())
18040       return true;
18041     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18042     if (!IL)
18043       return true;
18044     if (IL->getValue() != 1)
18045       return true;
18046 
18047     InitExpr = BO->getLHS();
18048   }
18049 
18050   // This checks if the elements are from the same enum.
18051   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18052   if (!DRE)
18053     return true;
18054 
18055   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18056   if (!EnumConstant)
18057     return true;
18058 
18059   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18060       Enum)
18061     return true;
18062 
18063   return false;
18064 }
18065 
18066 // Emits a warning when an element is implicitly set a value that
18067 // a previous element has already been set to.
18068 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18069                                         EnumDecl *Enum, QualType EnumType) {
18070   // Avoid anonymous enums
18071   if (!Enum->getIdentifier())
18072     return;
18073 
18074   // Only check for small enums.
18075   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18076     return;
18077 
18078   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18079     return;
18080 
18081   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18082   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18083 
18084   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18085 
18086   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18087   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18088 
18089   // Use int64_t as a key to avoid needing special handling for map keys.
18090   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18091     llvm::APSInt Val = D->getInitVal();
18092     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18093   };
18094 
18095   DuplicatesVector DupVector;
18096   ValueToVectorMap EnumMap;
18097 
18098   // Populate the EnumMap with all values represented by enum constants without
18099   // an initializer.
18100   for (auto *Element : Elements) {
18101     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18102 
18103     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18104     // this constant.  Skip this enum since it may be ill-formed.
18105     if (!ECD) {
18106       return;
18107     }
18108 
18109     // Constants with initalizers are handled in the next loop.
18110     if (ECD->getInitExpr())
18111       continue;
18112 
18113     // Duplicate values are handled in the next loop.
18114     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18115   }
18116 
18117   if (EnumMap.size() == 0)
18118     return;
18119 
18120   // Create vectors for any values that has duplicates.
18121   for (auto *Element : Elements) {
18122     // The last loop returned if any constant was null.
18123     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18124     if (!ValidDuplicateEnum(ECD, Enum))
18125       continue;
18126 
18127     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18128     if (Iter == EnumMap.end())
18129       continue;
18130 
18131     DeclOrVector& Entry = Iter->second;
18132     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18133       // Ensure constants are different.
18134       if (D == ECD)
18135         continue;
18136 
18137       // Create new vector and push values onto it.
18138       auto Vec = std::make_unique<ECDVector>();
18139       Vec->push_back(D);
18140       Vec->push_back(ECD);
18141 
18142       // Update entry to point to the duplicates vector.
18143       Entry = Vec.get();
18144 
18145       // Store the vector somewhere we can consult later for quick emission of
18146       // diagnostics.
18147       DupVector.emplace_back(std::move(Vec));
18148       continue;
18149     }
18150 
18151     ECDVector *Vec = Entry.get<ECDVector*>();
18152     // Make sure constants are not added more than once.
18153     if (*Vec->begin() == ECD)
18154       continue;
18155 
18156     Vec->push_back(ECD);
18157   }
18158 
18159   // Emit diagnostics.
18160   for (const auto &Vec : DupVector) {
18161     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18162 
18163     // Emit warning for one enum constant.
18164     auto *FirstECD = Vec->front();
18165     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18166       << FirstECD << toString(FirstECD->getInitVal(), 10)
18167       << FirstECD->getSourceRange();
18168 
18169     // Emit one note for each of the remaining enum constants with
18170     // the same value.
18171     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18172       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18173         << ECD << toString(ECD->getInitVal(), 10)
18174         << ECD->getSourceRange();
18175   }
18176 }
18177 
18178 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18179                              bool AllowMask) const {
18180   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18181   assert(ED->isCompleteDefinition() && "expected enum definition");
18182 
18183   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18184   llvm::APInt &FlagBits = R.first->second;
18185 
18186   if (R.second) {
18187     for (auto *E : ED->enumerators()) {
18188       const auto &EVal = E->getInitVal();
18189       // Only single-bit enumerators introduce new flag values.
18190       if (EVal.isPowerOf2())
18191         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18192     }
18193   }
18194 
18195   // A value is in a flag enum if either its bits are a subset of the enum's
18196   // flag bits (the first condition) or we are allowing masks and the same is
18197   // true of its complement (the second condition). When masks are allowed, we
18198   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18199   //
18200   // While it's true that any value could be used as a mask, the assumption is
18201   // that a mask will have all of the insignificant bits set. Anything else is
18202   // likely a logic error.
18203   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18204   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18205 }
18206 
18207 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18208                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18209                          const ParsedAttributesView &Attrs) {
18210   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18211   QualType EnumType = Context.getTypeDeclType(Enum);
18212 
18213   ProcessDeclAttributeList(S, Enum, Attrs);
18214 
18215   if (Enum->isDependentType()) {
18216     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18217       EnumConstantDecl *ECD =
18218         cast_or_null<EnumConstantDecl>(Elements[i]);
18219       if (!ECD) continue;
18220 
18221       ECD->setType(EnumType);
18222     }
18223 
18224     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18225     return;
18226   }
18227 
18228   // TODO: If the result value doesn't fit in an int, it must be a long or long
18229   // long value.  ISO C does not support this, but GCC does as an extension,
18230   // emit a warning.
18231   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18232   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18233   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18234 
18235   // Verify that all the values are okay, compute the size of the values, and
18236   // reverse the list.
18237   unsigned NumNegativeBits = 0;
18238   unsigned NumPositiveBits = 0;
18239 
18240   // Keep track of whether all elements have type int.
18241   bool AllElementsInt = true;
18242 
18243   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18244     EnumConstantDecl *ECD =
18245       cast_or_null<EnumConstantDecl>(Elements[i]);
18246     if (!ECD) continue;  // Already issued a diagnostic.
18247 
18248     const llvm::APSInt &InitVal = ECD->getInitVal();
18249 
18250     // Keep track of the size of positive and negative values.
18251     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18252       NumPositiveBits = std::max(NumPositiveBits,
18253                                  (unsigned)InitVal.getActiveBits());
18254     else
18255       NumNegativeBits = std::max(NumNegativeBits,
18256                                  (unsigned)InitVal.getMinSignedBits());
18257 
18258     // Keep track of whether every enum element has type int (very common).
18259     if (AllElementsInt)
18260       AllElementsInt = ECD->getType() == Context.IntTy;
18261   }
18262 
18263   // Figure out the type that should be used for this enum.
18264   QualType BestType;
18265   unsigned BestWidth;
18266 
18267   // C++0x N3000 [conv.prom]p3:
18268   //   An rvalue of an unscoped enumeration type whose underlying
18269   //   type is not fixed can be converted to an rvalue of the first
18270   //   of the following types that can represent all the values of
18271   //   the enumeration: int, unsigned int, long int, unsigned long
18272   //   int, long long int, or unsigned long long int.
18273   // C99 6.4.4.3p2:
18274   //   An identifier declared as an enumeration constant has type int.
18275   // The C99 rule is modified by a gcc extension
18276   QualType BestPromotionType;
18277 
18278   bool Packed = Enum->hasAttr<PackedAttr>();
18279   // -fshort-enums is the equivalent to specifying the packed attribute on all
18280   // enum definitions.
18281   if (LangOpts.ShortEnums)
18282     Packed = true;
18283 
18284   // If the enum already has a type because it is fixed or dictated by the
18285   // target, promote that type instead of analyzing the enumerators.
18286   if (Enum->isComplete()) {
18287     BestType = Enum->getIntegerType();
18288     if (BestType->isPromotableIntegerType())
18289       BestPromotionType = Context.getPromotedIntegerType(BestType);
18290     else
18291       BestPromotionType = BestType;
18292 
18293     BestWidth = Context.getIntWidth(BestType);
18294   }
18295   else if (NumNegativeBits) {
18296     // If there is a negative value, figure out the smallest integer type (of
18297     // int/long/longlong) that fits.
18298     // If it's packed, check also if it fits a char or a short.
18299     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18300       BestType = Context.SignedCharTy;
18301       BestWidth = CharWidth;
18302     } else if (Packed && NumNegativeBits <= ShortWidth &&
18303                NumPositiveBits < ShortWidth) {
18304       BestType = Context.ShortTy;
18305       BestWidth = ShortWidth;
18306     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18307       BestType = Context.IntTy;
18308       BestWidth = IntWidth;
18309     } else {
18310       BestWidth = Context.getTargetInfo().getLongWidth();
18311 
18312       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18313         BestType = Context.LongTy;
18314       } else {
18315         BestWidth = Context.getTargetInfo().getLongLongWidth();
18316 
18317         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18318           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18319         BestType = Context.LongLongTy;
18320       }
18321     }
18322     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18323   } else {
18324     // If there is no negative value, figure out the smallest type that fits
18325     // all of the enumerator values.
18326     // If it's packed, check also if it fits a char or a short.
18327     if (Packed && NumPositiveBits <= CharWidth) {
18328       BestType = Context.UnsignedCharTy;
18329       BestPromotionType = Context.IntTy;
18330       BestWidth = CharWidth;
18331     } else if (Packed && NumPositiveBits <= ShortWidth) {
18332       BestType = Context.UnsignedShortTy;
18333       BestPromotionType = Context.IntTy;
18334       BestWidth = ShortWidth;
18335     } else if (NumPositiveBits <= IntWidth) {
18336       BestType = Context.UnsignedIntTy;
18337       BestWidth = IntWidth;
18338       BestPromotionType
18339         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18340                            ? Context.UnsignedIntTy : Context.IntTy;
18341     } else if (NumPositiveBits <=
18342                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18343       BestType = Context.UnsignedLongTy;
18344       BestPromotionType
18345         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18346                            ? Context.UnsignedLongTy : Context.LongTy;
18347     } else {
18348       BestWidth = Context.getTargetInfo().getLongLongWidth();
18349       assert(NumPositiveBits <= BestWidth &&
18350              "How could an initializer get larger than ULL?");
18351       BestType = Context.UnsignedLongLongTy;
18352       BestPromotionType
18353         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18354                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18355     }
18356   }
18357 
18358   // Loop over all of the enumerator constants, changing their types to match
18359   // the type of the enum if needed.
18360   for (auto *D : Elements) {
18361     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18362     if (!ECD) continue;  // Already issued a diagnostic.
18363 
18364     // Standard C says the enumerators have int type, but we allow, as an
18365     // extension, the enumerators to be larger than int size.  If each
18366     // enumerator value fits in an int, type it as an int, otherwise type it the
18367     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18368     // that X has type 'int', not 'unsigned'.
18369 
18370     // Determine whether the value fits into an int.
18371     llvm::APSInt InitVal = ECD->getInitVal();
18372 
18373     // If it fits into an integer type, force it.  Otherwise force it to match
18374     // the enum decl type.
18375     QualType NewTy;
18376     unsigned NewWidth;
18377     bool NewSign;
18378     if (!getLangOpts().CPlusPlus &&
18379         !Enum->isFixed() &&
18380         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18381       NewTy = Context.IntTy;
18382       NewWidth = IntWidth;
18383       NewSign = true;
18384     } else if (ECD->getType() == BestType) {
18385       // Already the right type!
18386       if (getLangOpts().CPlusPlus)
18387         // C++ [dcl.enum]p4: Following the closing brace of an
18388         // enum-specifier, each enumerator has the type of its
18389         // enumeration.
18390         ECD->setType(EnumType);
18391       continue;
18392     } else {
18393       NewTy = BestType;
18394       NewWidth = BestWidth;
18395       NewSign = BestType->isSignedIntegerOrEnumerationType();
18396     }
18397 
18398     // Adjust the APSInt value.
18399     InitVal = InitVal.extOrTrunc(NewWidth);
18400     InitVal.setIsSigned(NewSign);
18401     ECD->setInitVal(InitVal);
18402 
18403     // Adjust the Expr initializer and type.
18404     if (ECD->getInitExpr() &&
18405         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18406       ECD->setInitExpr(ImplicitCastExpr::Create(
18407           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18408           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18409     if (getLangOpts().CPlusPlus)
18410       // C++ [dcl.enum]p4: Following the closing brace of an
18411       // enum-specifier, each enumerator has the type of its
18412       // enumeration.
18413       ECD->setType(EnumType);
18414     else
18415       ECD->setType(NewTy);
18416   }
18417 
18418   Enum->completeDefinition(BestType, BestPromotionType,
18419                            NumPositiveBits, NumNegativeBits);
18420 
18421   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18422 
18423   if (Enum->isClosedFlag()) {
18424     for (Decl *D : Elements) {
18425       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18426       if (!ECD) continue;  // Already issued a diagnostic.
18427 
18428       llvm::APSInt InitVal = ECD->getInitVal();
18429       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18430           !IsValueInFlagEnum(Enum, InitVal, true))
18431         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18432           << ECD << Enum;
18433     }
18434   }
18435 
18436   // Now that the enum type is defined, ensure it's not been underaligned.
18437   if (Enum->hasAttrs())
18438     CheckAlignasUnderalignment(Enum);
18439 }
18440 
18441 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18442                                   SourceLocation StartLoc,
18443                                   SourceLocation EndLoc) {
18444   StringLiteral *AsmString = cast<StringLiteral>(expr);
18445 
18446   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18447                                                    AsmString, StartLoc,
18448                                                    EndLoc);
18449   CurContext->addDecl(New);
18450   return New;
18451 }
18452 
18453 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18454                                       IdentifierInfo* AliasName,
18455                                       SourceLocation PragmaLoc,
18456                                       SourceLocation NameLoc,
18457                                       SourceLocation AliasNameLoc) {
18458   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18459                                          LookupOrdinaryName);
18460   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18461                            AttributeCommonInfo::AS_Pragma);
18462   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18463       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18464 
18465   // If a declaration that:
18466   // 1) declares a function or a variable
18467   // 2) has external linkage
18468   // already exists, add a label attribute to it.
18469   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18470     if (isDeclExternC(PrevDecl))
18471       PrevDecl->addAttr(Attr);
18472     else
18473       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18474           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18475   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18476   } else
18477     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18478 }
18479 
18480 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18481                              SourceLocation PragmaLoc,
18482                              SourceLocation NameLoc) {
18483   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18484 
18485   if (PrevDecl) {
18486     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18487   } else {
18488     (void)WeakUndeclaredIdentifiers.insert(
18489       std::pair<IdentifierInfo*,WeakInfo>
18490         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18491   }
18492 }
18493 
18494 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18495                                 IdentifierInfo* AliasName,
18496                                 SourceLocation PragmaLoc,
18497                                 SourceLocation NameLoc,
18498                                 SourceLocation AliasNameLoc) {
18499   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18500                                     LookupOrdinaryName);
18501   WeakInfo W = WeakInfo(Name, NameLoc);
18502 
18503   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18504     if (!PrevDecl->hasAttr<AliasAttr>())
18505       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18506         DeclApplyPragmaWeak(TUScope, ND, W);
18507   } else {
18508     (void)WeakUndeclaredIdentifiers.insert(
18509       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18510   }
18511 }
18512 
18513 Decl *Sema::getObjCDeclContext() const {
18514   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18515 }
18516 
18517 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18518                                                      bool Final) {
18519   assert(FD && "Expected non-null FunctionDecl");
18520 
18521   // SYCL functions can be template, so we check if they have appropriate
18522   // attribute prior to checking if it is a template.
18523   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18524     return FunctionEmissionStatus::Emitted;
18525 
18526   // Templates are emitted when they're instantiated.
18527   if (FD->isDependentContext())
18528     return FunctionEmissionStatus::TemplateDiscarded;
18529 
18530   // Check whether this function is an externally visible definition.
18531   auto IsEmittedForExternalSymbol = [this, FD]() {
18532     // We have to check the GVA linkage of the function's *definition* -- if we
18533     // only have a declaration, we don't know whether or not the function will
18534     // be emitted, because (say) the definition could include "inline".
18535     FunctionDecl *Def = FD->getDefinition();
18536 
18537     return Def && !isDiscardableGVALinkage(
18538                       getASTContext().GetGVALinkageForFunction(Def));
18539   };
18540 
18541   if (LangOpts.OpenMPIsDevice) {
18542     // In OpenMP device mode we will not emit host only functions, or functions
18543     // we don't need due to their linkage.
18544     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18545         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18546     // DevTy may be changed later by
18547     //  #pragma omp declare target to(*) device_type(*).
18548     // Therefore DevTy having no value does not imply host. The emission status
18549     // will be checked again at the end of compilation unit with Final = true.
18550     if (DevTy.hasValue())
18551       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18552         return FunctionEmissionStatus::OMPDiscarded;
18553     // If we have an explicit value for the device type, or we are in a target
18554     // declare context, we need to emit all extern and used symbols.
18555     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18556       if (IsEmittedForExternalSymbol())
18557         return FunctionEmissionStatus::Emitted;
18558     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18559     // we'll omit it.
18560     if (Final)
18561       return FunctionEmissionStatus::OMPDiscarded;
18562   } else if (LangOpts.OpenMP > 45) {
18563     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18564     // function. In 5.0, no_host was introduced which might cause a function to
18565     // be ommitted.
18566     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18567         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18568     if (DevTy.hasValue())
18569       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18570         return FunctionEmissionStatus::OMPDiscarded;
18571   }
18572 
18573   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18574     return FunctionEmissionStatus::Emitted;
18575 
18576   if (LangOpts.CUDA) {
18577     // When compiling for device, host functions are never emitted.  Similarly,
18578     // when compiling for host, device and global functions are never emitted.
18579     // (Technically, we do emit a host-side stub for global functions, but this
18580     // doesn't count for our purposes here.)
18581     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18582     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18583       return FunctionEmissionStatus::CUDADiscarded;
18584     if (!LangOpts.CUDAIsDevice &&
18585         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18586       return FunctionEmissionStatus::CUDADiscarded;
18587 
18588     if (IsEmittedForExternalSymbol())
18589       return FunctionEmissionStatus::Emitted;
18590   }
18591 
18592   // Otherwise, the function is known-emitted if it's in our set of
18593   // known-emitted functions.
18594   return FunctionEmissionStatus::Unknown;
18595 }
18596 
18597 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18598   // Host-side references to a __global__ function refer to the stub, so the
18599   // function itself is never emitted and therefore should not be marked.
18600   // If we have host fn calls kernel fn calls host+device, the HD function
18601   // does not get instantiated on the host. We model this by omitting at the
18602   // call to the kernel from the callgraph. This ensures that, when compiling
18603   // for host, only HD functions actually called from the host get marked as
18604   // known-emitted.
18605   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18606          IdentifyCUDATarget(Callee) == CFT_Global;
18607 }
18608