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_via_dependent_bases_lookup) << &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       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439         if (!IIDecl ||
440             (*Res)->getLocation().getRawEncoding() <
441               IIDecl->getLocation().getRawEncoding())
442           IIDecl = *Res;
443       }
444     }
445 
446     if (!IIDecl) {
447       // None of the entities we found is a type, so there is no way
448       // to even assume that the result is a type. In this case, don't
449       // complain about the ambiguity. The parser will either try to
450       // perform this lookup again (e.g., as an object name), which
451       // will produce the ambiguity, or will complain that it expected
452       // a type name.
453       Result.suppressDiagnostics();
454       return nullptr;
455     }
456 
457     // We found a type within the ambiguous lookup; diagnose the
458     // ambiguity and then return that type. This might be the right
459     // answer, or it might not be, but it suppresses any attempt to
460     // perform the name lookup again.
461     break;
462 
463   case LookupResult::Found:
464     IIDecl = Result.getFoundDecl();
465     break;
466   }
467 
468   assert(IIDecl && "Didn't find decl");
469 
470   QualType T;
471   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472     // C++ [class.qual]p2: A lookup that would find the injected-class-name
473     // instead names the constructors of the class, except when naming a class.
474     // This is ill-formed when we're not actually forming a ctor or dtor name.
475     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478         FoundRD->isInjectedClassName() &&
479         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481           << &II << /*Type*/1;
482 
483     DiagnoseUseOfDecl(IIDecl, NameLoc);
484 
485     T = Context.getTypeDeclType(TD);
486     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489     if (!HasTrailingDot)
490       T = Context.getObjCInterfaceType(IDecl);
491   } else if (AllowDeducedTemplate) {
492     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494                                                        QualType(), false);
495   }
496 
497   if (T.isNull()) {
498     // If it's not plausibly a type, suppress diagnostics.
499     Result.suppressDiagnostics();
500     return nullptr;
501   }
502 
503   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504   // constructor or destructor name (in such a case, the scope specifier
505   // will be attached to the enclosing Expr or Decl node).
506   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507       !isa<ObjCInterfaceDecl>(IIDecl)) {
508     if (WantNontrivialTypeSourceInfo) {
509       // Construct a type with type-source information.
510       TypeLocBuilder Builder;
511       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512 
513       T = getElaboratedType(ETK_None, *SS, T);
514       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515       ElabTL.setElaboratedKeywordLoc(SourceLocation());
516       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518     } else {
519       T = getElaboratedType(ETK_None, *SS, T);
520     }
521   }
522 
523   return ParsedType::make(T);
524 }
525 
526 // Builds a fake NNS for the given decl context.
527 static NestedNameSpecifier *
528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529   for (;; DC = DC->getLookupParent()) {
530     DC = DC->getPrimaryContext();
531     auto *ND = dyn_cast<NamespaceDecl>(DC);
532     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533       return NestedNameSpecifier::Create(Context, nullptr, ND);
534     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536                                          RD->getTypeForDecl());
537     else if (isa<TranslationUnitDecl>(DC))
538       return NestedNameSpecifier::GlobalSpecifier(Context);
539   }
540   llvm_unreachable("something isn't in TU scope?");
541 }
542 
543 /// Find the parent class with dependent bases of the innermost enclosing method
544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545 /// up allowing unqualified dependent type names at class-level, which MSVC
546 /// correctly rejects.
547 static const CXXRecordDecl *
548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552       if (MD->getParent()->hasAnyDependentBases())
553         return MD->getParent();
554   }
555   return nullptr;
556 }
557 
558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559                                           SourceLocation NameLoc,
560                                           bool IsTemplateTypeArg) {
561   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
562 
563   NestedNameSpecifier *NNS = nullptr;
564   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565     // If we weren't able to parse a default template argument, delay lookup
566     // until instantiation time by making a non-dependent DependentTypeName. We
567     // pretend we saw a NestedNameSpecifier referring to the current scope, and
568     // lookup is retried.
569     // FIXME: This hurts our diagnostic quality, since we get errors like "no
570     // type named 'Foo' in 'current_namespace'" when the user didn't write any
571     // name specifiers.
572     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574   } else if (const CXXRecordDecl *RD =
575                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576     // Build a DependentNameType that will perform lookup into RD at
577     // instantiation time.
578     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579                                       RD->getTypeForDecl());
580 
581     // Diagnose that this identifier was undeclared, and retry the lookup during
582     // template instantiation.
583     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584                                                                       << RD;
585   } else {
586     // This is not a situation that we should recover from.
587     return ParsedType();
588   }
589 
590   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591 
592   // Build type location information.  We synthesized the qualifier, so we have
593   // to build a fake NestedNameSpecifierLoc.
594   NestedNameSpecifierLocBuilder NNSLocBuilder;
595   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597 
598   TypeLocBuilder Builder;
599   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600   DepTL.setNameLoc(NameLoc);
601   DepTL.setElaboratedKeywordLoc(SourceLocation());
602   DepTL.setQualifierLoc(QualifierLoc);
603   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604 }
605 
606 /// isTagName() - This method is called *for error recovery purposes only*
607 /// to determine if the specified name is a valid tag name ("struct foo").  If
608 /// so, this returns the TST for the tag corresponding to it (TST_enum,
609 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
610 /// cases in C where the user forgot to specify the tag.
611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612   // Do a tag name lookup in this scope.
613   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614   LookupName(R, S, false);
615   R.suppressDiagnostics();
616   if (R.getResultKind() == LookupResult::Found)
617     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618       switch (TD->getTagKind()) {
619       case TTK_Struct: return DeclSpec::TST_struct;
620       case TTK_Interface: return DeclSpec::TST_interface;
621       case TTK_Union:  return DeclSpec::TST_union;
622       case TTK_Class:  return DeclSpec::TST_class;
623       case TTK_Enum:   return DeclSpec::TST_enum;
624       }
625     }
626 
627   return DeclSpec::TST_unspecified;
628 }
629 
630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
632 /// then downgrade the missing typename error to a warning.
633 /// This is needed for MSVC compatibility; Example:
634 /// @code
635 /// template<class T> class A {
636 /// public:
637 ///   typedef int TYPE;
638 /// };
639 /// template<class T> class B : public A<T> {
640 /// public:
641 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
642 /// };
643 /// @endcode
644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645   if (CurContext->isRecord()) {
646     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647       return true;
648 
649     const Type *Ty = SS->getScopeRep()->getAsType();
650 
651     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652     for (const auto &Base : RD->bases())
653       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654         return true;
655     return S->isFunctionPrototypeScope();
656   }
657   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658 }
659 
660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661                                    SourceLocation IILoc,
662                                    Scope *S,
663                                    CXXScopeSpec *SS,
664                                    ParsedType &SuggestedType,
665                                    bool IsTemplateName) {
666   // Don't report typename errors for editor placeholders.
667   if (II->isEditorPlaceholder())
668     return;
669   // We don't have anything to suggest (yet).
670   SuggestedType = nullptr;
671 
672   // There may have been a typo in the name of the type. Look up typo
673   // results, in case we have something that we can suggest.
674   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675                            /*AllowTemplates=*/IsTemplateName,
676                            /*AllowNonTemplates=*/!IsTemplateName);
677   if (TypoCorrection Corrected =
678           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679                       CCC, CTK_ErrorRecovery)) {
680     // FIXME: Support error recovery for the template-name case.
681     bool CanRecover = !IsTemplateName;
682     if (Corrected.isKeyword()) {
683       // We corrected to a keyword.
684       diagnoseTypo(Corrected,
685                    PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                         : diag::err_unknown_typename_suggest)
687                        << II);
688       II = Corrected.getCorrectionAsIdentifierInfo();
689     } else {
690       // We found a similarly-named type or interface; suggest that.
691       if (!SS || !SS->isSet()) {
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName ? diag::err_no_template_suggest
694                                           : diag::err_unknown_typename_suggest)
695                          << II, CanRecover);
696       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699                                 II->getName().equals(CorrectedStr);
700         diagnoseTypo(Corrected,
701                      PDiag(IsTemplateName
702                                ? diag::err_no_member_template_suggest
703                                : diag::err_unknown_nested_typename_suggest)
704                          << II << DC << DroppedSpecifier << SS->getRange(),
705                      CanRecover);
706       } else {
707         llvm_unreachable("could not have corrected a typo here");
708       }
709 
710       if (!CanRecover)
711         return;
712 
713       CXXScopeSpec tmpSS;
714       if (Corrected.getCorrectionSpecifier())
715         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716                           SourceRange(IILoc));
717       // FIXME: Support class template argument deduction here.
718       SuggestedType =
719           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721                       /*IsCtorOrDtorName=*/false,
722                       /*WantNontrivialTypeSourceInfo=*/true);
723     }
724     return;
725   }
726 
727   if (getLangOpts().CPlusPlus && !IsTemplateName) {
728     // See if II is a class template that the user forgot to pass arguments to.
729     UnqualifiedId Name;
730     Name.setIdentifier(II, IILoc);
731     CXXScopeSpec EmptySS;
732     TemplateTy TemplateResult;
733     bool MemberOfUnknownSpecialization;
734     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735                        Name, nullptr, true, TemplateResult,
736                        MemberOfUnknownSpecialization) == TNK_Type_template) {
737       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738       return;
739     }
740   }
741 
742   // FIXME: Should we move the logic that tries to recover from a missing tag
743   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744 
745   if (!SS || (!SS->isSet() && !SS->isInvalid()))
746     Diag(IILoc, IsTemplateName ? diag::err_no_template
747                                : diag::err_unknown_typename)
748         << II;
749   else if (DeclContext *DC = computeDeclContext(*SS, false))
750     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751                                : diag::err_typename_nested_not_found)
752         << II << DC << SS->getRange();
753   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754     SuggestedType =
755         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756   } else if (isDependentScopeSpecifier(*SS)) {
757     unsigned DiagID = diag::err_typename_missing;
758     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759       DiagID = diag::ext_typename_missing;
760 
761     Diag(SS->getRange().getBegin(), DiagID)
762       << SS->getScopeRep() << II->getName()
763       << SourceRange(SS->getRange().getBegin(), IILoc)
764       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765     SuggestedType = ActOnTypenameType(S, SourceLocation(),
766                                       *SS, *II, IILoc).get();
767   } else {
768     assert(SS && SS->isInvalid() &&
769            "Invalid scope specifier has already been diagnosed");
770   }
771 }
772 
773 /// Determine whether the given result set contains either a type name
774 /// or
775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777                        NextToken.is(tok::less);
778 
779   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781       return true;
782 
783     if (CheckTemplate && isa<TemplateDecl>(*I))
784       return true;
785   }
786 
787   return false;
788 }
789 
790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791                                     Scope *S, CXXScopeSpec &SS,
792                                     IdentifierInfo *&Name,
793                                     SourceLocation NameLoc) {
794   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795   SemaRef.LookupParsedName(R, S, &SS);
796   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797     StringRef FixItTagName;
798     switch (Tag->getTagKind()) {
799       case TTK_Class:
800         FixItTagName = "class ";
801         break;
802 
803       case TTK_Enum:
804         FixItTagName = "enum ";
805         break;
806 
807       case TTK_Struct:
808         FixItTagName = "struct ";
809         break;
810 
811       case TTK_Interface:
812         FixItTagName = "__interface ";
813         break;
814 
815       case TTK_Union:
816         FixItTagName = "union ";
817         break;
818     }
819 
820     StringRef TagName = FixItTagName.drop_back();
821     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824 
825     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826          I != IEnd; ++I)
827       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828         << Name << TagName;
829 
830     // Replace lookup results with just the tag decl.
831     Result.clear(Sema::LookupTagName);
832     SemaRef.LookupParsedName(Result, S, &SS);
833     return true;
834   }
835 
836   return false;
837 }
838 
839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841                                   QualType T, SourceLocation NameLoc) {
842   ASTContext &Context = S.Context;
843 
844   TypeLocBuilder Builder;
845   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846 
847   T = S.getElaboratedType(ETK_None, SS, T);
848   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849   ElabTL.setElaboratedKeywordLoc(SourceLocation());
850   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852 }
853 
854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855                                             IdentifierInfo *&Name,
856                                             SourceLocation NameLoc,
857                                             const Token &NextToken,
858                                             CorrectionCandidateCallback *CCC) {
859   DeclarationNameInfo NameInfo(Name, NameLoc);
860   ObjCMethodDecl *CurMethod = getCurMethodDecl();
861 
862   assert(NextToken.isNot(tok::coloncolon) &&
863          "parse nested name specifiers before calling ClassifyName");
864   if (getLangOpts().CPlusPlus && SS.isSet() &&
865       isCurrentClassName(*Name, S, &SS)) {
866     // Per [class.qual]p2, this names the constructors of SS, not the
867     // injected-class-name. We don't have a classification for that.
868     // There's not much point caching this result, since the parser
869     // will reject it later.
870     return NameClassification::Unknown();
871   }
872 
873   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874   LookupParsedName(Result, S, &SS, !CurMethod);
875 
876   if (SS.isInvalid())
877     return NameClassification::Error();
878 
879   // For unqualified lookup in a class template in MSVC mode, look into
880   // dependent base classes where the primary class template is known.
881   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882     if (ParsedType TypeInBase =
883             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884       return TypeInBase;
885   }
886 
887   // Perform lookup for Objective-C instance variables (including automatically
888   // synthesized instance variables), if we're in an Objective-C method.
889   // FIXME: This lookup really, really needs to be folded in to the normal
890   // unqualified lookup mechanism.
891   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893     if (Ivar.isInvalid())
894       return NameClassification::Error();
895     if (Ivar.isUsable())
896       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897 
898     // We defer builtin creation until after ivar lookup inside ObjC methods.
899     if (Result.empty())
900       LookupBuiltin(Result);
901   }
902 
903   bool SecondTry = false;
904   bool IsFilteredTemplateName = false;
905 
906 Corrected:
907   switch (Result.getResultKind()) {
908   case LookupResult::NotFound:
909     // If an unqualified-id is followed by a '(', then we have a function
910     // call.
911     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912       // In C++, this is an ADL-only call.
913       // FIXME: Reference?
914       if (getLangOpts().CPlusPlus)
915         return NameClassification::UndeclaredNonType();
916 
917       // C90 6.3.2.2:
918       //   If the expression that precedes the parenthesized argument list in a
919       //   function call consists solely of an identifier, and if no
920       //   declaration is visible for this identifier, the identifier is
921       //   implicitly declared exactly as if, in the innermost block containing
922       //   the function call, the declaration
923       //
924       //     extern int identifier ();
925       //
926       //   appeared.
927       //
928       // We also allow this in C99 as an extension.
929       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930         return NameClassification::NonType(D);
931     }
932 
933     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934       // In C++20 onwards, this could be an ADL-only call to a function
935       // template, and we're required to assume that this is a template name.
936       //
937       // FIXME: Find a way to still do typo correction in this case.
938       TemplateName Template =
939           Context.getAssumedTemplateName(NameInfo.getName());
940       return NameClassification::UndeclaredTemplate(Template);
941     }
942 
943     // In C, we first see whether there is a tag type by the same name, in
944     // which case it's likely that the user just forgot to write "enum",
945     // "struct", or "union".
946     if (!getLangOpts().CPlusPlus && !SecondTry &&
947         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948       break;
949     }
950 
951     // Perform typo correction to determine if there is another name that is
952     // close to this name.
953     if (!SecondTry && CCC) {
954       SecondTry = true;
955       if (TypoCorrection Corrected =
956               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957                           &SS, *CCC, CTK_ErrorRecovery)) {
958         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959         unsigned QualifiedDiag = diag::err_no_member_suggest;
960 
961         NamedDecl *FirstDecl = Corrected.getFoundDecl();
962         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965           UnqualifiedDiag = diag::err_no_template_suggest;
966           QualifiedDiag = diag::err_no_member_template_suggest;
967         } else if (UnderlyingFirstDecl &&
968                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
969                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971           UnqualifiedDiag = diag::err_unknown_typename_suggest;
972           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973         }
974 
975         if (SS.isEmpty()) {
976           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977         } else {// FIXME: is this even reachable? Test it.
978           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980                                   Name->getName().equals(CorrectedStr);
981           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982                                     << Name << computeDeclContext(SS, false)
983                                     << DroppedSpecifier << SS.getRange());
984         }
985 
986         // Update the name, so that the caller has the new name.
987         Name = Corrected.getCorrectionAsIdentifierInfo();
988 
989         // Typo correction corrected to a keyword.
990         if (Corrected.isKeyword())
991           return Name;
992 
993         // Also update the LookupResult...
994         // FIXME: This should probably go away at some point
995         Result.clear();
996         Result.setLookupName(Corrected.getCorrection());
997         if (FirstDecl)
998           Result.addDecl(FirstDecl);
999 
1000         // If we found an Objective-C instance variable, let
1001         // LookupInObjCMethod build the appropriate expression to
1002         // reference the ivar.
1003         // FIXME: This is a gross hack.
1004         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005           DeclResult R =
1006               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007           if (R.isInvalid())
1008             return NameClassification::Error();
1009           if (R.isUsable())
1010             return NameClassification::NonType(Ivar);
1011         }
1012 
1013         goto Corrected;
1014       }
1015     }
1016 
1017     // We failed to correct; just fall through and let the parser deal with it.
1018     Result.suppressDiagnostics();
1019     return NameClassification::Unknown();
1020 
1021   case LookupResult::NotFoundInCurrentInstantiation: {
1022     // We performed name lookup into the current instantiation, and there were
1023     // dependent bases, so we treat this result the same way as any other
1024     // dependent nested-name-specifier.
1025 
1026     // C++ [temp.res]p2:
1027     //   A name used in a template declaration or definition and that is
1028     //   dependent on a template-parameter is assumed not to name a type
1029     //   unless the applicable name lookup finds a type name or the name is
1030     //   qualified by the keyword typename.
1031     //
1032     // FIXME: If the next token is '<', we might want to ask the parser to
1033     // perform some heroics to see if we actually have a
1034     // template-argument-list, which would indicate a missing 'template'
1035     // keyword here.
1036     return NameClassification::DependentNonType();
1037   }
1038 
1039   case LookupResult::Found:
1040   case LookupResult::FoundOverloaded:
1041   case LookupResult::FoundUnresolvedValue:
1042     break;
1043 
1044   case LookupResult::Ambiguous:
1045     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                       /*AllowDependent=*/false)) {
1048       // C++ [temp.local]p3:
1049       //   A lookup that finds an injected-class-name (10.2) can result in an
1050       //   ambiguity in certain cases (for example, if it is found in more than
1051       //   one base class). If all of the injected-class-names that are found
1052       //   refer to specializations of the same class template, and if the name
1053       //   is followed by a template-argument-list, the reference refers to the
1054       //   class template itself and not a specialization thereof, and is not
1055       //   ambiguous.
1056       //
1057       // This filtering can make an ambiguous result into an unambiguous one,
1058       // so try again after filtering out template names.
1059       FilterAcceptableTemplateNames(Result);
1060       if (!Result.isAmbiguous()) {
1061         IsFilteredTemplateName = true;
1062         break;
1063       }
1064     }
1065 
1066     // Diagnose the ambiguity and return an error.
1067     return NameClassification::Error();
1068   }
1069 
1070   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071       (IsFilteredTemplateName ||
1072        hasAnyAcceptableTemplateNames(
1073            Result, /*AllowFunctionTemplates=*/true,
1074            /*AllowDependent=*/false,
1075            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076                getLangOpts().CPlusPlus20))) {
1077     // C++ [temp.names]p3:
1078     //   After name lookup (3.4) finds that a name is a template-name or that
1079     //   an operator-function-id or a literal- operator-id refers to a set of
1080     //   overloaded functions any member of which is a function template if
1081     //   this is followed by a <, the < is always taken as the delimiter of a
1082     //   template-argument-list and never as the less-than operator.
1083     // C++2a [temp.names]p2:
1084     //   A name is also considered to refer to a template if it is an
1085     //   unqualified-id followed by a < and name lookup finds either one
1086     //   or more functions or finds nothing.
1087     if (!IsFilteredTemplateName)
1088       FilterAcceptableTemplateNames(Result);
1089 
1090     bool IsFunctionTemplate;
1091     bool IsVarTemplate;
1092     TemplateName Template;
1093     if (Result.end() - Result.begin() > 1) {
1094       IsFunctionTemplate = true;
1095       Template = Context.getOverloadedTemplateName(Result.begin(),
1096                                                    Result.end());
1097     } else if (!Result.empty()) {
1098       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099           *Result.begin(), /*AllowFunctionTemplates=*/true,
1100           /*AllowDependent=*/false));
1101       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102       IsVarTemplate = isa<VarTemplateDecl>(TD);
1103 
1104       if (SS.isNotEmpty())
1105         Template =
1106             Context.getQualifiedTemplateName(SS.getScopeRep(),
1107                                              /*TemplateKeyword=*/false, TD);
1108       else
1109         Template = TemplateName(TD);
1110     } else {
1111       // All results were non-template functions. This is a function template
1112       // name.
1113       IsFunctionTemplate = true;
1114       Template = Context.getAssumedTemplateName(NameInfo.getName());
1115     }
1116 
1117     if (IsFunctionTemplate) {
1118       // Function templates always go through overload resolution, at which
1119       // point we'll perform the various checks (e.g., accessibility) we need
1120       // to based on which function we selected.
1121       Result.suppressDiagnostics();
1122 
1123       return NameClassification::FunctionTemplate(Template);
1124     }
1125 
1126     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127                          : NameClassification::TypeTemplate(Template);
1128   }
1129 
1130   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132     DiagnoseUseOfDecl(Type, NameLoc);
1133     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134     QualType T = Context.getTypeDeclType(Type);
1135     if (SS.isNotEmpty())
1136       return buildNestedType(*this, SS, T, NameLoc);
1137     return ParsedType::make(T);
1138   }
1139 
1140   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141   if (!Class) {
1142     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143     if (ObjCCompatibleAliasDecl *Alias =
1144             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145       Class = Alias->getClassInterface();
1146   }
1147 
1148   if (Class) {
1149     DiagnoseUseOfDecl(Class, NameLoc);
1150 
1151     if (NextToken.is(tok::period)) {
1152       // Interface. <something> is parsed as a property reference expression.
1153       // Just return "unknown" as a fall-through for now.
1154       Result.suppressDiagnostics();
1155       return NameClassification::Unknown();
1156     }
1157 
1158     QualType T = Context.getObjCInterfaceType(Class);
1159     return ParsedType::make(T);
1160   }
1161 
1162   if (isa<ConceptDecl>(FirstDecl))
1163     return NameClassification::Concept(
1164         TemplateName(cast<TemplateDecl>(FirstDecl)));
1165 
1166   // We can have a type template here if we're classifying a template argument.
1167   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168       !isa<VarTemplateDecl>(FirstDecl))
1169     return NameClassification::TypeTemplate(
1170         TemplateName(cast<TemplateDecl>(FirstDecl)));
1171 
1172   // Check for a tag type hidden by a non-type decl in a few cases where it
1173   // seems likely a type is wanted instead of the non-type that was found.
1174   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175   if ((NextToken.is(tok::identifier) ||
1176        (NextIsOp &&
1177         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180     DiagnoseUseOfDecl(Type, NameLoc);
1181     QualType T = Context.getTypeDeclType(Type);
1182     if (SS.isNotEmpty())
1183       return buildNestedType(*this, SS, T, NameLoc);
1184     return ParsedType::make(T);
1185   }
1186 
1187   // If we already know which single declaration is referenced, just annotate
1188   // that declaration directly. Defer resolving even non-overloaded class
1189   // member accesses, as we need to defer certain access checks until we know
1190   // the context.
1191   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1193     return NameClassification::NonType(Result.getRepresentativeDecl());
1194 
1195   // Otherwise, this is an overload set that we will need to resolve later.
1196   Result.suppressDiagnostics();
1197   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1198       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1199       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1200       Result.begin(), Result.end()));
1201 }
1202 
1203 ExprResult
1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1205                                              SourceLocation NameLoc) {
1206   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1207   CXXScopeSpec SS;
1208   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1209   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1210 }
1211 
1212 ExprResult
1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1214                                             IdentifierInfo *Name,
1215                                             SourceLocation NameLoc,
1216                                             bool IsAddressOfOperand) {
1217   DeclarationNameInfo NameInfo(Name, NameLoc);
1218   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1219                                     NameInfo, IsAddressOfOperand,
1220                                     /*TemplateArgs=*/nullptr);
1221 }
1222 
1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1224                                               NamedDecl *Found,
1225                                               SourceLocation NameLoc,
1226                                               const Token &NextToken) {
1227   if (getCurMethodDecl() && SS.isEmpty())
1228     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1229       return BuildIvarRefExpr(S, NameLoc, Ivar);
1230 
1231   // Reconstruct the lookup result.
1232   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1233   Result.addDecl(Found);
1234   Result.resolveKind();
1235 
1236   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237   return BuildDeclarationNameExpr(SS, Result, ADL);
1238 }
1239 
1240 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1241   // For an implicit class member access, transform the result into a member
1242   // access expression if necessary.
1243   auto *ULE = cast<UnresolvedLookupExpr>(E);
1244   if ((*ULE->decls_begin())->isCXXClassMember()) {
1245     CXXScopeSpec SS;
1246     SS.Adopt(ULE->getQualifierLoc());
1247 
1248     // Reconstruct the lookup result.
1249     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1250                         LookupOrdinaryName);
1251     Result.setNamingClass(ULE->getNamingClass());
1252     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1253       Result.addDecl(*I, I.getAccess());
1254     Result.resolveKind();
1255     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1256                                            nullptr, S);
1257   }
1258 
1259   // Otherwise, this is already in the form we needed, and no further checks
1260   // are necessary.
1261   return ULE;
1262 }
1263 
1264 Sema::TemplateNameKindForDiagnostics
1265 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1266   auto *TD = Name.getAsTemplateDecl();
1267   if (!TD)
1268     return TemplateNameKindForDiagnostics::DependentTemplate;
1269   if (isa<ClassTemplateDecl>(TD))
1270     return TemplateNameKindForDiagnostics::ClassTemplate;
1271   if (isa<FunctionTemplateDecl>(TD))
1272     return TemplateNameKindForDiagnostics::FunctionTemplate;
1273   if (isa<VarTemplateDecl>(TD))
1274     return TemplateNameKindForDiagnostics::VarTemplate;
1275   if (isa<TypeAliasTemplateDecl>(TD))
1276     return TemplateNameKindForDiagnostics::AliasTemplate;
1277   if (isa<TemplateTemplateParmDecl>(TD))
1278     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1279   if (isa<ConceptDecl>(TD))
1280     return TemplateNameKindForDiagnostics::Concept;
1281   return TemplateNameKindForDiagnostics::DependentTemplate;
1282 }
1283 
1284 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1285   assert(DC->getLexicalParent() == CurContext &&
1286       "The next DeclContext should be lexically contained in the current one.");
1287   CurContext = DC;
1288   S->setEntity(DC);
1289 }
1290 
1291 void Sema::PopDeclContext() {
1292   assert(CurContext && "DeclContext imbalance!");
1293 
1294   CurContext = CurContext->getLexicalParent();
1295   assert(CurContext && "Popped translation unit!");
1296 }
1297 
1298 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1299                                                                     Decl *D) {
1300   // Unlike PushDeclContext, the context to which we return is not necessarily
1301   // the containing DC of TD, because the new context will be some pre-existing
1302   // TagDecl definition instead of a fresh one.
1303   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1304   CurContext = cast<TagDecl>(D)->getDefinition();
1305   assert(CurContext && "skipping definition of undefined tag");
1306   // Start lookups from the parent of the current context; we don't want to look
1307   // into the pre-existing complete definition.
1308   S->setEntity(CurContext->getLookupParent());
1309   return Result;
1310 }
1311 
1312 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1313   CurContext = static_cast<decltype(CurContext)>(Context);
1314 }
1315 
1316 /// EnterDeclaratorContext - Used when we must lookup names in the context
1317 /// of a declarator's nested name specifier.
1318 ///
1319 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1320   // C++0x [basic.lookup.unqual]p13:
1321   //   A name used in the definition of a static data member of class
1322   //   X (after the qualified-id of the static member) is looked up as
1323   //   if the name was used in a member function of X.
1324   // C++0x [basic.lookup.unqual]p14:
1325   //   If a variable member of a namespace is defined outside of the
1326   //   scope of its namespace then any name used in the definition of
1327   //   the variable member (after the declarator-id) is looked up as
1328   //   if the definition of the variable member occurred in its
1329   //   namespace.
1330   // Both of these imply that we should push a scope whose context
1331   // is the semantic context of the declaration.  We can't use
1332   // PushDeclContext here because that context is not necessarily
1333   // lexically contained in the current context.  Fortunately,
1334   // the containing scope should have the appropriate information.
1335 
1336   assert(!S->getEntity() && "scope already has entity");
1337 
1338 #ifndef NDEBUG
1339   Scope *Ancestor = S->getParent();
1340   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1342 #endif
1343 
1344   CurContext = DC;
1345   S->setEntity(DC);
1346 
1347   if (S->getParent()->isTemplateParamScope()) {
1348     // Also set the corresponding entities for all immediately-enclosing
1349     // template parameter scopes.
1350     EnterTemplatedContext(S->getParent(), DC);
1351   }
1352 }
1353 
1354 void Sema::ExitDeclaratorContext(Scope *S) {
1355   assert(S->getEntity() == CurContext && "Context imbalance!");
1356 
1357   // Switch back to the lexical context.  The safety of this is
1358   // enforced by an assert in EnterDeclaratorContext.
1359   Scope *Ancestor = S->getParent();
1360   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361   CurContext = Ancestor->getEntity();
1362 
1363   // We don't need to do anything with the scope, which is going to
1364   // disappear.
1365 }
1366 
1367 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1368   assert(S->isTemplateParamScope() &&
1369          "expected to be initializing a template parameter scope");
1370 
1371   // C++20 [temp.local]p7:
1372   //   In the definition of a member of a class template that appears outside
1373   //   of the class template definition, the name of a member of the class
1374   //   template hides the name of a template-parameter of any enclosing class
1375   //   templates (but not a template-parameter of the member if the member is a
1376   //   class or function template).
1377   // C++20 [temp.local]p9:
1378   //   In the definition of a class template or in the definition of a member
1379   //   of such a template that appears outside of the template definition, for
1380   //   each non-dependent base class (13.8.2.1), if the name of the base class
1381   //   or the name of a member of the base class is the same as the name of a
1382   //   template-parameter, the base class name or member name hides the
1383   //   template-parameter name (6.4.10).
1384   //
1385   // This means that a template parameter scope should be searched immediately
1386   // after searching the DeclContext for which it is a template parameter
1387   // scope. For example, for
1388   //   template<typename T> template<typename U> template<typename V>
1389   //     void N::A<T>::B<U>::f(...)
1390   // we search V then B<U> (and base classes) then U then A<T> (and base
1391   // classes) then T then N then ::.
1392   unsigned ScopeDepth = getTemplateDepth(S);
1393   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1394     DeclContext *SearchDCAfterScope = DC;
1395     for (; DC; DC = DC->getLookupParent()) {
1396       if (const TemplateParameterList *TPL =
1397               cast<Decl>(DC)->getDescribedTemplateParams()) {
1398         unsigned DCDepth = TPL->getDepth() + 1;
1399         if (DCDepth > ScopeDepth)
1400           continue;
1401         if (ScopeDepth == DCDepth)
1402           SearchDCAfterScope = DC = DC->getLookupParent();
1403         break;
1404       }
1405     }
1406     S->setLookupEntity(SearchDCAfterScope);
1407   }
1408 }
1409 
1410 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1411   // We assume that the caller has already called
1412   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1413   FunctionDecl *FD = D->getAsFunction();
1414   if (!FD)
1415     return;
1416 
1417   // Same implementation as PushDeclContext, but enters the context
1418   // from the lexical parent, rather than the top-level class.
1419   assert(CurContext == FD->getLexicalParent() &&
1420     "The next DeclContext should be lexically contained in the current one.");
1421   CurContext = FD;
1422   S->setEntity(CurContext);
1423 
1424   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1425     ParmVarDecl *Param = FD->getParamDecl(P);
1426     // If the parameter has an identifier, then add it to the scope
1427     if (Param->getIdentifier()) {
1428       S->AddDecl(Param);
1429       IdResolver.AddDecl(Param);
1430     }
1431   }
1432 }
1433 
1434 void Sema::ActOnExitFunctionContext() {
1435   // Same implementation as PopDeclContext, but returns to the lexical parent,
1436   // rather than the top-level class.
1437   assert(CurContext && "DeclContext imbalance!");
1438   CurContext = CurContext->getLexicalParent();
1439   assert(CurContext && "Popped translation unit!");
1440 }
1441 
1442 /// Determine whether we allow overloading of the function
1443 /// PrevDecl with another declaration.
1444 ///
1445 /// This routine determines whether overloading is possible, not
1446 /// whether some new function is actually an overload. It will return
1447 /// true in C++ (where we can always provide overloads) or, as an
1448 /// extension, in C when the previous function is already an
1449 /// overloaded function declaration or has the "overloadable"
1450 /// attribute.
1451 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1452                                        ASTContext &Context,
1453                                        const FunctionDecl *New) {
1454   if (Context.getLangOpts().CPlusPlus)
1455     return true;
1456 
1457   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1458     return true;
1459 
1460   return Previous.getResultKind() == LookupResult::Found &&
1461          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1462           New->hasAttr<OverloadableAttr>());
1463 }
1464 
1465 /// Add this decl to the scope shadowed decl chains.
1466 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1467   // Move up the scope chain until we find the nearest enclosing
1468   // non-transparent context. The declaration will be introduced into this
1469   // scope.
1470   while (S->getEntity() && S->getEntity()->isTransparentContext())
1471     S = S->getParent();
1472 
1473   // Add scoped declarations into their context, so that they can be
1474   // found later. Declarations without a context won't be inserted
1475   // into any context.
1476   if (AddToContext)
1477     CurContext->addDecl(D);
1478 
1479   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1480   // are function-local declarations.
1481   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1482       !D->getDeclContext()->getRedeclContext()->Equals(
1483         D->getLexicalDeclContext()->getRedeclContext()) &&
1484       !D->getLexicalDeclContext()->isFunctionOrMethod())
1485     return;
1486 
1487   // Template instantiations should also not be pushed into scope.
1488   if (isa<FunctionDecl>(D) &&
1489       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1490     return;
1491 
1492   // If this replaces anything in the current scope,
1493   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1494                                IEnd = IdResolver.end();
1495   for (; I != IEnd; ++I) {
1496     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1497       S->RemoveDecl(*I);
1498       IdResolver.RemoveDecl(*I);
1499 
1500       // Should only need to replace one decl.
1501       break;
1502     }
1503   }
1504 
1505   S->AddDecl(D);
1506 
1507   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1508     // Implicitly-generated labels may end up getting generated in an order that
1509     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1510     // the label at the appropriate place in the identifier chain.
1511     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1512       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1513       if (IDC == CurContext) {
1514         if (!S->isDeclScope(*I))
1515           continue;
1516       } else if (IDC->Encloses(CurContext))
1517         break;
1518     }
1519 
1520     IdResolver.InsertDeclAfter(I, D);
1521   } else {
1522     IdResolver.AddDecl(D);
1523   }
1524 }
1525 
1526 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1527                          bool AllowInlineNamespace) {
1528   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1529 }
1530 
1531 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1532   DeclContext *TargetDC = DC->getPrimaryContext();
1533   do {
1534     if (DeclContext *ScopeDC = S->getEntity())
1535       if (ScopeDC->getPrimaryContext() == TargetDC)
1536         return S;
1537   } while ((S = S->getParent()));
1538 
1539   return nullptr;
1540 }
1541 
1542 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1543                                             DeclContext*,
1544                                             ASTContext&);
1545 
1546 /// Filters out lookup results that don't fall within the given scope
1547 /// as determined by isDeclInScope.
1548 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1549                                 bool ConsiderLinkage,
1550                                 bool AllowInlineNamespace) {
1551   LookupResult::Filter F = R.makeFilter();
1552   while (F.hasNext()) {
1553     NamedDecl *D = F.next();
1554 
1555     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1556       continue;
1557 
1558     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1559       continue;
1560 
1561     F.erase();
1562   }
1563 
1564   F.done();
1565 }
1566 
1567 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1568 /// have compatible owning modules.
1569 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1570   // FIXME: The Modules TS is not clear about how friend declarations are
1571   // to be treated. It's not meaningful to have different owning modules for
1572   // linkage in redeclarations of the same entity, so for now allow the
1573   // redeclaration and change the owning modules to match.
1574   if (New->getFriendObjectKind() &&
1575       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1576     New->setLocalOwningModule(Old->getOwningModule());
1577     makeMergedDefinitionVisible(New);
1578     return false;
1579   }
1580 
1581   Module *NewM = New->getOwningModule();
1582   Module *OldM = Old->getOwningModule();
1583 
1584   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1585     NewM = NewM->Parent;
1586   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1587     OldM = OldM->Parent;
1588 
1589   if (NewM == OldM)
1590     return false;
1591 
1592   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1593   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1594   if (NewIsModuleInterface || OldIsModuleInterface) {
1595     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1596     //   if a declaration of D [...] appears in the purview of a module, all
1597     //   other such declarations shall appear in the purview of the same module
1598     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1599       << New
1600       << NewIsModuleInterface
1601       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1602       << OldIsModuleInterface
1603       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1604     Diag(Old->getLocation(), diag::note_previous_declaration);
1605     New->setInvalidDecl();
1606     return true;
1607   }
1608 
1609   return false;
1610 }
1611 
1612 static bool isUsingDecl(NamedDecl *D) {
1613   return isa<UsingShadowDecl>(D) ||
1614          isa<UnresolvedUsingTypenameDecl>(D) ||
1615          isa<UnresolvedUsingValueDecl>(D);
1616 }
1617 
1618 /// Removes using shadow declarations from the lookup results.
1619 static void RemoveUsingDecls(LookupResult &R) {
1620   LookupResult::Filter F = R.makeFilter();
1621   while (F.hasNext())
1622     if (isUsingDecl(F.next()))
1623       F.erase();
1624 
1625   F.done();
1626 }
1627 
1628 /// Check for this common pattern:
1629 /// @code
1630 /// class S {
1631 ///   S(const S&); // DO NOT IMPLEMENT
1632 ///   void operator=(const S&); // DO NOT IMPLEMENT
1633 /// };
1634 /// @endcode
1635 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1636   // FIXME: Should check for private access too but access is set after we get
1637   // the decl here.
1638   if (D->doesThisDeclarationHaveABody())
1639     return false;
1640 
1641   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1642     return CD->isCopyConstructor();
1643   return D->isCopyAssignmentOperator();
1644 }
1645 
1646 // We need this to handle
1647 //
1648 // typedef struct {
1649 //   void *foo() { return 0; }
1650 // } A;
1651 //
1652 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1653 // for example. If 'A', foo will have external linkage. If we have '*A',
1654 // foo will have no linkage. Since we can't know until we get to the end
1655 // of the typedef, this function finds out if D might have non-external linkage.
1656 // Callers should verify at the end of the TU if it D has external linkage or
1657 // not.
1658 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1659   const DeclContext *DC = D->getDeclContext();
1660   while (!DC->isTranslationUnit()) {
1661     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1662       if (!RD->hasNameForLinkage())
1663         return true;
1664     }
1665     DC = DC->getParent();
1666   }
1667 
1668   return !D->isExternallyVisible();
1669 }
1670 
1671 // FIXME: This needs to be refactored; some other isInMainFile users want
1672 // these semantics.
1673 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1674   if (S.TUKind != TU_Complete)
1675     return false;
1676   return S.SourceMgr.isInMainFile(Loc);
1677 }
1678 
1679 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1680   assert(D);
1681 
1682   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1683     return false;
1684 
1685   // Ignore all entities declared within templates, and out-of-line definitions
1686   // of members of class templates.
1687   if (D->getDeclContext()->isDependentContext() ||
1688       D->getLexicalDeclContext()->isDependentContext())
1689     return false;
1690 
1691   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1692     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1693       return false;
1694     // A non-out-of-line declaration of a member specialization was implicitly
1695     // instantiated; it's the out-of-line declaration that we're interested in.
1696     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1697         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1698       return false;
1699 
1700     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1701       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1702         return false;
1703     } else {
1704       // 'static inline' functions are defined in headers; don't warn.
1705       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1706         return false;
1707     }
1708 
1709     if (FD->doesThisDeclarationHaveABody() &&
1710         Context.DeclMustBeEmitted(FD))
1711       return false;
1712   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713     // Constants and utility variables are defined in headers with internal
1714     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1715     // like "inline".)
1716     if (!isMainFileLoc(*this, VD->getLocation()))
1717       return false;
1718 
1719     if (Context.DeclMustBeEmitted(VD))
1720       return false;
1721 
1722     if (VD->isStaticDataMember() &&
1723         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1724       return false;
1725     if (VD->isStaticDataMember() &&
1726         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1727         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1728       return false;
1729 
1730     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1731       return false;
1732   } else {
1733     return false;
1734   }
1735 
1736   // Only warn for unused decls internal to the translation unit.
1737   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1738   // for inline functions defined in the main source file, for instance.
1739   return mightHaveNonExternalLinkage(D);
1740 }
1741 
1742 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1743   if (!D)
1744     return;
1745 
1746   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1747     const FunctionDecl *First = FD->getFirstDecl();
1748     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1749       return; // First should already be in the vector.
1750   }
1751 
1752   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753     const VarDecl *First = VD->getFirstDecl();
1754     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1755       return; // First should already be in the vector.
1756   }
1757 
1758   if (ShouldWarnIfUnusedFileScopedDecl(D))
1759     UnusedFileScopedDecls.push_back(D);
1760 }
1761 
1762 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1763   if (D->isInvalidDecl())
1764     return false;
1765 
1766   bool Referenced = false;
1767   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1768     // For a decomposition declaration, warn if none of the bindings are
1769     // referenced, instead of if the variable itself is referenced (which
1770     // it is, by the bindings' expressions).
1771     for (auto *BD : DD->bindings()) {
1772       if (BD->isReferenced()) {
1773         Referenced = true;
1774         break;
1775       }
1776     }
1777   } else if (!D->getDeclName()) {
1778     return false;
1779   } else if (D->isReferenced() || D->isUsed()) {
1780     Referenced = true;
1781   }
1782 
1783   if (Referenced || D->hasAttr<UnusedAttr>() ||
1784       D->hasAttr<ObjCPreciseLifetimeAttr>())
1785     return false;
1786 
1787   if (isa<LabelDecl>(D))
1788     return true;
1789 
1790   // Except for labels, we only care about unused decls that are local to
1791   // functions.
1792   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1793   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1794     // For dependent types, the diagnostic is deferred.
1795     WithinFunction =
1796         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1797   if (!WithinFunction)
1798     return false;
1799 
1800   if (isa<TypedefNameDecl>(D))
1801     return true;
1802 
1803   // White-list anything that isn't a local variable.
1804   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1805     return false;
1806 
1807   // Types of valid local variables should be complete, so this should succeed.
1808   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1809 
1810     // White-list anything with an __attribute__((unused)) type.
1811     const auto *Ty = VD->getType().getTypePtr();
1812 
1813     // Only look at the outermost level of typedef.
1814     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1815       if (TT->getDecl()->hasAttr<UnusedAttr>())
1816         return false;
1817     }
1818 
1819     // If we failed to complete the type for some reason, or if the type is
1820     // dependent, don't diagnose the variable.
1821     if (Ty->isIncompleteType() || Ty->isDependentType())
1822       return false;
1823 
1824     // Look at the element type to ensure that the warning behaviour is
1825     // consistent for both scalars and arrays.
1826     Ty = Ty->getBaseElementTypeUnsafe();
1827 
1828     if (const TagType *TT = Ty->getAs<TagType>()) {
1829       const TagDecl *Tag = TT->getDecl();
1830       if (Tag->hasAttr<UnusedAttr>())
1831         return false;
1832 
1833       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1834         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1835           return false;
1836 
1837         if (const Expr *Init = VD->getInit()) {
1838           if (const ExprWithCleanups *Cleanups =
1839                   dyn_cast<ExprWithCleanups>(Init))
1840             Init = Cleanups->getSubExpr();
1841           const CXXConstructExpr *Construct =
1842             dyn_cast<CXXConstructExpr>(Init);
1843           if (Construct && !Construct->isElidable()) {
1844             CXXConstructorDecl *CD = Construct->getConstructor();
1845             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1846                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1847               return false;
1848           }
1849 
1850           // Suppress the warning if we don't know how this is constructed, and
1851           // it could possibly be non-trivial constructor.
1852           if (Init->isTypeDependent())
1853             for (const CXXConstructorDecl *Ctor : RD->ctors())
1854               if (!Ctor->isTrivial())
1855                 return false;
1856         }
1857       }
1858     }
1859 
1860     // TODO: __attribute__((unused)) templates?
1861   }
1862 
1863   return true;
1864 }
1865 
1866 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1867                                      FixItHint &Hint) {
1868   if (isa<LabelDecl>(D)) {
1869     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1870         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1871         true);
1872     if (AfterColon.isInvalid())
1873       return;
1874     Hint = FixItHint::CreateRemoval(
1875         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1876   }
1877 }
1878 
1879 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1880   if (D->getTypeForDecl()->isDependentType())
1881     return;
1882 
1883   for (auto *TmpD : D->decls()) {
1884     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1885       DiagnoseUnusedDecl(T);
1886     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1887       DiagnoseUnusedNestedTypedefs(R);
1888   }
1889 }
1890 
1891 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1892 /// unless they are marked attr(unused).
1893 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1894   if (!ShouldDiagnoseUnusedDecl(D))
1895     return;
1896 
1897   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1898     // typedefs can be referenced later on, so the diagnostics are emitted
1899     // at end-of-translation-unit.
1900     UnusedLocalTypedefNameCandidates.insert(TD);
1901     return;
1902   }
1903 
1904   FixItHint Hint;
1905   GenerateFixForUnusedDecl(D, Context, Hint);
1906 
1907   unsigned DiagID;
1908   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1909     DiagID = diag::warn_unused_exception_param;
1910   else if (isa<LabelDecl>(D))
1911     DiagID = diag::warn_unused_label;
1912   else
1913     DiagID = diag::warn_unused_variable;
1914 
1915   Diag(D->getLocation(), DiagID) << D << Hint;
1916 }
1917 
1918 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1919   // Verify that we have no forward references left.  If so, there was a goto
1920   // or address of a label taken, but no definition of it.  Label fwd
1921   // definitions are indicated with a null substmt which is also not a resolved
1922   // MS inline assembly label name.
1923   bool Diagnose = false;
1924   if (L->isMSAsmLabel())
1925     Diagnose = !L->isResolvedMSAsmLabel();
1926   else
1927     Diagnose = L->getStmt() == nullptr;
1928   if (Diagnose)
1929     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1930 }
1931 
1932 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1933   S->mergeNRVOIntoParent();
1934 
1935   if (S->decl_empty()) return;
1936   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1937          "Scope shouldn't contain decls!");
1938 
1939   for (auto *TmpD : S->decls()) {
1940     assert(TmpD && "This decl didn't get pushed??");
1941 
1942     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1943     NamedDecl *D = cast<NamedDecl>(TmpD);
1944 
1945     // Diagnose unused variables in this scope.
1946     if (!S->hasUnrecoverableErrorOccurred()) {
1947       DiagnoseUnusedDecl(D);
1948       if (const auto *RD = dyn_cast<RecordDecl>(D))
1949         DiagnoseUnusedNestedTypedefs(RD);
1950     }
1951 
1952     if (!D->getDeclName()) continue;
1953 
1954     // If this was a forward reference to a label, verify it was defined.
1955     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1956       CheckPoppedLabel(LD, *this);
1957 
1958     // Remove this name from our lexical scope, and warn on it if we haven't
1959     // already.
1960     IdResolver.RemoveDecl(D);
1961     auto ShadowI = ShadowingDecls.find(D);
1962     if (ShadowI != ShadowingDecls.end()) {
1963       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1964         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1965             << D << FD << FD->getParent();
1966         Diag(FD->getLocation(), diag::note_previous_declaration);
1967       }
1968       ShadowingDecls.erase(ShadowI);
1969     }
1970   }
1971 }
1972 
1973 /// Look for an Objective-C class in the translation unit.
1974 ///
1975 /// \param Id The name of the Objective-C class we're looking for. If
1976 /// typo-correction fixes this name, the Id will be updated
1977 /// to the fixed name.
1978 ///
1979 /// \param IdLoc The location of the name in the translation unit.
1980 ///
1981 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1982 /// if there is no class with the given name.
1983 ///
1984 /// \returns The declaration of the named Objective-C class, or NULL if the
1985 /// class could not be found.
1986 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1987                                               SourceLocation IdLoc,
1988                                               bool DoTypoCorrection) {
1989   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1990   // creation from this context.
1991   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1992 
1993   if (!IDecl && DoTypoCorrection) {
1994     // Perform typo correction at the given location, but only if we
1995     // find an Objective-C class name.
1996     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1997     if (TypoCorrection C =
1998             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1999                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2000       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2001       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2002       Id = IDecl->getIdentifier();
2003     }
2004   }
2005   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2006   // This routine must always return a class definition, if any.
2007   if (Def && Def->getDefinition())
2008       Def = Def->getDefinition();
2009   return Def;
2010 }
2011 
2012 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2013 /// from S, where a non-field would be declared. This routine copes
2014 /// with the difference between C and C++ scoping rules in structs and
2015 /// unions. For example, the following code is well-formed in C but
2016 /// ill-formed in C++:
2017 /// @code
2018 /// struct S6 {
2019 ///   enum { BAR } e;
2020 /// };
2021 ///
2022 /// void test_S6() {
2023 ///   struct S6 a;
2024 ///   a.e = BAR;
2025 /// }
2026 /// @endcode
2027 /// For the declaration of BAR, this routine will return a different
2028 /// scope. The scope S will be the scope of the unnamed enumeration
2029 /// within S6. In C++, this routine will return the scope associated
2030 /// with S6, because the enumeration's scope is a transparent
2031 /// context but structures can contain non-field names. In C, this
2032 /// routine will return the translation unit scope, since the
2033 /// enumeration's scope is a transparent context and structures cannot
2034 /// contain non-field names.
2035 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2036   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2037          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2038          (S->isClassScope() && !getLangOpts().CPlusPlus))
2039     S = S->getParent();
2040   return S;
2041 }
2042 
2043 /// Looks up the declaration of "struct objc_super" and
2044 /// saves it for later use in building builtin declaration of
2045 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2046 /// pre-existing declaration exists no action takes place.
2047 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2048                                         IdentifierInfo *II) {
2049   if (!II->isStr("objc_msgSendSuper"))
2050     return;
2051   ASTContext &Context = ThisSema.Context;
2052 
2053   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2054                       SourceLocation(), Sema::LookupTagName);
2055   ThisSema.LookupName(Result, S);
2056   if (Result.getResultKind() == LookupResult::Found)
2057     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2058       Context.setObjCSuperType(Context.getTagDeclType(TD));
2059 }
2060 
2061 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2062                                ASTContext::GetBuiltinTypeError Error) {
2063   switch (Error) {
2064   case ASTContext::GE_None:
2065     return "";
2066   case ASTContext::GE_Missing_type:
2067     return BuiltinInfo.getHeaderName(ID);
2068   case ASTContext::GE_Missing_stdio:
2069     return "stdio.h";
2070   case ASTContext::GE_Missing_setjmp:
2071     return "setjmp.h";
2072   case ASTContext::GE_Missing_ucontext:
2073     return "ucontext.h";
2074   }
2075   llvm_unreachable("unhandled error kind");
2076 }
2077 
2078 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2079 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2080 /// if we're creating this built-in in anticipation of redeclaring the
2081 /// built-in.
2082 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2083                                      Scope *S, bool ForRedeclaration,
2084                                      SourceLocation Loc) {
2085   LookupPredefedObjCSuperType(*this, S, II);
2086 
2087   ASTContext::GetBuiltinTypeError Error;
2088   QualType R = Context.GetBuiltinType(ID, Error);
2089   if (Error) {
2090     if (!ForRedeclaration)
2091       return nullptr;
2092 
2093     // If we have a builtin without an associated type we should not emit a
2094     // warning when we were not able to find a type for it.
2095     if (Error == ASTContext::GE_Missing_type)
2096       return nullptr;
2097 
2098     // If we could not find a type for setjmp it is because the jmp_buf type was
2099     // not defined prior to the setjmp declaration.
2100     if (Error == ASTContext::GE_Missing_setjmp) {
2101       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2102           << Context.BuiltinInfo.getName(ID);
2103       return nullptr;
2104     }
2105 
2106     // Generally, we emit a warning that the declaration requires the
2107     // appropriate header.
2108     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2109         << getHeaderName(Context.BuiltinInfo, ID, Error)
2110         << Context.BuiltinInfo.getName(ID);
2111     return nullptr;
2112   }
2113 
2114   if (!ForRedeclaration &&
2115       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2116        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2117     Diag(Loc, diag::ext_implicit_lib_function_decl)
2118         << Context.BuiltinInfo.getName(ID) << R;
2119     if (Context.BuiltinInfo.getHeaderName(ID) &&
2120         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2121       Diag(Loc, diag::note_include_header_or_declare)
2122           << Context.BuiltinInfo.getHeaderName(ID)
2123           << Context.BuiltinInfo.getName(ID);
2124   }
2125 
2126   if (R.isNull())
2127     return nullptr;
2128 
2129   DeclContext *Parent = Context.getTranslationUnitDecl();
2130   if (getLangOpts().CPlusPlus) {
2131     LinkageSpecDecl *CLinkageDecl =
2132         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2133                                 LinkageSpecDecl::lang_c, false);
2134     CLinkageDecl->setImplicit();
2135     Parent->addDecl(CLinkageDecl);
2136     Parent = CLinkageDecl;
2137   }
2138 
2139   FunctionDecl *New = FunctionDecl::Create(Context,
2140                                            Parent,
2141                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2142                                            SC_Extern,
2143                                            false,
2144                                            R->isFunctionProtoType());
2145   New->setImplicit();
2146 
2147   // Create Decl objects for each parameter, adding them to the
2148   // FunctionDecl.
2149   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2150     SmallVector<ParmVarDecl*, 16> Params;
2151     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2152       ParmVarDecl *parm =
2153           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2154                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2155                               SC_None, nullptr);
2156       parm->setScopeInfo(0, i);
2157       Params.push_back(parm);
2158     }
2159     New->setParams(Params);
2160   }
2161 
2162   AddKnownFunctionAttributes(New);
2163   RegisterLocallyScopedExternCDecl(New, S);
2164 
2165   // TUScope is the translation-unit scope to insert this function into.
2166   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2167   // relate Scopes to DeclContexts, and probably eliminate CurContext
2168   // entirely, but we're not there yet.
2169   DeclContext *SavedContext = CurContext;
2170   CurContext = Parent;
2171   PushOnScopeChains(New, TUScope);
2172   CurContext = SavedContext;
2173   return New;
2174 }
2175 
2176 /// Typedef declarations don't have linkage, but they still denote the same
2177 /// entity if their types are the same.
2178 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2179 /// isSameEntity.
2180 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2181                                                      TypedefNameDecl *Decl,
2182                                                      LookupResult &Previous) {
2183   // This is only interesting when modules are enabled.
2184   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2185     return;
2186 
2187   // Empty sets are uninteresting.
2188   if (Previous.empty())
2189     return;
2190 
2191   LookupResult::Filter Filter = Previous.makeFilter();
2192   while (Filter.hasNext()) {
2193     NamedDecl *Old = Filter.next();
2194 
2195     // Non-hidden declarations are never ignored.
2196     if (S.isVisible(Old))
2197       continue;
2198 
2199     // Declarations of the same entity are not ignored, even if they have
2200     // different linkages.
2201     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2202       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2203                                 Decl->getUnderlyingType()))
2204         continue;
2205 
2206       // If both declarations give a tag declaration a typedef name for linkage
2207       // purposes, then they declare the same entity.
2208       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2209           Decl->getAnonDeclWithTypedefName())
2210         continue;
2211     }
2212 
2213     Filter.erase();
2214   }
2215 
2216   Filter.done();
2217 }
2218 
2219 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2220   QualType OldType;
2221   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2222     OldType = OldTypedef->getUnderlyingType();
2223   else
2224     OldType = Context.getTypeDeclType(Old);
2225   QualType NewType = New->getUnderlyingType();
2226 
2227   if (NewType->isVariablyModifiedType()) {
2228     // Must not redefine a typedef with a variably-modified type.
2229     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2230     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2231       << Kind << NewType;
2232     if (Old->getLocation().isValid())
2233       notePreviousDefinition(Old, New->getLocation());
2234     New->setInvalidDecl();
2235     return true;
2236   }
2237 
2238   if (OldType != NewType &&
2239       !OldType->isDependentType() &&
2240       !NewType->isDependentType() &&
2241       !Context.hasSameType(OldType, NewType)) {
2242     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2243     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2244       << Kind << NewType << OldType;
2245     if (Old->getLocation().isValid())
2246       notePreviousDefinition(Old, New->getLocation());
2247     New->setInvalidDecl();
2248     return true;
2249   }
2250   return false;
2251 }
2252 
2253 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2254 /// same name and scope as a previous declaration 'Old'.  Figure out
2255 /// how to resolve this situation, merging decls or emitting
2256 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2257 ///
2258 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2259                                 LookupResult &OldDecls) {
2260   // If the new decl is known invalid already, don't bother doing any
2261   // merging checks.
2262   if (New->isInvalidDecl()) return;
2263 
2264   // Allow multiple definitions for ObjC built-in typedefs.
2265   // FIXME: Verify the underlying types are equivalent!
2266   if (getLangOpts().ObjC) {
2267     const IdentifierInfo *TypeID = New->getIdentifier();
2268     switch (TypeID->getLength()) {
2269     default: break;
2270     case 2:
2271       {
2272         if (!TypeID->isStr("id"))
2273           break;
2274         QualType T = New->getUnderlyingType();
2275         if (!T->isPointerType())
2276           break;
2277         if (!T->isVoidPointerType()) {
2278           QualType PT = T->castAs<PointerType>()->getPointeeType();
2279           if (!PT->isStructureType())
2280             break;
2281         }
2282         Context.setObjCIdRedefinitionType(T);
2283         // Install the built-in type for 'id', ignoring the current definition.
2284         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2285         return;
2286       }
2287     case 5:
2288       if (!TypeID->isStr("Class"))
2289         break;
2290       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2291       // Install the built-in type for 'Class', ignoring the current definition.
2292       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2293       return;
2294     case 3:
2295       if (!TypeID->isStr("SEL"))
2296         break;
2297       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2298       // Install the built-in type for 'SEL', ignoring the current definition.
2299       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2300       return;
2301     }
2302     // Fall through - the typedef name was not a builtin type.
2303   }
2304 
2305   // Verify the old decl was also a type.
2306   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2307   if (!Old) {
2308     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2309       << New->getDeclName();
2310 
2311     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2312     if (OldD->getLocation().isValid())
2313       notePreviousDefinition(OldD, New->getLocation());
2314 
2315     return New->setInvalidDecl();
2316   }
2317 
2318   // If the old declaration is invalid, just give up here.
2319   if (Old->isInvalidDecl())
2320     return New->setInvalidDecl();
2321 
2322   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2323     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2324     auto *NewTag = New->getAnonDeclWithTypedefName();
2325     NamedDecl *Hidden = nullptr;
2326     if (OldTag && NewTag &&
2327         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2328         !hasVisibleDefinition(OldTag, &Hidden)) {
2329       // There is a definition of this tag, but it is not visible. Use it
2330       // instead of our tag.
2331       New->setTypeForDecl(OldTD->getTypeForDecl());
2332       if (OldTD->isModed())
2333         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2334                                     OldTD->getUnderlyingType());
2335       else
2336         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2337 
2338       // Make the old tag definition visible.
2339       makeMergedDefinitionVisible(Hidden);
2340 
2341       // If this was an unscoped enumeration, yank all of its enumerators
2342       // out of the scope.
2343       if (isa<EnumDecl>(NewTag)) {
2344         Scope *EnumScope = getNonFieldDeclScope(S);
2345         for (auto *D : NewTag->decls()) {
2346           auto *ED = cast<EnumConstantDecl>(D);
2347           assert(EnumScope->isDeclScope(ED));
2348           EnumScope->RemoveDecl(ED);
2349           IdResolver.RemoveDecl(ED);
2350           ED->getLexicalDeclContext()->removeDecl(ED);
2351         }
2352       }
2353     }
2354   }
2355 
2356   // If the typedef types are not identical, reject them in all languages and
2357   // with any extensions enabled.
2358   if (isIncompatibleTypedef(Old, New))
2359     return;
2360 
2361   // The types match.  Link up the redeclaration chain and merge attributes if
2362   // the old declaration was a typedef.
2363   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2364     New->setPreviousDecl(Typedef);
2365     mergeDeclAttributes(New, Old);
2366   }
2367 
2368   if (getLangOpts().MicrosoftExt)
2369     return;
2370 
2371   if (getLangOpts().CPlusPlus) {
2372     // C++ [dcl.typedef]p2:
2373     //   In a given non-class scope, a typedef specifier can be used to
2374     //   redefine the name of any type declared in that scope to refer
2375     //   to the type to which it already refers.
2376     if (!isa<CXXRecordDecl>(CurContext))
2377       return;
2378 
2379     // C++0x [dcl.typedef]p4:
2380     //   In a given class scope, a typedef specifier can be used to redefine
2381     //   any class-name declared in that scope that is not also a typedef-name
2382     //   to refer to the type to which it already refers.
2383     //
2384     // This wording came in via DR424, which was a correction to the
2385     // wording in DR56, which accidentally banned code like:
2386     //
2387     //   struct S {
2388     //     typedef struct A { } A;
2389     //   };
2390     //
2391     // in the C++03 standard. We implement the C++0x semantics, which
2392     // allow the above but disallow
2393     //
2394     //   struct S {
2395     //     typedef int I;
2396     //     typedef int I;
2397     //   };
2398     //
2399     // since that was the intent of DR56.
2400     if (!isa<TypedefNameDecl>(Old))
2401       return;
2402 
2403     Diag(New->getLocation(), diag::err_redefinition)
2404       << New->getDeclName();
2405     notePreviousDefinition(Old, New->getLocation());
2406     return New->setInvalidDecl();
2407   }
2408 
2409   // Modules always permit redefinition of typedefs, as does C11.
2410   if (getLangOpts().Modules || getLangOpts().C11)
2411     return;
2412 
2413   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2414   // is normally mapped to an error, but can be controlled with
2415   // -Wtypedef-redefinition.  If either the original or the redefinition is
2416   // in a system header, don't emit this for compatibility with GCC.
2417   if (getDiagnostics().getSuppressSystemWarnings() &&
2418       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2419       (Old->isImplicit() ||
2420        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2421        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2422     return;
2423 
2424   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2425     << New->getDeclName();
2426   notePreviousDefinition(Old, New->getLocation());
2427 }
2428 
2429 /// DeclhasAttr - returns true if decl Declaration already has the target
2430 /// attribute.
2431 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2432   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2433   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2434   for (const auto *i : D->attrs())
2435     if (i->getKind() == A->getKind()) {
2436       if (Ann) {
2437         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2438           return true;
2439         continue;
2440       }
2441       // FIXME: Don't hardcode this check
2442       if (OA && isa<OwnershipAttr>(i))
2443         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2444       return true;
2445     }
2446 
2447   return false;
2448 }
2449 
2450 static bool isAttributeTargetADefinition(Decl *D) {
2451   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2452     return VD->isThisDeclarationADefinition();
2453   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2454     return TD->isCompleteDefinition() || TD->isBeingDefined();
2455   return true;
2456 }
2457 
2458 /// Merge alignment attributes from \p Old to \p New, taking into account the
2459 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2460 ///
2461 /// \return \c true if any attributes were added to \p New.
2462 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2463   // Look for alignas attributes on Old, and pick out whichever attribute
2464   // specifies the strictest alignment requirement.
2465   AlignedAttr *OldAlignasAttr = nullptr;
2466   AlignedAttr *OldStrictestAlignAttr = nullptr;
2467   unsigned OldAlign = 0;
2468   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2469     // FIXME: We have no way of representing inherited dependent alignments
2470     // in a case like:
2471     //   template<int A, int B> struct alignas(A) X;
2472     //   template<int A, int B> struct alignas(B) X {};
2473     // For now, we just ignore any alignas attributes which are not on the
2474     // definition in such a case.
2475     if (I->isAlignmentDependent())
2476       return false;
2477 
2478     if (I->isAlignas())
2479       OldAlignasAttr = I;
2480 
2481     unsigned Align = I->getAlignment(S.Context);
2482     if (Align > OldAlign) {
2483       OldAlign = Align;
2484       OldStrictestAlignAttr = I;
2485     }
2486   }
2487 
2488   // Look for alignas attributes on New.
2489   AlignedAttr *NewAlignasAttr = nullptr;
2490   unsigned NewAlign = 0;
2491   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2492     if (I->isAlignmentDependent())
2493       return false;
2494 
2495     if (I->isAlignas())
2496       NewAlignasAttr = I;
2497 
2498     unsigned Align = I->getAlignment(S.Context);
2499     if (Align > NewAlign)
2500       NewAlign = Align;
2501   }
2502 
2503   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2504     // Both declarations have 'alignas' attributes. We require them to match.
2505     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2506     // fall short. (If two declarations both have alignas, they must both match
2507     // every definition, and so must match each other if there is a definition.)
2508 
2509     // If either declaration only contains 'alignas(0)' specifiers, then it
2510     // specifies the natural alignment for the type.
2511     if (OldAlign == 0 || NewAlign == 0) {
2512       QualType Ty;
2513       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2514         Ty = VD->getType();
2515       else
2516         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2517 
2518       if (OldAlign == 0)
2519         OldAlign = S.Context.getTypeAlign(Ty);
2520       if (NewAlign == 0)
2521         NewAlign = S.Context.getTypeAlign(Ty);
2522     }
2523 
2524     if (OldAlign != NewAlign) {
2525       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2526         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2527         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2528       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2529     }
2530   }
2531 
2532   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2533     // C++11 [dcl.align]p6:
2534     //   if any declaration of an entity has an alignment-specifier,
2535     //   every defining declaration of that entity shall specify an
2536     //   equivalent alignment.
2537     // C11 6.7.5/7:
2538     //   If the definition of an object does not have an alignment
2539     //   specifier, any other declaration of that object shall also
2540     //   have no alignment specifier.
2541     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2542       << OldAlignasAttr;
2543     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2544       << OldAlignasAttr;
2545   }
2546 
2547   bool AnyAdded = false;
2548 
2549   // Ensure we have an attribute representing the strictest alignment.
2550   if (OldAlign > NewAlign) {
2551     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2552     Clone->setInherited(true);
2553     New->addAttr(Clone);
2554     AnyAdded = true;
2555   }
2556 
2557   // Ensure we have an alignas attribute if the old declaration had one.
2558   if (OldAlignasAttr && !NewAlignasAttr &&
2559       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2560     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2561     Clone->setInherited(true);
2562     New->addAttr(Clone);
2563     AnyAdded = true;
2564   }
2565 
2566   return AnyAdded;
2567 }
2568 
2569 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2570                                const InheritableAttr *Attr,
2571                                Sema::AvailabilityMergeKind AMK) {
2572   // This function copies an attribute Attr from a previous declaration to the
2573   // new declaration D if the new declaration doesn't itself have that attribute
2574   // yet or if that attribute allows duplicates.
2575   // If you're adding a new attribute that requires logic different from
2576   // "use explicit attribute on decl if present, else use attribute from
2577   // previous decl", for example if the attribute needs to be consistent
2578   // between redeclarations, you need to call a custom merge function here.
2579   InheritableAttr *NewAttr = nullptr;
2580   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2581     NewAttr = S.mergeAvailabilityAttr(
2582         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2583         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2584         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2585         AA->getPriority());
2586   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2587     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2588   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2589     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2590   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2591     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2592   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2593     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2594   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2595     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2596                                 FA->getFirstArg());
2597   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2598     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2599   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2600     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2601   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2602     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2603                                        IA->getInheritanceModel());
2604   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2605     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2606                                       &S.Context.Idents.get(AA->getSpelling()));
2607   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2608            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2609             isa<CUDAGlobalAttr>(Attr))) {
2610     // CUDA target attributes are part of function signature for
2611     // overloading purposes and must not be merged.
2612     return false;
2613   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2614     NewAttr = S.mergeMinSizeAttr(D, *MA);
2615   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2616     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2617   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2618     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2619   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2620     NewAttr = S.mergeCommonAttr(D, *CommonA);
2621   else if (isa<AlignedAttr>(Attr))
2622     // AlignedAttrs are handled separately, because we need to handle all
2623     // such attributes on a declaration at the same time.
2624     NewAttr = nullptr;
2625   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2626            (AMK == Sema::AMK_Override ||
2627             AMK == Sema::AMK_ProtocolImplementation))
2628     NewAttr = nullptr;
2629   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2630     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2631   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2632     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2633   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2634     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2635   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2636     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2637   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2638     NewAttr = S.mergeImportNameAttr(D, *INA);
2639   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2640     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2641 
2642   if (NewAttr) {
2643     NewAttr->setInherited(true);
2644     D->addAttr(NewAttr);
2645     if (isa<MSInheritanceAttr>(NewAttr))
2646       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2647     return true;
2648   }
2649 
2650   return false;
2651 }
2652 
2653 static const NamedDecl *getDefinition(const Decl *D) {
2654   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2655     return TD->getDefinition();
2656   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2657     const VarDecl *Def = VD->getDefinition();
2658     if (Def)
2659       return Def;
2660     return VD->getActingDefinition();
2661   }
2662   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2663     return FD->getDefinition();
2664   return nullptr;
2665 }
2666 
2667 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2668   for (const auto *Attribute : D->attrs())
2669     if (Attribute->getKind() == Kind)
2670       return true;
2671   return false;
2672 }
2673 
2674 /// checkNewAttributesAfterDef - If we already have a definition, check that
2675 /// there are no new attributes in this declaration.
2676 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2677   if (!New->hasAttrs())
2678     return;
2679 
2680   const NamedDecl *Def = getDefinition(Old);
2681   if (!Def || Def == New)
2682     return;
2683 
2684   AttrVec &NewAttributes = New->getAttrs();
2685   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2686     const Attr *NewAttribute = NewAttributes[I];
2687 
2688     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2689       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2690         Sema::SkipBodyInfo SkipBody;
2691         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2692 
2693         // If we're skipping this definition, drop the "alias" attribute.
2694         if (SkipBody.ShouldSkip) {
2695           NewAttributes.erase(NewAttributes.begin() + I);
2696           --E;
2697           continue;
2698         }
2699       } else {
2700         VarDecl *VD = cast<VarDecl>(New);
2701         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2702                                 VarDecl::TentativeDefinition
2703                             ? diag::err_alias_after_tentative
2704                             : diag::err_redefinition;
2705         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2706         if (Diag == diag::err_redefinition)
2707           S.notePreviousDefinition(Def, VD->getLocation());
2708         else
2709           S.Diag(Def->getLocation(), diag::note_previous_definition);
2710         VD->setInvalidDecl();
2711       }
2712       ++I;
2713       continue;
2714     }
2715 
2716     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2717       // Tentative definitions are only interesting for the alias check above.
2718       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2719         ++I;
2720         continue;
2721       }
2722     }
2723 
2724     if (hasAttribute(Def, NewAttribute->getKind())) {
2725       ++I;
2726       continue; // regular attr merging will take care of validating this.
2727     }
2728 
2729     if (isa<C11NoReturnAttr>(NewAttribute)) {
2730       // C's _Noreturn is allowed to be added to a function after it is defined.
2731       ++I;
2732       continue;
2733     } else if (isa<UuidAttr>(NewAttribute)) {
2734       // msvc will allow a subsequent definition to add an uuid to a class
2735       ++I;
2736       continue;
2737     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2738       if (AA->isAlignas()) {
2739         // C++11 [dcl.align]p6:
2740         //   if any declaration of an entity has an alignment-specifier,
2741         //   every defining declaration of that entity shall specify an
2742         //   equivalent alignment.
2743         // C11 6.7.5/7:
2744         //   If the definition of an object does not have an alignment
2745         //   specifier, any other declaration of that object shall also
2746         //   have no alignment specifier.
2747         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2748           << AA;
2749         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2750           << AA;
2751         NewAttributes.erase(NewAttributes.begin() + I);
2752         --E;
2753         continue;
2754       }
2755     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2756       // If there is a C definition followed by a redeclaration with this
2757       // attribute then there are two different definitions. In C++, prefer the
2758       // standard diagnostics.
2759       if (!S.getLangOpts().CPlusPlus) {
2760         S.Diag(NewAttribute->getLocation(),
2761                diag::err_loader_uninitialized_redeclaration);
2762         S.Diag(Def->getLocation(), diag::note_previous_definition);
2763         NewAttributes.erase(NewAttributes.begin() + I);
2764         --E;
2765         continue;
2766       }
2767     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2768                cast<VarDecl>(New)->isInline() &&
2769                !cast<VarDecl>(New)->isInlineSpecified()) {
2770       // Don't warn about applying selectany to implicitly inline variables.
2771       // Older compilers and language modes would require the use of selectany
2772       // to make such variables inline, and it would have no effect if we
2773       // honored it.
2774       ++I;
2775       continue;
2776     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2777       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2778       // declarations after defintions.
2779       ++I;
2780       continue;
2781     }
2782 
2783     S.Diag(NewAttribute->getLocation(),
2784            diag::warn_attribute_precede_definition);
2785     S.Diag(Def->getLocation(), diag::note_previous_definition);
2786     NewAttributes.erase(NewAttributes.begin() + I);
2787     --E;
2788   }
2789 }
2790 
2791 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2792                                      const ConstInitAttr *CIAttr,
2793                                      bool AttrBeforeInit) {
2794   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2795 
2796   // Figure out a good way to write this specifier on the old declaration.
2797   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2798   // enough of the attribute list spelling information to extract that without
2799   // heroics.
2800   std::string SuitableSpelling;
2801   if (S.getLangOpts().CPlusPlus20)
2802     SuitableSpelling = std::string(
2803         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2804   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2805     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2806         InsertLoc, {tok::l_square, tok::l_square,
2807                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2808                     S.PP.getIdentifierInfo("require_constant_initialization"),
2809                     tok::r_square, tok::r_square}));
2810   if (SuitableSpelling.empty())
2811     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2812         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2813                     S.PP.getIdentifierInfo("require_constant_initialization"),
2814                     tok::r_paren, tok::r_paren}));
2815   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2816     SuitableSpelling = "constinit";
2817   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2818     SuitableSpelling = "[[clang::require_constant_initialization]]";
2819   if (SuitableSpelling.empty())
2820     SuitableSpelling = "__attribute__((require_constant_initialization))";
2821   SuitableSpelling += " ";
2822 
2823   if (AttrBeforeInit) {
2824     // extern constinit int a;
2825     // int a = 0; // error (missing 'constinit'), accepted as extension
2826     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2827     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2828         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2829     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2830   } else {
2831     // int a = 0;
2832     // constinit extern int a; // error (missing 'constinit')
2833     S.Diag(CIAttr->getLocation(),
2834            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2835                                  : diag::warn_require_const_init_added_too_late)
2836         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2837     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2838         << CIAttr->isConstinit()
2839         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2840   }
2841 }
2842 
2843 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2844 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2845                                AvailabilityMergeKind AMK) {
2846   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2847     UsedAttr *NewAttr = OldAttr->clone(Context);
2848     NewAttr->setInherited(true);
2849     New->addAttr(NewAttr);
2850   }
2851 
2852   if (!Old->hasAttrs() && !New->hasAttrs())
2853     return;
2854 
2855   // [dcl.constinit]p1:
2856   //   If the [constinit] specifier is applied to any declaration of a
2857   //   variable, it shall be applied to the initializing declaration.
2858   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2859   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2860   if (bool(OldConstInit) != bool(NewConstInit)) {
2861     const auto *OldVD = cast<VarDecl>(Old);
2862     auto *NewVD = cast<VarDecl>(New);
2863 
2864     // Find the initializing declaration. Note that we might not have linked
2865     // the new declaration into the redeclaration chain yet.
2866     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2867     if (!InitDecl &&
2868         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2869       InitDecl = NewVD;
2870 
2871     if (InitDecl == NewVD) {
2872       // This is the initializing declaration. If it would inherit 'constinit',
2873       // that's ill-formed. (Note that we do not apply this to the attribute
2874       // form).
2875       if (OldConstInit && OldConstInit->isConstinit())
2876         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2877                                  /*AttrBeforeInit=*/true);
2878     } else if (NewConstInit) {
2879       // This is the first time we've been told that this declaration should
2880       // have a constant initializer. If we already saw the initializing
2881       // declaration, this is too late.
2882       if (InitDecl && InitDecl != NewVD) {
2883         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2884                                  /*AttrBeforeInit=*/false);
2885         NewVD->dropAttr<ConstInitAttr>();
2886       }
2887     }
2888   }
2889 
2890   // Attributes declared post-definition are currently ignored.
2891   checkNewAttributesAfterDef(*this, New, Old);
2892 
2893   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2894     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2895       if (!OldA->isEquivalent(NewA)) {
2896         // This redeclaration changes __asm__ label.
2897         Diag(New->getLocation(), diag::err_different_asm_label);
2898         Diag(OldA->getLocation(), diag::note_previous_declaration);
2899       }
2900     } else if (Old->isUsed()) {
2901       // This redeclaration adds an __asm__ label to a declaration that has
2902       // already been ODR-used.
2903       Diag(New->getLocation(), diag::err_late_asm_label_name)
2904         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2905     }
2906   }
2907 
2908   // Re-declaration cannot add abi_tag's.
2909   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2910     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2911       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2912         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2913                       NewTag) == OldAbiTagAttr->tags_end()) {
2914           Diag(NewAbiTagAttr->getLocation(),
2915                diag::err_new_abi_tag_on_redeclaration)
2916               << NewTag;
2917           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2918         }
2919       }
2920     } else {
2921       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2922       Diag(Old->getLocation(), diag::note_previous_declaration);
2923     }
2924   }
2925 
2926   // This redeclaration adds a section attribute.
2927   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2928     if (auto *VD = dyn_cast<VarDecl>(New)) {
2929       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2930         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2931         Diag(Old->getLocation(), diag::note_previous_declaration);
2932       }
2933     }
2934   }
2935 
2936   // Redeclaration adds code-seg attribute.
2937   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2938   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2939       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2940     Diag(New->getLocation(), diag::warn_mismatched_section)
2941          << 0 /*codeseg*/;
2942     Diag(Old->getLocation(), diag::note_previous_declaration);
2943   }
2944 
2945   if (!Old->hasAttrs())
2946     return;
2947 
2948   bool foundAny = New->hasAttrs();
2949 
2950   // Ensure that any moving of objects within the allocated map is done before
2951   // we process them.
2952   if (!foundAny) New->setAttrs(AttrVec());
2953 
2954   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2955     // Ignore deprecated/unavailable/availability attributes if requested.
2956     AvailabilityMergeKind LocalAMK = AMK_None;
2957     if (isa<DeprecatedAttr>(I) ||
2958         isa<UnavailableAttr>(I) ||
2959         isa<AvailabilityAttr>(I)) {
2960       switch (AMK) {
2961       case AMK_None:
2962         continue;
2963 
2964       case AMK_Redeclaration:
2965       case AMK_Override:
2966       case AMK_ProtocolImplementation:
2967         LocalAMK = AMK;
2968         break;
2969       }
2970     }
2971 
2972     // Already handled.
2973     if (isa<UsedAttr>(I))
2974       continue;
2975 
2976     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2977       foundAny = true;
2978   }
2979 
2980   if (mergeAlignedAttrs(*this, New, Old))
2981     foundAny = true;
2982 
2983   if (!foundAny) New->dropAttrs();
2984 }
2985 
2986 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2987 /// to the new one.
2988 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2989                                      const ParmVarDecl *oldDecl,
2990                                      Sema &S) {
2991   // C++11 [dcl.attr.depend]p2:
2992   //   The first declaration of a function shall specify the
2993   //   carries_dependency attribute for its declarator-id if any declaration
2994   //   of the function specifies the carries_dependency attribute.
2995   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2996   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2997     S.Diag(CDA->getLocation(),
2998            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2999     // Find the first declaration of the parameter.
3000     // FIXME: Should we build redeclaration chains for function parameters?
3001     const FunctionDecl *FirstFD =
3002       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3003     const ParmVarDecl *FirstVD =
3004       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3005     S.Diag(FirstVD->getLocation(),
3006            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3007   }
3008 
3009   if (!oldDecl->hasAttrs())
3010     return;
3011 
3012   bool foundAny = newDecl->hasAttrs();
3013 
3014   // Ensure that any moving of objects within the allocated map is
3015   // done before we process them.
3016   if (!foundAny) newDecl->setAttrs(AttrVec());
3017 
3018   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3019     if (!DeclHasAttr(newDecl, I)) {
3020       InheritableAttr *newAttr =
3021         cast<InheritableParamAttr>(I->clone(S.Context));
3022       newAttr->setInherited(true);
3023       newDecl->addAttr(newAttr);
3024       foundAny = true;
3025     }
3026   }
3027 
3028   if (!foundAny) newDecl->dropAttrs();
3029 }
3030 
3031 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3032                                 const ParmVarDecl *OldParam,
3033                                 Sema &S) {
3034   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3035     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3036       if (*Oldnullability != *Newnullability) {
3037         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3038           << DiagNullabilityKind(
3039                *Newnullability,
3040                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3041                 != 0))
3042           << DiagNullabilityKind(
3043                *Oldnullability,
3044                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3045                 != 0));
3046         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3047       }
3048     } else {
3049       QualType NewT = NewParam->getType();
3050       NewT = S.Context.getAttributedType(
3051                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3052                          NewT, NewT);
3053       NewParam->setType(NewT);
3054     }
3055   }
3056 }
3057 
3058 namespace {
3059 
3060 /// Used in MergeFunctionDecl to keep track of function parameters in
3061 /// C.
3062 struct GNUCompatibleParamWarning {
3063   ParmVarDecl *OldParm;
3064   ParmVarDecl *NewParm;
3065   QualType PromotedType;
3066 };
3067 
3068 } // end anonymous namespace
3069 
3070 // Determine whether the previous declaration was a definition, implicit
3071 // declaration, or a declaration.
3072 template <typename T>
3073 static std::pair<diag::kind, SourceLocation>
3074 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3075   diag::kind PrevDiag;
3076   SourceLocation OldLocation = Old->getLocation();
3077   if (Old->isThisDeclarationADefinition())
3078     PrevDiag = diag::note_previous_definition;
3079   else if (Old->isImplicit()) {
3080     PrevDiag = diag::note_previous_implicit_declaration;
3081     if (OldLocation.isInvalid())
3082       OldLocation = New->getLocation();
3083   } else
3084     PrevDiag = diag::note_previous_declaration;
3085   return std::make_pair(PrevDiag, OldLocation);
3086 }
3087 
3088 /// canRedefineFunction - checks if a function can be redefined. Currently,
3089 /// only extern inline functions can be redefined, and even then only in
3090 /// GNU89 mode.
3091 static bool canRedefineFunction(const FunctionDecl *FD,
3092                                 const LangOptions& LangOpts) {
3093   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3094           !LangOpts.CPlusPlus &&
3095           FD->isInlineSpecified() &&
3096           FD->getStorageClass() == SC_Extern);
3097 }
3098 
3099 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3100   const AttributedType *AT = T->getAs<AttributedType>();
3101   while (AT && !AT->isCallingConv())
3102     AT = AT->getModifiedType()->getAs<AttributedType>();
3103   return AT;
3104 }
3105 
3106 template <typename T>
3107 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3108   const DeclContext *DC = Old->getDeclContext();
3109   if (DC->isRecord())
3110     return false;
3111 
3112   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3113   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3114     return true;
3115   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3116     return true;
3117   return false;
3118 }
3119 
3120 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3121 static bool isExternC(VarTemplateDecl *) { return false; }
3122 
3123 /// Check whether a redeclaration of an entity introduced by a
3124 /// using-declaration is valid, given that we know it's not an overload
3125 /// (nor a hidden tag declaration).
3126 template<typename ExpectedDecl>
3127 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3128                                    ExpectedDecl *New) {
3129   // C++11 [basic.scope.declarative]p4:
3130   //   Given a set of declarations in a single declarative region, each of
3131   //   which specifies the same unqualified name,
3132   //   -- they shall all refer to the same entity, or all refer to functions
3133   //      and function templates; or
3134   //   -- exactly one declaration shall declare a class name or enumeration
3135   //      name that is not a typedef name and the other declarations shall all
3136   //      refer to the same variable or enumerator, or all refer to functions
3137   //      and function templates; in this case the class name or enumeration
3138   //      name is hidden (3.3.10).
3139 
3140   // C++11 [namespace.udecl]p14:
3141   //   If a function declaration in namespace scope or block scope has the
3142   //   same name and the same parameter-type-list as a function introduced
3143   //   by a using-declaration, and the declarations do not declare the same
3144   //   function, the program is ill-formed.
3145 
3146   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3147   if (Old &&
3148       !Old->getDeclContext()->getRedeclContext()->Equals(
3149           New->getDeclContext()->getRedeclContext()) &&
3150       !(isExternC(Old) && isExternC(New)))
3151     Old = nullptr;
3152 
3153   if (!Old) {
3154     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3155     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3156     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3157     return true;
3158   }
3159   return false;
3160 }
3161 
3162 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3163                                             const FunctionDecl *B) {
3164   assert(A->getNumParams() == B->getNumParams());
3165 
3166   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3167     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3168     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3169     if (AttrA == AttrB)
3170       return true;
3171     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3172            AttrA->isDynamic() == AttrB->isDynamic();
3173   };
3174 
3175   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3176 }
3177 
3178 /// If necessary, adjust the semantic declaration context for a qualified
3179 /// declaration to name the correct inline namespace within the qualifier.
3180 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3181                                                DeclaratorDecl *OldD) {
3182   // The only case where we need to update the DeclContext is when
3183   // redeclaration lookup for a qualified name finds a declaration
3184   // in an inline namespace within the context named by the qualifier:
3185   //
3186   //   inline namespace N { int f(); }
3187   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3188   //
3189   // For unqualified declarations, the semantic context *can* change
3190   // along the redeclaration chain (for local extern declarations,
3191   // extern "C" declarations, and friend declarations in particular).
3192   if (!NewD->getQualifier())
3193     return;
3194 
3195   // NewD is probably already in the right context.
3196   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3197   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3198   if (NamedDC->Equals(SemaDC))
3199     return;
3200 
3201   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3202           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3203          "unexpected context for redeclaration");
3204 
3205   auto *LexDC = NewD->getLexicalDeclContext();
3206   auto FixSemaDC = [=](NamedDecl *D) {
3207     if (!D)
3208       return;
3209     D->setDeclContext(SemaDC);
3210     D->setLexicalDeclContext(LexDC);
3211   };
3212 
3213   FixSemaDC(NewD);
3214   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3215     FixSemaDC(FD->getDescribedFunctionTemplate());
3216   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3217     FixSemaDC(VD->getDescribedVarTemplate());
3218 }
3219 
3220 /// MergeFunctionDecl - We just parsed a function 'New' from
3221 /// declarator D which has the same name and scope as a previous
3222 /// declaration 'Old'.  Figure out how to resolve this situation,
3223 /// merging decls or emitting diagnostics as appropriate.
3224 ///
3225 /// In C++, New and Old must be declarations that are not
3226 /// overloaded. Use IsOverload to determine whether New and Old are
3227 /// overloaded, and to select the Old declaration that New should be
3228 /// merged with.
3229 ///
3230 /// Returns true if there was an error, false otherwise.
3231 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3232                              Scope *S, bool MergeTypeWithOld) {
3233   // Verify the old decl was also a function.
3234   FunctionDecl *Old = OldD->getAsFunction();
3235   if (!Old) {
3236     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3237       if (New->getFriendObjectKind()) {
3238         Diag(New->getLocation(), diag::err_using_decl_friend);
3239         Diag(Shadow->getTargetDecl()->getLocation(),
3240              diag::note_using_decl_target);
3241         Diag(Shadow->getUsingDecl()->getLocation(),
3242              diag::note_using_decl) << 0;
3243         return true;
3244       }
3245 
3246       // Check whether the two declarations might declare the same function.
3247       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3248         return true;
3249       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3250     } else {
3251       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3252         << New->getDeclName();
3253       notePreviousDefinition(OldD, New->getLocation());
3254       return true;
3255     }
3256   }
3257 
3258   // If the old declaration is invalid, just give up here.
3259   if (Old->isInvalidDecl())
3260     return true;
3261 
3262   // Disallow redeclaration of some builtins.
3263   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3264     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3265     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3266         << Old << Old->getType();
3267     return true;
3268   }
3269 
3270   diag::kind PrevDiag;
3271   SourceLocation OldLocation;
3272   std::tie(PrevDiag, OldLocation) =
3273       getNoteDiagForInvalidRedeclaration(Old, New);
3274 
3275   // Don't complain about this if we're in GNU89 mode and the old function
3276   // is an extern inline function.
3277   // Don't complain about specializations. They are not supposed to have
3278   // storage classes.
3279   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3280       New->getStorageClass() == SC_Static &&
3281       Old->hasExternalFormalLinkage() &&
3282       !New->getTemplateSpecializationInfo() &&
3283       !canRedefineFunction(Old, getLangOpts())) {
3284     if (getLangOpts().MicrosoftExt) {
3285       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3286       Diag(OldLocation, PrevDiag);
3287     } else {
3288       Diag(New->getLocation(), diag::err_static_non_static) << New;
3289       Diag(OldLocation, PrevDiag);
3290       return true;
3291     }
3292   }
3293 
3294   if (New->hasAttr<InternalLinkageAttr>() &&
3295       !Old->hasAttr<InternalLinkageAttr>()) {
3296     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3297         << New->getDeclName();
3298     notePreviousDefinition(Old, New->getLocation());
3299     New->dropAttr<InternalLinkageAttr>();
3300   }
3301 
3302   if (CheckRedeclarationModuleOwnership(New, Old))
3303     return true;
3304 
3305   if (!getLangOpts().CPlusPlus) {
3306     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3307     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3308       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3309         << New << OldOvl;
3310 
3311       // Try our best to find a decl that actually has the overloadable
3312       // attribute for the note. In most cases (e.g. programs with only one
3313       // broken declaration/definition), this won't matter.
3314       //
3315       // FIXME: We could do this if we juggled some extra state in
3316       // OverloadableAttr, rather than just removing it.
3317       const Decl *DiagOld = Old;
3318       if (OldOvl) {
3319         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3320           const auto *A = D->getAttr<OverloadableAttr>();
3321           return A && !A->isImplicit();
3322         });
3323         // If we've implicitly added *all* of the overloadable attrs to this
3324         // chain, emitting a "previous redecl" note is pointless.
3325         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3326       }
3327 
3328       if (DiagOld)
3329         Diag(DiagOld->getLocation(),
3330              diag::note_attribute_overloadable_prev_overload)
3331           << OldOvl;
3332 
3333       if (OldOvl)
3334         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3335       else
3336         New->dropAttr<OverloadableAttr>();
3337     }
3338   }
3339 
3340   // If a function is first declared with a calling convention, but is later
3341   // declared or defined without one, all following decls assume the calling
3342   // convention of the first.
3343   //
3344   // It's OK if a function is first declared without a calling convention,
3345   // but is later declared or defined with the default calling convention.
3346   //
3347   // To test if either decl has an explicit calling convention, we look for
3348   // AttributedType sugar nodes on the type as written.  If they are missing or
3349   // were canonicalized away, we assume the calling convention was implicit.
3350   //
3351   // Note also that we DO NOT return at this point, because we still have
3352   // other tests to run.
3353   QualType OldQType = Context.getCanonicalType(Old->getType());
3354   QualType NewQType = Context.getCanonicalType(New->getType());
3355   const FunctionType *OldType = cast<FunctionType>(OldQType);
3356   const FunctionType *NewType = cast<FunctionType>(NewQType);
3357   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3358   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3359   bool RequiresAdjustment = false;
3360 
3361   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3362     FunctionDecl *First = Old->getFirstDecl();
3363     const FunctionType *FT =
3364         First->getType().getCanonicalType()->castAs<FunctionType>();
3365     FunctionType::ExtInfo FI = FT->getExtInfo();
3366     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3367     if (!NewCCExplicit) {
3368       // Inherit the CC from the previous declaration if it was specified
3369       // there but not here.
3370       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3371       RequiresAdjustment = true;
3372     } else if (New->getBuiltinID()) {
3373       // Calling Conventions on a Builtin aren't really useful and setting a
3374       // default calling convention and cdecl'ing some builtin redeclarations is
3375       // common, so warn and ignore the calling convention on the redeclaration.
3376       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3377           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3378           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3379       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3380       RequiresAdjustment = true;
3381     } else {
3382       // Calling conventions aren't compatible, so complain.
3383       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3384       Diag(New->getLocation(), diag::err_cconv_change)
3385         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3386         << !FirstCCExplicit
3387         << (!FirstCCExplicit ? "" :
3388             FunctionType::getNameForCallConv(FI.getCC()));
3389 
3390       // Put the note on the first decl, since it is the one that matters.
3391       Diag(First->getLocation(), diag::note_previous_declaration);
3392       return true;
3393     }
3394   }
3395 
3396   // FIXME: diagnose the other way around?
3397   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3398     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3399     RequiresAdjustment = true;
3400   }
3401 
3402   // Merge regparm attribute.
3403   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3404       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3405     if (NewTypeInfo.getHasRegParm()) {
3406       Diag(New->getLocation(), diag::err_regparm_mismatch)
3407         << NewType->getRegParmType()
3408         << OldType->getRegParmType();
3409       Diag(OldLocation, diag::note_previous_declaration);
3410       return true;
3411     }
3412 
3413     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3414     RequiresAdjustment = true;
3415   }
3416 
3417   // Merge ns_returns_retained attribute.
3418   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3419     if (NewTypeInfo.getProducesResult()) {
3420       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3421           << "'ns_returns_retained'";
3422       Diag(OldLocation, diag::note_previous_declaration);
3423       return true;
3424     }
3425 
3426     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3427     RequiresAdjustment = true;
3428   }
3429 
3430   if (OldTypeInfo.getNoCallerSavedRegs() !=
3431       NewTypeInfo.getNoCallerSavedRegs()) {
3432     if (NewTypeInfo.getNoCallerSavedRegs()) {
3433       AnyX86NoCallerSavedRegistersAttr *Attr =
3434         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3435       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3436       Diag(OldLocation, diag::note_previous_declaration);
3437       return true;
3438     }
3439 
3440     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3441     RequiresAdjustment = true;
3442   }
3443 
3444   if (RequiresAdjustment) {
3445     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3446     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3447     New->setType(QualType(AdjustedType, 0));
3448     NewQType = Context.getCanonicalType(New->getType());
3449   }
3450 
3451   // If this redeclaration makes the function inline, we may need to add it to
3452   // UndefinedButUsed.
3453   if (!Old->isInlined() && New->isInlined() &&
3454       !New->hasAttr<GNUInlineAttr>() &&
3455       !getLangOpts().GNUInline &&
3456       Old->isUsed(false) &&
3457       !Old->isDefined() && !New->isThisDeclarationADefinition())
3458     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3459                                            SourceLocation()));
3460 
3461   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3462   // about it.
3463   if (New->hasAttr<GNUInlineAttr>() &&
3464       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3465     UndefinedButUsed.erase(Old->getCanonicalDecl());
3466   }
3467 
3468   // If pass_object_size params don't match up perfectly, this isn't a valid
3469   // redeclaration.
3470   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3471       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3472     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3473         << New->getDeclName();
3474     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3475     return true;
3476   }
3477 
3478   if (getLangOpts().CPlusPlus) {
3479     // C++1z [over.load]p2
3480     //   Certain function declarations cannot be overloaded:
3481     //     -- Function declarations that differ only in the return type,
3482     //        the exception specification, or both cannot be overloaded.
3483 
3484     // Check the exception specifications match. This may recompute the type of
3485     // both Old and New if it resolved exception specifications, so grab the
3486     // types again after this. Because this updates the type, we do this before
3487     // any of the other checks below, which may update the "de facto" NewQType
3488     // but do not necessarily update the type of New.
3489     if (CheckEquivalentExceptionSpec(Old, New))
3490       return true;
3491     OldQType = Context.getCanonicalType(Old->getType());
3492     NewQType = Context.getCanonicalType(New->getType());
3493 
3494     // Go back to the type source info to compare the declared return types,
3495     // per C++1y [dcl.type.auto]p13:
3496     //   Redeclarations or specializations of a function or function template
3497     //   with a declared return type that uses a placeholder type shall also
3498     //   use that placeholder, not a deduced type.
3499     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3500     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3501     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3502         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3503                                        OldDeclaredReturnType)) {
3504       QualType ResQT;
3505       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3506           OldDeclaredReturnType->isObjCObjectPointerType())
3507         // FIXME: This does the wrong thing for a deduced return type.
3508         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3509       if (ResQT.isNull()) {
3510         if (New->isCXXClassMember() && New->isOutOfLine())
3511           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3512               << New << New->getReturnTypeSourceRange();
3513         else
3514           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3515               << New->getReturnTypeSourceRange();
3516         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3517                                     << Old->getReturnTypeSourceRange();
3518         return true;
3519       }
3520       else
3521         NewQType = ResQT;
3522     }
3523 
3524     QualType OldReturnType = OldType->getReturnType();
3525     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3526     if (OldReturnType != NewReturnType) {
3527       // If this function has a deduced return type and has already been
3528       // defined, copy the deduced value from the old declaration.
3529       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3530       if (OldAT && OldAT->isDeduced()) {
3531         New->setType(
3532             SubstAutoType(New->getType(),
3533                           OldAT->isDependentType() ? Context.DependentTy
3534                                                    : OldAT->getDeducedType()));
3535         NewQType = Context.getCanonicalType(
3536             SubstAutoType(NewQType,
3537                           OldAT->isDependentType() ? Context.DependentTy
3538                                                    : OldAT->getDeducedType()));
3539       }
3540     }
3541 
3542     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3543     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3544     if (OldMethod && NewMethod) {
3545       // Preserve triviality.
3546       NewMethod->setTrivial(OldMethod->isTrivial());
3547 
3548       // MSVC allows explicit template specialization at class scope:
3549       // 2 CXXMethodDecls referring to the same function will be injected.
3550       // We don't want a redeclaration error.
3551       bool IsClassScopeExplicitSpecialization =
3552                               OldMethod->isFunctionTemplateSpecialization() &&
3553                               NewMethod->isFunctionTemplateSpecialization();
3554       bool isFriend = NewMethod->getFriendObjectKind();
3555 
3556       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3557           !IsClassScopeExplicitSpecialization) {
3558         //    -- Member function declarations with the same name and the
3559         //       same parameter types cannot be overloaded if any of them
3560         //       is a static member function declaration.
3561         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3562           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3563           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3564           return true;
3565         }
3566 
3567         // C++ [class.mem]p1:
3568         //   [...] A member shall not be declared twice in the
3569         //   member-specification, except that a nested class or member
3570         //   class template can be declared and then later defined.
3571         if (!inTemplateInstantiation()) {
3572           unsigned NewDiag;
3573           if (isa<CXXConstructorDecl>(OldMethod))
3574             NewDiag = diag::err_constructor_redeclared;
3575           else if (isa<CXXDestructorDecl>(NewMethod))
3576             NewDiag = diag::err_destructor_redeclared;
3577           else if (isa<CXXConversionDecl>(NewMethod))
3578             NewDiag = diag::err_conv_function_redeclared;
3579           else
3580             NewDiag = diag::err_member_redeclared;
3581 
3582           Diag(New->getLocation(), NewDiag);
3583         } else {
3584           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3585             << New << New->getType();
3586         }
3587         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3588         return true;
3589 
3590       // Complain if this is an explicit declaration of a special
3591       // member that was initially declared implicitly.
3592       //
3593       // As an exception, it's okay to befriend such methods in order
3594       // to permit the implicit constructor/destructor/operator calls.
3595       } else if (OldMethod->isImplicit()) {
3596         if (isFriend) {
3597           NewMethod->setImplicit();
3598         } else {
3599           Diag(NewMethod->getLocation(),
3600                diag::err_definition_of_implicitly_declared_member)
3601             << New << getSpecialMember(OldMethod);
3602           return true;
3603         }
3604       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3605         Diag(NewMethod->getLocation(),
3606              diag::err_definition_of_explicitly_defaulted_member)
3607           << getSpecialMember(OldMethod);
3608         return true;
3609       }
3610     }
3611 
3612     // C++11 [dcl.attr.noreturn]p1:
3613     //   The first declaration of a function shall specify the noreturn
3614     //   attribute if any declaration of that function specifies the noreturn
3615     //   attribute.
3616     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3617     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3618       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3619       Diag(Old->getFirstDecl()->getLocation(),
3620            diag::note_noreturn_missing_first_decl);
3621     }
3622 
3623     // C++11 [dcl.attr.depend]p2:
3624     //   The first declaration of a function shall specify the
3625     //   carries_dependency attribute for its declarator-id if any declaration
3626     //   of the function specifies the carries_dependency attribute.
3627     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3628     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3629       Diag(CDA->getLocation(),
3630            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3631       Diag(Old->getFirstDecl()->getLocation(),
3632            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3633     }
3634 
3635     // (C++98 8.3.5p3):
3636     //   All declarations for a function shall agree exactly in both the
3637     //   return type and the parameter-type-list.
3638     // We also want to respect all the extended bits except noreturn.
3639 
3640     // noreturn should now match unless the old type info didn't have it.
3641     QualType OldQTypeForComparison = OldQType;
3642     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3643       auto *OldType = OldQType->castAs<FunctionProtoType>();
3644       const FunctionType *OldTypeForComparison
3645         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3646       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3647       assert(OldQTypeForComparison.isCanonical());
3648     }
3649 
3650     if (haveIncompatibleLanguageLinkages(Old, New)) {
3651       // As a special case, retain the language linkage from previous
3652       // declarations of a friend function as an extension.
3653       //
3654       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3655       // and is useful because there's otherwise no way to specify language
3656       // linkage within class scope.
3657       //
3658       // Check cautiously as the friend object kind isn't yet complete.
3659       if (New->getFriendObjectKind() != Decl::FOK_None) {
3660         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3661         Diag(OldLocation, PrevDiag);
3662       } else {
3663         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3664         Diag(OldLocation, PrevDiag);
3665         return true;
3666       }
3667     }
3668 
3669     // If the function types are compatible, merge the declarations. Ignore the
3670     // exception specifier because it was already checked above in
3671     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3672     // about incompatible types under -fms-compatibility.
3673     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3674                                                          NewQType))
3675       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3676 
3677     // If the types are imprecise (due to dependent constructs in friends or
3678     // local extern declarations), it's OK if they differ. We'll check again
3679     // during instantiation.
3680     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3681       return false;
3682 
3683     // Fall through for conflicting redeclarations and redefinitions.
3684   }
3685 
3686   // C: Function types need to be compatible, not identical. This handles
3687   // duplicate function decls like "void f(int); void f(enum X);" properly.
3688   if (!getLangOpts().CPlusPlus &&
3689       Context.typesAreCompatible(OldQType, NewQType)) {
3690     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3691     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3692     const FunctionProtoType *OldProto = nullptr;
3693     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3694         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3695       // The old declaration provided a function prototype, but the
3696       // new declaration does not. Merge in the prototype.
3697       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3698       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3699       NewQType =
3700           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3701                                   OldProto->getExtProtoInfo());
3702       New->setType(NewQType);
3703       New->setHasInheritedPrototype();
3704 
3705       // Synthesize parameters with the same types.
3706       SmallVector<ParmVarDecl*, 16> Params;
3707       for (const auto &ParamType : OldProto->param_types()) {
3708         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3709                                                  SourceLocation(), nullptr,
3710                                                  ParamType, /*TInfo=*/nullptr,
3711                                                  SC_None, nullptr);
3712         Param->setScopeInfo(0, Params.size());
3713         Param->setImplicit();
3714         Params.push_back(Param);
3715       }
3716 
3717       New->setParams(Params);
3718     }
3719 
3720     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3721   }
3722 
3723   // Check if the function types are compatible when pointer size address
3724   // spaces are ignored.
3725   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3726     return false;
3727 
3728   // GNU C permits a K&R definition to follow a prototype declaration
3729   // if the declared types of the parameters in the K&R definition
3730   // match the types in the prototype declaration, even when the
3731   // promoted types of the parameters from the K&R definition differ
3732   // from the types in the prototype. GCC then keeps the types from
3733   // the prototype.
3734   //
3735   // If a variadic prototype is followed by a non-variadic K&R definition,
3736   // the K&R definition becomes variadic.  This is sort of an edge case, but
3737   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3738   // C99 6.9.1p8.
3739   if (!getLangOpts().CPlusPlus &&
3740       Old->hasPrototype() && !New->hasPrototype() &&
3741       New->getType()->getAs<FunctionProtoType>() &&
3742       Old->getNumParams() == New->getNumParams()) {
3743     SmallVector<QualType, 16> ArgTypes;
3744     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3745     const FunctionProtoType *OldProto
3746       = Old->getType()->getAs<FunctionProtoType>();
3747     const FunctionProtoType *NewProto
3748       = New->getType()->getAs<FunctionProtoType>();
3749 
3750     // Determine whether this is the GNU C extension.
3751     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3752                                                NewProto->getReturnType());
3753     bool LooseCompatible = !MergedReturn.isNull();
3754     for (unsigned Idx = 0, End = Old->getNumParams();
3755          LooseCompatible && Idx != End; ++Idx) {
3756       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3757       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3758       if (Context.typesAreCompatible(OldParm->getType(),
3759                                      NewProto->getParamType(Idx))) {
3760         ArgTypes.push_back(NewParm->getType());
3761       } else if (Context.typesAreCompatible(OldParm->getType(),
3762                                             NewParm->getType(),
3763                                             /*CompareUnqualified=*/true)) {
3764         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3765                                            NewProto->getParamType(Idx) };
3766         Warnings.push_back(Warn);
3767         ArgTypes.push_back(NewParm->getType());
3768       } else
3769         LooseCompatible = false;
3770     }
3771 
3772     if (LooseCompatible) {
3773       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3774         Diag(Warnings[Warn].NewParm->getLocation(),
3775              diag::ext_param_promoted_not_compatible_with_prototype)
3776           << Warnings[Warn].PromotedType
3777           << Warnings[Warn].OldParm->getType();
3778         if (Warnings[Warn].OldParm->getLocation().isValid())
3779           Diag(Warnings[Warn].OldParm->getLocation(),
3780                diag::note_previous_declaration);
3781       }
3782 
3783       if (MergeTypeWithOld)
3784         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3785                                              OldProto->getExtProtoInfo()));
3786       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3787     }
3788 
3789     // Fall through to diagnose conflicting types.
3790   }
3791 
3792   // A function that has already been declared has been redeclared or
3793   // defined with a different type; show an appropriate diagnostic.
3794 
3795   // If the previous declaration was an implicitly-generated builtin
3796   // declaration, then at the very least we should use a specialized note.
3797   unsigned BuiltinID;
3798   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3799     // If it's actually a library-defined builtin function like 'malloc'
3800     // or 'printf', just warn about the incompatible redeclaration.
3801     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3802       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3803       Diag(OldLocation, diag::note_previous_builtin_declaration)
3804         << Old << Old->getType();
3805 
3806       // If this is a global redeclaration, just forget hereafter
3807       // about the "builtin-ness" of the function.
3808       //
3809       // Doing this for local extern declarations is problematic.  If
3810       // the builtin declaration remains visible, a second invalid
3811       // local declaration will produce a hard error; if it doesn't
3812       // remain visible, a single bogus local redeclaration (which is
3813       // actually only a warning) could break all the downstream code.
3814       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3815         New->getIdentifier()->revertBuiltin();
3816 
3817       return false;
3818     }
3819 
3820     PrevDiag = diag::note_previous_builtin_declaration;
3821   }
3822 
3823   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3824   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3825   return true;
3826 }
3827 
3828 /// Completes the merge of two function declarations that are
3829 /// known to be compatible.
3830 ///
3831 /// This routine handles the merging of attributes and other
3832 /// properties of function declarations from the old declaration to
3833 /// the new declaration, once we know that New is in fact a
3834 /// redeclaration of Old.
3835 ///
3836 /// \returns false
3837 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3838                                         Scope *S, bool MergeTypeWithOld) {
3839   // Merge the attributes
3840   mergeDeclAttributes(New, Old);
3841 
3842   // Merge "pure" flag.
3843   if (Old->isPure())
3844     New->setPure();
3845 
3846   // Merge "used" flag.
3847   if (Old->getMostRecentDecl()->isUsed(false))
3848     New->setIsUsed();
3849 
3850   // Merge attributes from the parameters.  These can mismatch with K&R
3851   // declarations.
3852   if (New->getNumParams() == Old->getNumParams())
3853       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3854         ParmVarDecl *NewParam = New->getParamDecl(i);
3855         ParmVarDecl *OldParam = Old->getParamDecl(i);
3856         mergeParamDeclAttributes(NewParam, OldParam, *this);
3857         mergeParamDeclTypes(NewParam, OldParam, *this);
3858       }
3859 
3860   if (getLangOpts().CPlusPlus)
3861     return MergeCXXFunctionDecl(New, Old, S);
3862 
3863   // Merge the function types so the we get the composite types for the return
3864   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3865   // was visible.
3866   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3867   if (!Merged.isNull() && MergeTypeWithOld)
3868     New->setType(Merged);
3869 
3870   return false;
3871 }
3872 
3873 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3874                                 ObjCMethodDecl *oldMethod) {
3875   // Merge the attributes, including deprecated/unavailable
3876   AvailabilityMergeKind MergeKind =
3877     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3878       ? AMK_ProtocolImplementation
3879       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3880                                                        : AMK_Override;
3881 
3882   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3883 
3884   // Merge attributes from the parameters.
3885   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3886                                        oe = oldMethod->param_end();
3887   for (ObjCMethodDecl::param_iterator
3888          ni = newMethod->param_begin(), ne = newMethod->param_end();
3889        ni != ne && oi != oe; ++ni, ++oi)
3890     mergeParamDeclAttributes(*ni, *oi, *this);
3891 
3892   CheckObjCMethodOverride(newMethod, oldMethod);
3893 }
3894 
3895 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3896   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3897 
3898   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3899          ? diag::err_redefinition_different_type
3900          : diag::err_redeclaration_different_type)
3901     << New->getDeclName() << New->getType() << Old->getType();
3902 
3903   diag::kind PrevDiag;
3904   SourceLocation OldLocation;
3905   std::tie(PrevDiag, OldLocation)
3906     = getNoteDiagForInvalidRedeclaration(Old, New);
3907   S.Diag(OldLocation, PrevDiag);
3908   New->setInvalidDecl();
3909 }
3910 
3911 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3912 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3913 /// emitting diagnostics as appropriate.
3914 ///
3915 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3916 /// to here in AddInitializerToDecl. We can't check them before the initializer
3917 /// is attached.
3918 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3919                              bool MergeTypeWithOld) {
3920   if (New->isInvalidDecl() || Old->isInvalidDecl())
3921     return;
3922 
3923   QualType MergedT;
3924   if (getLangOpts().CPlusPlus) {
3925     if (New->getType()->isUndeducedType()) {
3926       // We don't know what the new type is until the initializer is attached.
3927       return;
3928     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3929       // These could still be something that needs exception specs checked.
3930       return MergeVarDeclExceptionSpecs(New, Old);
3931     }
3932     // C++ [basic.link]p10:
3933     //   [...] the types specified by all declarations referring to a given
3934     //   object or function shall be identical, except that declarations for an
3935     //   array object can specify array types that differ by the presence or
3936     //   absence of a major array bound (8.3.4).
3937     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3938       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3939       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3940 
3941       // We are merging a variable declaration New into Old. If it has an array
3942       // bound, and that bound differs from Old's bound, we should diagnose the
3943       // mismatch.
3944       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3945         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3946              PrevVD = PrevVD->getPreviousDecl()) {
3947           QualType PrevVDTy = PrevVD->getType();
3948           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3949             continue;
3950 
3951           if (!Context.hasSameType(New->getType(), PrevVDTy))
3952             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3953         }
3954       }
3955 
3956       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3957         if (Context.hasSameType(OldArray->getElementType(),
3958                                 NewArray->getElementType()))
3959           MergedT = New->getType();
3960       }
3961       // FIXME: Check visibility. New is hidden but has a complete type. If New
3962       // has no array bound, it should not inherit one from Old, if Old is not
3963       // visible.
3964       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3965         if (Context.hasSameType(OldArray->getElementType(),
3966                                 NewArray->getElementType()))
3967           MergedT = Old->getType();
3968       }
3969     }
3970     else if (New->getType()->isObjCObjectPointerType() &&
3971                Old->getType()->isObjCObjectPointerType()) {
3972       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3973                                               Old->getType());
3974     }
3975   } else {
3976     // C 6.2.7p2:
3977     //   All declarations that refer to the same object or function shall have
3978     //   compatible type.
3979     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3980   }
3981   if (MergedT.isNull()) {
3982     // It's OK if we couldn't merge types if either type is dependent, for a
3983     // block-scope variable. In other cases (static data members of class
3984     // templates, variable templates, ...), we require the types to be
3985     // equivalent.
3986     // FIXME: The C++ standard doesn't say anything about this.
3987     if ((New->getType()->isDependentType() ||
3988          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3989       // If the old type was dependent, we can't merge with it, so the new type
3990       // becomes dependent for now. We'll reproduce the original type when we
3991       // instantiate the TypeSourceInfo for the variable.
3992       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3993         New->setType(Context.DependentTy);
3994       return;
3995     }
3996     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3997   }
3998 
3999   // Don't actually update the type on the new declaration if the old
4000   // declaration was an extern declaration in a different scope.
4001   if (MergeTypeWithOld)
4002     New->setType(MergedT);
4003 }
4004 
4005 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4006                                   LookupResult &Previous) {
4007   // C11 6.2.7p4:
4008   //   For an identifier with internal or external linkage declared
4009   //   in a scope in which a prior declaration of that identifier is
4010   //   visible, if the prior declaration specifies internal or
4011   //   external linkage, the type of the identifier at the later
4012   //   declaration becomes the composite type.
4013   //
4014   // If the variable isn't visible, we do not merge with its type.
4015   if (Previous.isShadowed())
4016     return false;
4017 
4018   if (S.getLangOpts().CPlusPlus) {
4019     // C++11 [dcl.array]p3:
4020     //   If there is a preceding declaration of the entity in the same
4021     //   scope in which the bound was specified, an omitted array bound
4022     //   is taken to be the same as in that earlier declaration.
4023     return NewVD->isPreviousDeclInSameBlockScope() ||
4024            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4025             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4026   } else {
4027     // If the old declaration was function-local, don't merge with its
4028     // type unless we're in the same function.
4029     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4030            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4031   }
4032 }
4033 
4034 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4035 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4036 /// situation, merging decls or emitting diagnostics as appropriate.
4037 ///
4038 /// Tentative definition rules (C99 6.9.2p2) are checked by
4039 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4040 /// definitions here, since the initializer hasn't been attached.
4041 ///
4042 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4043   // If the new decl is already invalid, don't do any other checking.
4044   if (New->isInvalidDecl())
4045     return;
4046 
4047   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4048     return;
4049 
4050   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4051 
4052   // Verify the old decl was also a variable or variable template.
4053   VarDecl *Old = nullptr;
4054   VarTemplateDecl *OldTemplate = nullptr;
4055   if (Previous.isSingleResult()) {
4056     if (NewTemplate) {
4057       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4058       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4059 
4060       if (auto *Shadow =
4061               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4062         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4063           return New->setInvalidDecl();
4064     } else {
4065       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4066 
4067       if (auto *Shadow =
4068               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4069         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4070           return New->setInvalidDecl();
4071     }
4072   }
4073   if (!Old) {
4074     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4075         << New->getDeclName();
4076     notePreviousDefinition(Previous.getRepresentativeDecl(),
4077                            New->getLocation());
4078     return New->setInvalidDecl();
4079   }
4080 
4081   // Ensure the template parameters are compatible.
4082   if (NewTemplate &&
4083       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4084                                       OldTemplate->getTemplateParameters(),
4085                                       /*Complain=*/true, TPL_TemplateMatch))
4086     return New->setInvalidDecl();
4087 
4088   // C++ [class.mem]p1:
4089   //   A member shall not be declared twice in the member-specification [...]
4090   //
4091   // Here, we need only consider static data members.
4092   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4093     Diag(New->getLocation(), diag::err_duplicate_member)
4094       << New->getIdentifier();
4095     Diag(Old->getLocation(), diag::note_previous_declaration);
4096     New->setInvalidDecl();
4097   }
4098 
4099   mergeDeclAttributes(New, Old);
4100   // Warn if an already-declared variable is made a weak_import in a subsequent
4101   // declaration
4102   if (New->hasAttr<WeakImportAttr>() &&
4103       Old->getStorageClass() == SC_None &&
4104       !Old->hasAttr<WeakImportAttr>()) {
4105     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4106     notePreviousDefinition(Old, New->getLocation());
4107     // Remove weak_import attribute on new declaration.
4108     New->dropAttr<WeakImportAttr>();
4109   }
4110 
4111   if (New->hasAttr<InternalLinkageAttr>() &&
4112       !Old->hasAttr<InternalLinkageAttr>()) {
4113     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4114         << New->getDeclName();
4115     notePreviousDefinition(Old, New->getLocation());
4116     New->dropAttr<InternalLinkageAttr>();
4117   }
4118 
4119   // Merge the types.
4120   VarDecl *MostRecent = Old->getMostRecentDecl();
4121   if (MostRecent != Old) {
4122     MergeVarDeclTypes(New, MostRecent,
4123                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4124     if (New->isInvalidDecl())
4125       return;
4126   }
4127 
4128   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4129   if (New->isInvalidDecl())
4130     return;
4131 
4132   diag::kind PrevDiag;
4133   SourceLocation OldLocation;
4134   std::tie(PrevDiag, OldLocation) =
4135       getNoteDiagForInvalidRedeclaration(Old, New);
4136 
4137   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4138   if (New->getStorageClass() == SC_Static &&
4139       !New->isStaticDataMember() &&
4140       Old->hasExternalFormalLinkage()) {
4141     if (getLangOpts().MicrosoftExt) {
4142       Diag(New->getLocation(), diag::ext_static_non_static)
4143           << New->getDeclName();
4144       Diag(OldLocation, PrevDiag);
4145     } else {
4146       Diag(New->getLocation(), diag::err_static_non_static)
4147           << New->getDeclName();
4148       Diag(OldLocation, PrevDiag);
4149       return New->setInvalidDecl();
4150     }
4151   }
4152   // C99 6.2.2p4:
4153   //   For an identifier declared with the storage-class specifier
4154   //   extern in a scope in which a prior declaration of that
4155   //   identifier is visible,23) if the prior declaration specifies
4156   //   internal or external linkage, the linkage of the identifier at
4157   //   the later declaration is the same as the linkage specified at
4158   //   the prior declaration. If no prior declaration is visible, or
4159   //   if the prior declaration specifies no linkage, then the
4160   //   identifier has external linkage.
4161   if (New->hasExternalStorage() && Old->hasLinkage())
4162     /* Okay */;
4163   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4164            !New->isStaticDataMember() &&
4165            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4166     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4167     Diag(OldLocation, PrevDiag);
4168     return New->setInvalidDecl();
4169   }
4170 
4171   // Check if extern is followed by non-extern and vice-versa.
4172   if (New->hasExternalStorage() &&
4173       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4174     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4175     Diag(OldLocation, PrevDiag);
4176     return New->setInvalidDecl();
4177   }
4178   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4179       !New->hasExternalStorage()) {
4180     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4181     Diag(OldLocation, PrevDiag);
4182     return New->setInvalidDecl();
4183   }
4184 
4185   if (CheckRedeclarationModuleOwnership(New, Old))
4186     return;
4187 
4188   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4189 
4190   // FIXME: The test for external storage here seems wrong? We still
4191   // need to check for mismatches.
4192   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4193       // Don't complain about out-of-line definitions of static members.
4194       !(Old->getLexicalDeclContext()->isRecord() &&
4195         !New->getLexicalDeclContext()->isRecord())) {
4196     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4197     Diag(OldLocation, PrevDiag);
4198     return New->setInvalidDecl();
4199   }
4200 
4201   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4202     if (VarDecl *Def = Old->getDefinition()) {
4203       // C++1z [dcl.fcn.spec]p4:
4204       //   If the definition of a variable appears in a translation unit before
4205       //   its first declaration as inline, the program is ill-formed.
4206       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4207       Diag(Def->getLocation(), diag::note_previous_definition);
4208     }
4209   }
4210 
4211   // If this redeclaration makes the variable inline, we may need to add it to
4212   // UndefinedButUsed.
4213   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4214       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4215     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4216                                            SourceLocation()));
4217 
4218   if (New->getTLSKind() != Old->getTLSKind()) {
4219     if (!Old->getTLSKind()) {
4220       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4221       Diag(OldLocation, PrevDiag);
4222     } else if (!New->getTLSKind()) {
4223       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4224       Diag(OldLocation, PrevDiag);
4225     } else {
4226       // Do not allow redeclaration to change the variable between requiring
4227       // static and dynamic initialization.
4228       // FIXME: GCC allows this, but uses the TLS keyword on the first
4229       // declaration to determine the kind. Do we need to be compatible here?
4230       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4231         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4232       Diag(OldLocation, PrevDiag);
4233     }
4234   }
4235 
4236   // C++ doesn't have tentative definitions, so go right ahead and check here.
4237   if (getLangOpts().CPlusPlus &&
4238       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4239     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4240         Old->getCanonicalDecl()->isConstexpr()) {
4241       // This definition won't be a definition any more once it's been merged.
4242       Diag(New->getLocation(),
4243            diag::warn_deprecated_redundant_constexpr_static_def);
4244     } else if (VarDecl *Def = Old->getDefinition()) {
4245       if (checkVarDeclRedefinition(Def, New))
4246         return;
4247     }
4248   }
4249 
4250   if (haveIncompatibleLanguageLinkages(Old, New)) {
4251     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4252     Diag(OldLocation, PrevDiag);
4253     New->setInvalidDecl();
4254     return;
4255   }
4256 
4257   // Merge "used" flag.
4258   if (Old->getMostRecentDecl()->isUsed(false))
4259     New->setIsUsed();
4260 
4261   // Keep a chain of previous declarations.
4262   New->setPreviousDecl(Old);
4263   if (NewTemplate)
4264     NewTemplate->setPreviousDecl(OldTemplate);
4265   adjustDeclContextForDeclaratorDecl(New, Old);
4266 
4267   // Inherit access appropriately.
4268   New->setAccess(Old->getAccess());
4269   if (NewTemplate)
4270     NewTemplate->setAccess(New->getAccess());
4271 
4272   if (Old->isInline())
4273     New->setImplicitlyInline();
4274 }
4275 
4276 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4277   SourceManager &SrcMgr = getSourceManager();
4278   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4279   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4280   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4281   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4282   auto &HSI = PP.getHeaderSearchInfo();
4283   StringRef HdrFilename =
4284       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4285 
4286   auto noteFromModuleOrInclude = [&](Module *Mod,
4287                                      SourceLocation IncLoc) -> bool {
4288     // Redefinition errors with modules are common with non modular mapped
4289     // headers, example: a non-modular header H in module A that also gets
4290     // included directly in a TU. Pointing twice to the same header/definition
4291     // is confusing, try to get better diagnostics when modules is on.
4292     if (IncLoc.isValid()) {
4293       if (Mod) {
4294         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4295             << HdrFilename.str() << Mod->getFullModuleName();
4296         if (!Mod->DefinitionLoc.isInvalid())
4297           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4298               << Mod->getFullModuleName();
4299       } else {
4300         Diag(IncLoc, diag::note_redefinition_include_same_file)
4301             << HdrFilename.str();
4302       }
4303       return true;
4304     }
4305 
4306     return false;
4307   };
4308 
4309   // Is it the same file and same offset? Provide more information on why
4310   // this leads to a redefinition error.
4311   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4312     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4313     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4314     bool EmittedDiag =
4315         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4316     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4317 
4318     // If the header has no guards, emit a note suggesting one.
4319     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4320       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4321 
4322     if (EmittedDiag)
4323       return;
4324   }
4325 
4326   // Redefinition coming from different files or couldn't do better above.
4327   if (Old->getLocation().isValid())
4328     Diag(Old->getLocation(), diag::note_previous_definition);
4329 }
4330 
4331 /// We've just determined that \p Old and \p New both appear to be definitions
4332 /// of the same variable. Either diagnose or fix the problem.
4333 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4334   if (!hasVisibleDefinition(Old) &&
4335       (New->getFormalLinkage() == InternalLinkage ||
4336        New->isInline() ||
4337        New->getDescribedVarTemplate() ||
4338        New->getNumTemplateParameterLists() ||
4339        New->getDeclContext()->isDependentContext())) {
4340     // The previous definition is hidden, and multiple definitions are
4341     // permitted (in separate TUs). Demote this to a declaration.
4342     New->demoteThisDefinitionToDeclaration();
4343 
4344     // Make the canonical definition visible.
4345     if (auto *OldTD = Old->getDescribedVarTemplate())
4346       makeMergedDefinitionVisible(OldTD);
4347     makeMergedDefinitionVisible(Old);
4348     return false;
4349   } else {
4350     Diag(New->getLocation(), diag::err_redefinition) << New;
4351     notePreviousDefinition(Old, New->getLocation());
4352     New->setInvalidDecl();
4353     return true;
4354   }
4355 }
4356 
4357 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4358 /// no declarator (e.g. "struct foo;") is parsed.
4359 Decl *
4360 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4361                                  RecordDecl *&AnonRecord) {
4362   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4363                                     AnonRecord);
4364 }
4365 
4366 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4367 // disambiguate entities defined in different scopes.
4368 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4369 // compatibility.
4370 // We will pick our mangling number depending on which version of MSVC is being
4371 // targeted.
4372 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4373   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4374              ? S->getMSCurManglingNumber()
4375              : S->getMSLastManglingNumber();
4376 }
4377 
4378 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4379   if (!Context.getLangOpts().CPlusPlus)
4380     return;
4381 
4382   if (isa<CXXRecordDecl>(Tag->getParent())) {
4383     // If this tag is the direct child of a class, number it if
4384     // it is anonymous.
4385     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4386       return;
4387     MangleNumberingContext &MCtx =
4388         Context.getManglingNumberContext(Tag->getParent());
4389     Context.setManglingNumber(
4390         Tag, MCtx.getManglingNumber(
4391                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4392     return;
4393   }
4394 
4395   // If this tag isn't a direct child of a class, number it if it is local.
4396   MangleNumberingContext *MCtx;
4397   Decl *ManglingContextDecl;
4398   std::tie(MCtx, ManglingContextDecl) =
4399       getCurrentMangleNumberContext(Tag->getDeclContext());
4400   if (MCtx) {
4401     Context.setManglingNumber(
4402         Tag, MCtx->getManglingNumber(
4403                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4404   }
4405 }
4406 
4407 namespace {
4408 struct NonCLikeKind {
4409   enum {
4410     None,
4411     BaseClass,
4412     DefaultMemberInit,
4413     Lambda,
4414     Friend,
4415     OtherMember,
4416     Invalid,
4417   } Kind = None;
4418   SourceRange Range;
4419 
4420   explicit operator bool() { return Kind != None; }
4421 };
4422 }
4423 
4424 /// Determine whether a class is C-like, according to the rules of C++
4425 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4426 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4427   if (RD->isInvalidDecl())
4428     return {NonCLikeKind::Invalid, {}};
4429 
4430   // C++ [dcl.typedef]p9: [P1766R1]
4431   //   An unnamed class with a typedef name for linkage purposes shall not
4432   //
4433   //    -- have any base classes
4434   if (RD->getNumBases())
4435     return {NonCLikeKind::BaseClass,
4436             SourceRange(RD->bases_begin()->getBeginLoc(),
4437                         RD->bases_end()[-1].getEndLoc())};
4438   bool Invalid = false;
4439   for (Decl *D : RD->decls()) {
4440     // Don't complain about things we already diagnosed.
4441     if (D->isInvalidDecl()) {
4442       Invalid = true;
4443       continue;
4444     }
4445 
4446     //  -- have any [...] default member initializers
4447     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4448       if (FD->hasInClassInitializer()) {
4449         auto *Init = FD->getInClassInitializer();
4450         return {NonCLikeKind::DefaultMemberInit,
4451                 Init ? Init->getSourceRange() : D->getSourceRange()};
4452       }
4453       continue;
4454     }
4455 
4456     // FIXME: We don't allow friend declarations. This violates the wording of
4457     // P1766, but not the intent.
4458     if (isa<FriendDecl>(D))
4459       return {NonCLikeKind::Friend, D->getSourceRange()};
4460 
4461     //  -- declare any members other than non-static data members, member
4462     //     enumerations, or member classes,
4463     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4464         isa<EnumDecl>(D))
4465       continue;
4466     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4467     if (!MemberRD) {
4468       if (D->isImplicit())
4469         continue;
4470       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4471     }
4472 
4473     //  -- contain a lambda-expression,
4474     if (MemberRD->isLambda())
4475       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4476 
4477     //  and all member classes shall also satisfy these requirements
4478     //  (recursively).
4479     if (MemberRD->isThisDeclarationADefinition()) {
4480       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4481         return Kind;
4482     }
4483   }
4484 
4485   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4486 }
4487 
4488 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4489                                         TypedefNameDecl *NewTD) {
4490   if (TagFromDeclSpec->isInvalidDecl())
4491     return;
4492 
4493   // Do nothing if the tag already has a name for linkage purposes.
4494   if (TagFromDeclSpec->hasNameForLinkage())
4495     return;
4496 
4497   // A well-formed anonymous tag must always be a TUK_Definition.
4498   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4499 
4500   // The type must match the tag exactly;  no qualifiers allowed.
4501   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4502                            Context.getTagDeclType(TagFromDeclSpec))) {
4503     if (getLangOpts().CPlusPlus)
4504       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4505     return;
4506   }
4507 
4508   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4509   //   An unnamed class with a typedef name for linkage purposes shall [be
4510   //   C-like].
4511   //
4512   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4513   // shouldn't happen, but there are constructs that the language rule doesn't
4514   // disallow for which we can't reasonably avoid computing linkage early.
4515   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4516   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4517                              : NonCLikeKind();
4518   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4519   if (NonCLike || ChangesLinkage) {
4520     if (NonCLike.Kind == NonCLikeKind::Invalid)
4521       return;
4522 
4523     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4524     if (ChangesLinkage) {
4525       // If the linkage changes, we can't accept this as an extension.
4526       if (NonCLike.Kind == NonCLikeKind::None)
4527         DiagID = diag::err_typedef_changes_linkage;
4528       else
4529         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4530     }
4531 
4532     SourceLocation FixitLoc =
4533         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4534     llvm::SmallString<40> TextToInsert;
4535     TextToInsert += ' ';
4536     TextToInsert += NewTD->getIdentifier()->getName();
4537 
4538     Diag(FixitLoc, DiagID)
4539       << isa<TypeAliasDecl>(NewTD)
4540       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4541     if (NonCLike.Kind != NonCLikeKind::None) {
4542       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4543         << NonCLike.Kind - 1 << NonCLike.Range;
4544     }
4545     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4546       << NewTD << isa<TypeAliasDecl>(NewTD);
4547 
4548     if (ChangesLinkage)
4549       return;
4550   }
4551 
4552   // Otherwise, set this as the anon-decl typedef for the tag.
4553   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4554 }
4555 
4556 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4557   switch (T) {
4558   case DeclSpec::TST_class:
4559     return 0;
4560   case DeclSpec::TST_struct:
4561     return 1;
4562   case DeclSpec::TST_interface:
4563     return 2;
4564   case DeclSpec::TST_union:
4565     return 3;
4566   case DeclSpec::TST_enum:
4567     return 4;
4568   default:
4569     llvm_unreachable("unexpected type specifier");
4570   }
4571 }
4572 
4573 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4574 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4575 /// parameters to cope with template friend declarations.
4576 Decl *
4577 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4578                                  MultiTemplateParamsArg TemplateParams,
4579                                  bool IsExplicitInstantiation,
4580                                  RecordDecl *&AnonRecord) {
4581   Decl *TagD = nullptr;
4582   TagDecl *Tag = nullptr;
4583   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4584       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4585       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4586       DS.getTypeSpecType() == DeclSpec::TST_union ||
4587       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4588     TagD = DS.getRepAsDecl();
4589 
4590     if (!TagD) // We probably had an error
4591       return nullptr;
4592 
4593     // Note that the above type specs guarantee that the
4594     // type rep is a Decl, whereas in many of the others
4595     // it's a Type.
4596     if (isa<TagDecl>(TagD))
4597       Tag = cast<TagDecl>(TagD);
4598     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4599       Tag = CTD->getTemplatedDecl();
4600   }
4601 
4602   if (Tag) {
4603     handleTagNumbering(Tag, S);
4604     Tag->setFreeStanding();
4605     if (Tag->isInvalidDecl())
4606       return Tag;
4607   }
4608 
4609   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4610     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4611     // or incomplete types shall not be restrict-qualified."
4612     if (TypeQuals & DeclSpec::TQ_restrict)
4613       Diag(DS.getRestrictSpecLoc(),
4614            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4615            << DS.getSourceRange();
4616   }
4617 
4618   if (DS.isInlineSpecified())
4619     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4620         << getLangOpts().CPlusPlus17;
4621 
4622   if (DS.hasConstexprSpecifier()) {
4623     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4624     // and definitions of functions and variables.
4625     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4626     // the declaration of a function or function template
4627     if (Tag)
4628       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4629           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4630           << DS.getConstexprSpecifier();
4631     else
4632       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4633           << DS.getConstexprSpecifier();
4634     // Don't emit warnings after this error.
4635     return TagD;
4636   }
4637 
4638   DiagnoseFunctionSpecifiers(DS);
4639 
4640   if (DS.isFriendSpecified()) {
4641     // If we're dealing with a decl but not a TagDecl, assume that
4642     // whatever routines created it handled the friendship aspect.
4643     if (TagD && !Tag)
4644       return nullptr;
4645     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4646   }
4647 
4648   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4649   bool IsExplicitSpecialization =
4650     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4651   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4652       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4653       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4654     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4655     // nested-name-specifier unless it is an explicit instantiation
4656     // or an explicit specialization.
4657     //
4658     // FIXME: We allow class template partial specializations here too, per the
4659     // obvious intent of DR1819.
4660     //
4661     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4662     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4663         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4664     return nullptr;
4665   }
4666 
4667   // Track whether this decl-specifier declares anything.
4668   bool DeclaresAnything = true;
4669 
4670   // Handle anonymous struct definitions.
4671   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4672     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4673         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4674       if (getLangOpts().CPlusPlus ||
4675           Record->getDeclContext()->isRecord()) {
4676         // If CurContext is a DeclContext that can contain statements,
4677         // RecursiveASTVisitor won't visit the decls that
4678         // BuildAnonymousStructOrUnion() will put into CurContext.
4679         // Also store them here so that they can be part of the
4680         // DeclStmt that gets created in this case.
4681         // FIXME: Also return the IndirectFieldDecls created by
4682         // BuildAnonymousStructOr union, for the same reason?
4683         if (CurContext->isFunctionOrMethod())
4684           AnonRecord = Record;
4685         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4686                                            Context.getPrintingPolicy());
4687       }
4688 
4689       DeclaresAnything = false;
4690     }
4691   }
4692 
4693   // C11 6.7.2.1p2:
4694   //   A struct-declaration that does not declare an anonymous structure or
4695   //   anonymous union shall contain a struct-declarator-list.
4696   //
4697   // This rule also existed in C89 and C99; the grammar for struct-declaration
4698   // did not permit a struct-declaration without a struct-declarator-list.
4699   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4700       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4701     // Check for Microsoft C extension: anonymous struct/union member.
4702     // Handle 2 kinds of anonymous struct/union:
4703     //   struct STRUCT;
4704     //   union UNION;
4705     // and
4706     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4707     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4708     if ((Tag && Tag->getDeclName()) ||
4709         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4710       RecordDecl *Record = nullptr;
4711       if (Tag)
4712         Record = dyn_cast<RecordDecl>(Tag);
4713       else if (const RecordType *RT =
4714                    DS.getRepAsType().get()->getAsStructureType())
4715         Record = RT->getDecl();
4716       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4717         Record = UT->getDecl();
4718 
4719       if (Record && getLangOpts().MicrosoftExt) {
4720         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4721             << Record->isUnion() << DS.getSourceRange();
4722         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4723       }
4724 
4725       DeclaresAnything = false;
4726     }
4727   }
4728 
4729   // Skip all the checks below if we have a type error.
4730   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4731       (TagD && TagD->isInvalidDecl()))
4732     return TagD;
4733 
4734   if (getLangOpts().CPlusPlus &&
4735       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4736     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4737       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4738           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4739         DeclaresAnything = false;
4740 
4741   if (!DS.isMissingDeclaratorOk()) {
4742     // Customize diagnostic for a typedef missing a name.
4743     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4744       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4745           << DS.getSourceRange();
4746     else
4747       DeclaresAnything = false;
4748   }
4749 
4750   if (DS.isModulePrivateSpecified() &&
4751       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4752     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4753       << Tag->getTagKind()
4754       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4755 
4756   ActOnDocumentableDecl(TagD);
4757 
4758   // C 6.7/2:
4759   //   A declaration [...] shall declare at least a declarator [...], a tag,
4760   //   or the members of an enumeration.
4761   // C++ [dcl.dcl]p3:
4762   //   [If there are no declarators], and except for the declaration of an
4763   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4764   //   names into the program, or shall redeclare a name introduced by a
4765   //   previous declaration.
4766   if (!DeclaresAnything) {
4767     // In C, we allow this as a (popular) extension / bug. Don't bother
4768     // producing further diagnostics for redundant qualifiers after this.
4769     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4770                                ? diag::err_no_declarators
4771                                : diag::ext_no_declarators)
4772         << DS.getSourceRange();
4773     return TagD;
4774   }
4775 
4776   // C++ [dcl.stc]p1:
4777   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4778   //   init-declarator-list of the declaration shall not be empty.
4779   // C++ [dcl.fct.spec]p1:
4780   //   If a cv-qualifier appears in a decl-specifier-seq, the
4781   //   init-declarator-list of the declaration shall not be empty.
4782   //
4783   // Spurious qualifiers here appear to be valid in C.
4784   unsigned DiagID = diag::warn_standalone_specifier;
4785   if (getLangOpts().CPlusPlus)
4786     DiagID = diag::ext_standalone_specifier;
4787 
4788   // Note that a linkage-specification sets a storage class, but
4789   // 'extern "C" struct foo;' is actually valid and not theoretically
4790   // useless.
4791   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4792     if (SCS == DeclSpec::SCS_mutable)
4793       // Since mutable is not a viable storage class specifier in C, there is
4794       // no reason to treat it as an extension. Instead, diagnose as an error.
4795       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4796     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4797       Diag(DS.getStorageClassSpecLoc(), DiagID)
4798         << DeclSpec::getSpecifierName(SCS);
4799   }
4800 
4801   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4802     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4803       << DeclSpec::getSpecifierName(TSCS);
4804   if (DS.getTypeQualifiers()) {
4805     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4806       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4807     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4808       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4809     // Restrict is covered above.
4810     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4811       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4812     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4813       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4814   }
4815 
4816   // Warn about ignored type attributes, for example:
4817   // __attribute__((aligned)) struct A;
4818   // Attributes should be placed after tag to apply to type declaration.
4819   if (!DS.getAttributes().empty()) {
4820     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4821     if (TypeSpecType == DeclSpec::TST_class ||
4822         TypeSpecType == DeclSpec::TST_struct ||
4823         TypeSpecType == DeclSpec::TST_interface ||
4824         TypeSpecType == DeclSpec::TST_union ||
4825         TypeSpecType == DeclSpec::TST_enum) {
4826       for (const ParsedAttr &AL : DS.getAttributes())
4827         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4828             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4829     }
4830   }
4831 
4832   return TagD;
4833 }
4834 
4835 /// We are trying to inject an anonymous member into the given scope;
4836 /// check if there's an existing declaration that can't be overloaded.
4837 ///
4838 /// \return true if this is a forbidden redeclaration
4839 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4840                                          Scope *S,
4841                                          DeclContext *Owner,
4842                                          DeclarationName Name,
4843                                          SourceLocation NameLoc,
4844                                          bool IsUnion) {
4845   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4846                  Sema::ForVisibleRedeclaration);
4847   if (!SemaRef.LookupName(R, S)) return false;
4848 
4849   // Pick a representative declaration.
4850   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4851   assert(PrevDecl && "Expected a non-null Decl");
4852 
4853   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4854     return false;
4855 
4856   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4857     << IsUnion << Name;
4858   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4859 
4860   return true;
4861 }
4862 
4863 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4864 /// anonymous struct or union AnonRecord into the owning context Owner
4865 /// and scope S. This routine will be invoked just after we realize
4866 /// that an unnamed union or struct is actually an anonymous union or
4867 /// struct, e.g.,
4868 ///
4869 /// @code
4870 /// union {
4871 ///   int i;
4872 ///   float f;
4873 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4874 ///    // f into the surrounding scope.x
4875 /// @endcode
4876 ///
4877 /// This routine is recursive, injecting the names of nested anonymous
4878 /// structs/unions into the owning context and scope as well.
4879 static bool
4880 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4881                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4882                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4883   bool Invalid = false;
4884 
4885   // Look every FieldDecl and IndirectFieldDecl with a name.
4886   for (auto *D : AnonRecord->decls()) {
4887     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4888         cast<NamedDecl>(D)->getDeclName()) {
4889       ValueDecl *VD = cast<ValueDecl>(D);
4890       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4891                                        VD->getLocation(),
4892                                        AnonRecord->isUnion())) {
4893         // C++ [class.union]p2:
4894         //   The names of the members of an anonymous union shall be
4895         //   distinct from the names of any other entity in the
4896         //   scope in which the anonymous union is declared.
4897         Invalid = true;
4898       } else {
4899         // C++ [class.union]p2:
4900         //   For the purpose of name lookup, after the anonymous union
4901         //   definition, the members of the anonymous union are
4902         //   considered to have been defined in the scope in which the
4903         //   anonymous union is declared.
4904         unsigned OldChainingSize = Chaining.size();
4905         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4906           Chaining.append(IF->chain_begin(), IF->chain_end());
4907         else
4908           Chaining.push_back(VD);
4909 
4910         assert(Chaining.size() >= 2);
4911         NamedDecl **NamedChain =
4912           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4913         for (unsigned i = 0; i < Chaining.size(); i++)
4914           NamedChain[i] = Chaining[i];
4915 
4916         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4917             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4918             VD->getType(), {NamedChain, Chaining.size()});
4919 
4920         for (const auto *Attr : VD->attrs())
4921           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4922 
4923         IndirectField->setAccess(AS);
4924         IndirectField->setImplicit();
4925         SemaRef.PushOnScopeChains(IndirectField, S);
4926 
4927         // That includes picking up the appropriate access specifier.
4928         if (AS != AS_none) IndirectField->setAccess(AS);
4929 
4930         Chaining.resize(OldChainingSize);
4931       }
4932     }
4933   }
4934 
4935   return Invalid;
4936 }
4937 
4938 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4939 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4940 /// illegal input values are mapped to SC_None.
4941 static StorageClass
4942 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4943   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4944   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4945          "Parser allowed 'typedef' as storage class VarDecl.");
4946   switch (StorageClassSpec) {
4947   case DeclSpec::SCS_unspecified:    return SC_None;
4948   case DeclSpec::SCS_extern:
4949     if (DS.isExternInLinkageSpec())
4950       return SC_None;
4951     return SC_Extern;
4952   case DeclSpec::SCS_static:         return SC_Static;
4953   case DeclSpec::SCS_auto:           return SC_Auto;
4954   case DeclSpec::SCS_register:       return SC_Register;
4955   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4956     // Illegal SCSs map to None: error reporting is up to the caller.
4957   case DeclSpec::SCS_mutable:        // Fall through.
4958   case DeclSpec::SCS_typedef:        return SC_None;
4959   }
4960   llvm_unreachable("unknown storage class specifier");
4961 }
4962 
4963 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4964   assert(Record->hasInClassInitializer());
4965 
4966   for (const auto *I : Record->decls()) {
4967     const auto *FD = dyn_cast<FieldDecl>(I);
4968     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4969       FD = IFD->getAnonField();
4970     if (FD && FD->hasInClassInitializer())
4971       return FD->getLocation();
4972   }
4973 
4974   llvm_unreachable("couldn't find in-class initializer");
4975 }
4976 
4977 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4978                                       SourceLocation DefaultInitLoc) {
4979   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4980     return;
4981 
4982   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4983   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4984 }
4985 
4986 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4987                                       CXXRecordDecl *AnonUnion) {
4988   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4989     return;
4990 
4991   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4992 }
4993 
4994 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4995 /// anonymous structure or union. Anonymous unions are a C++ feature
4996 /// (C++ [class.union]) and a C11 feature; anonymous structures
4997 /// are a C11 feature and GNU C++ extension.
4998 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4999                                         AccessSpecifier AS,
5000                                         RecordDecl *Record,
5001                                         const PrintingPolicy &Policy) {
5002   DeclContext *Owner = Record->getDeclContext();
5003 
5004   // Diagnose whether this anonymous struct/union is an extension.
5005   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5006     Diag(Record->getLocation(), diag::ext_anonymous_union);
5007   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5008     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5009   else if (!Record->isUnion() && !getLangOpts().C11)
5010     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5011 
5012   // C and C++ require different kinds of checks for anonymous
5013   // structs/unions.
5014   bool Invalid = false;
5015   if (getLangOpts().CPlusPlus) {
5016     const char *PrevSpec = nullptr;
5017     if (Record->isUnion()) {
5018       // C++ [class.union]p6:
5019       // C++17 [class.union.anon]p2:
5020       //   Anonymous unions declared in a named namespace or in the
5021       //   global namespace shall be declared static.
5022       unsigned DiagID;
5023       DeclContext *OwnerScope = Owner->getRedeclContext();
5024       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5025           (OwnerScope->isTranslationUnit() ||
5026            (OwnerScope->isNamespace() &&
5027             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5028         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5029           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5030 
5031         // Recover by adding 'static'.
5032         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5033                                PrevSpec, DiagID, Policy);
5034       }
5035       // C++ [class.union]p6:
5036       //   A storage class is not allowed in a declaration of an
5037       //   anonymous union in a class scope.
5038       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5039                isa<RecordDecl>(Owner)) {
5040         Diag(DS.getStorageClassSpecLoc(),
5041              diag::err_anonymous_union_with_storage_spec)
5042           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5043 
5044         // Recover by removing the storage specifier.
5045         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5046                                SourceLocation(),
5047                                PrevSpec, DiagID, Context.getPrintingPolicy());
5048       }
5049     }
5050 
5051     // Ignore const/volatile/restrict qualifiers.
5052     if (DS.getTypeQualifiers()) {
5053       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5054         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5055           << Record->isUnion() << "const"
5056           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5057       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5058         Diag(DS.getVolatileSpecLoc(),
5059              diag::ext_anonymous_struct_union_qualified)
5060           << Record->isUnion() << "volatile"
5061           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5062       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5063         Diag(DS.getRestrictSpecLoc(),
5064              diag::ext_anonymous_struct_union_qualified)
5065           << Record->isUnion() << "restrict"
5066           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5067       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5068         Diag(DS.getAtomicSpecLoc(),
5069              diag::ext_anonymous_struct_union_qualified)
5070           << Record->isUnion() << "_Atomic"
5071           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5072       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5073         Diag(DS.getUnalignedSpecLoc(),
5074              diag::ext_anonymous_struct_union_qualified)
5075           << Record->isUnion() << "__unaligned"
5076           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5077 
5078       DS.ClearTypeQualifiers();
5079     }
5080 
5081     // C++ [class.union]p2:
5082     //   The member-specification of an anonymous union shall only
5083     //   define non-static data members. [Note: nested types and
5084     //   functions cannot be declared within an anonymous union. ]
5085     for (auto *Mem : Record->decls()) {
5086       // Ignore invalid declarations; we already diagnosed them.
5087       if (Mem->isInvalidDecl())
5088         continue;
5089 
5090       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5091         // C++ [class.union]p3:
5092         //   An anonymous union shall not have private or protected
5093         //   members (clause 11).
5094         assert(FD->getAccess() != AS_none);
5095         if (FD->getAccess() != AS_public) {
5096           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5097             << Record->isUnion() << (FD->getAccess() == AS_protected);
5098           Invalid = true;
5099         }
5100 
5101         // C++ [class.union]p1
5102         //   An object of a class with a non-trivial constructor, a non-trivial
5103         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5104         //   assignment operator cannot be a member of a union, nor can an
5105         //   array of such objects.
5106         if (CheckNontrivialField(FD))
5107           Invalid = true;
5108       } else if (Mem->isImplicit()) {
5109         // Any implicit members are fine.
5110       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5111         // This is a type that showed up in an
5112         // elaborated-type-specifier inside the anonymous struct or
5113         // union, but which actually declares a type outside of the
5114         // anonymous struct or union. It's okay.
5115       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5116         if (!MemRecord->isAnonymousStructOrUnion() &&
5117             MemRecord->getDeclName()) {
5118           // Visual C++ allows type definition in anonymous struct or union.
5119           if (getLangOpts().MicrosoftExt)
5120             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5121               << Record->isUnion();
5122           else {
5123             // This is a nested type declaration.
5124             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5125               << Record->isUnion();
5126             Invalid = true;
5127           }
5128         } else {
5129           // This is an anonymous type definition within another anonymous type.
5130           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5131           // not part of standard C++.
5132           Diag(MemRecord->getLocation(),
5133                diag::ext_anonymous_record_with_anonymous_type)
5134             << Record->isUnion();
5135         }
5136       } else if (isa<AccessSpecDecl>(Mem)) {
5137         // Any access specifier is fine.
5138       } else if (isa<StaticAssertDecl>(Mem)) {
5139         // In C++1z, static_assert declarations are also fine.
5140       } else {
5141         // We have something that isn't a non-static data
5142         // member. Complain about it.
5143         unsigned DK = diag::err_anonymous_record_bad_member;
5144         if (isa<TypeDecl>(Mem))
5145           DK = diag::err_anonymous_record_with_type;
5146         else if (isa<FunctionDecl>(Mem))
5147           DK = diag::err_anonymous_record_with_function;
5148         else if (isa<VarDecl>(Mem))
5149           DK = diag::err_anonymous_record_with_static;
5150 
5151         // Visual C++ allows type definition in anonymous struct or union.
5152         if (getLangOpts().MicrosoftExt &&
5153             DK == diag::err_anonymous_record_with_type)
5154           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5155             << Record->isUnion();
5156         else {
5157           Diag(Mem->getLocation(), DK) << Record->isUnion();
5158           Invalid = true;
5159         }
5160       }
5161     }
5162 
5163     // C++11 [class.union]p8 (DR1460):
5164     //   At most one variant member of a union may have a
5165     //   brace-or-equal-initializer.
5166     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5167         Owner->isRecord())
5168       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5169                                 cast<CXXRecordDecl>(Record));
5170   }
5171 
5172   if (!Record->isUnion() && !Owner->isRecord()) {
5173     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5174       << getLangOpts().CPlusPlus;
5175     Invalid = true;
5176   }
5177 
5178   // C++ [dcl.dcl]p3:
5179   //   [If there are no declarators], and except for the declaration of an
5180   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5181   //   names into the program
5182   // C++ [class.mem]p2:
5183   //   each such member-declaration shall either declare at least one member
5184   //   name of the class or declare at least one unnamed bit-field
5185   //
5186   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5187   if (getLangOpts().CPlusPlus && Record->field_empty())
5188     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5189 
5190   // Mock up a declarator.
5191   Declarator Dc(DS, DeclaratorContext::MemberContext);
5192   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5193   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5194 
5195   // Create a declaration for this anonymous struct/union.
5196   NamedDecl *Anon = nullptr;
5197   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5198     Anon = FieldDecl::Create(
5199         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5200         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5201         /*BitWidth=*/nullptr, /*Mutable=*/false,
5202         /*InitStyle=*/ICIS_NoInit);
5203     Anon->setAccess(AS);
5204     ProcessDeclAttributes(S, Anon, Dc);
5205 
5206     if (getLangOpts().CPlusPlus)
5207       FieldCollector->Add(cast<FieldDecl>(Anon));
5208   } else {
5209     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5210     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5211     if (SCSpec == DeclSpec::SCS_mutable) {
5212       // mutable can only appear on non-static class members, so it's always
5213       // an error here
5214       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5215       Invalid = true;
5216       SC = SC_None;
5217     }
5218 
5219     assert(DS.getAttributes().empty() && "No attribute expected");
5220     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5221                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5222                            Context.getTypeDeclType(Record), TInfo, SC);
5223 
5224     // Default-initialize the implicit variable. This initialization will be
5225     // trivial in almost all cases, except if a union member has an in-class
5226     // initializer:
5227     //   union { int n = 0; };
5228     ActOnUninitializedDecl(Anon);
5229   }
5230   Anon->setImplicit();
5231 
5232   // Mark this as an anonymous struct/union type.
5233   Record->setAnonymousStructOrUnion(true);
5234 
5235   // Add the anonymous struct/union object to the current
5236   // context. We'll be referencing this object when we refer to one of
5237   // its members.
5238   Owner->addDecl(Anon);
5239 
5240   // Inject the members of the anonymous struct/union into the owning
5241   // context and into the identifier resolver chain for name lookup
5242   // purposes.
5243   SmallVector<NamedDecl*, 2> Chain;
5244   Chain.push_back(Anon);
5245 
5246   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5247     Invalid = true;
5248 
5249   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5250     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5251       MangleNumberingContext *MCtx;
5252       Decl *ManglingContextDecl;
5253       std::tie(MCtx, ManglingContextDecl) =
5254           getCurrentMangleNumberContext(NewVD->getDeclContext());
5255       if (MCtx) {
5256         Context.setManglingNumber(
5257             NewVD, MCtx->getManglingNumber(
5258                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5259         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5260       }
5261     }
5262   }
5263 
5264   if (Invalid)
5265     Anon->setInvalidDecl();
5266 
5267   return Anon;
5268 }
5269 
5270 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5271 /// Microsoft C anonymous structure.
5272 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5273 /// Example:
5274 ///
5275 /// struct A { int a; };
5276 /// struct B { struct A; int b; };
5277 ///
5278 /// void foo() {
5279 ///   B var;
5280 ///   var.a = 3;
5281 /// }
5282 ///
5283 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5284                                            RecordDecl *Record) {
5285   assert(Record && "expected a record!");
5286 
5287   // Mock up a declarator.
5288   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5289   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5290   assert(TInfo && "couldn't build declarator info for anonymous struct");
5291 
5292   auto *ParentDecl = cast<RecordDecl>(CurContext);
5293   QualType RecTy = Context.getTypeDeclType(Record);
5294 
5295   // Create a declaration for this anonymous struct.
5296   NamedDecl *Anon =
5297       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5298                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5299                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5300                         /*InitStyle=*/ICIS_NoInit);
5301   Anon->setImplicit();
5302 
5303   // Add the anonymous struct object to the current context.
5304   CurContext->addDecl(Anon);
5305 
5306   // Inject the members of the anonymous struct into the current
5307   // context and into the identifier resolver chain for name lookup
5308   // purposes.
5309   SmallVector<NamedDecl*, 2> Chain;
5310   Chain.push_back(Anon);
5311 
5312   RecordDecl *RecordDef = Record->getDefinition();
5313   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5314                                diag::err_field_incomplete_or_sizeless) ||
5315       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5316                                           AS_none, Chain)) {
5317     Anon->setInvalidDecl();
5318     ParentDecl->setInvalidDecl();
5319   }
5320 
5321   return Anon;
5322 }
5323 
5324 /// GetNameForDeclarator - Determine the full declaration name for the
5325 /// given Declarator.
5326 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5327   return GetNameFromUnqualifiedId(D.getName());
5328 }
5329 
5330 /// Retrieves the declaration name from a parsed unqualified-id.
5331 DeclarationNameInfo
5332 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5333   DeclarationNameInfo NameInfo;
5334   NameInfo.setLoc(Name.StartLocation);
5335 
5336   switch (Name.getKind()) {
5337 
5338   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5339   case UnqualifiedIdKind::IK_Identifier:
5340     NameInfo.setName(Name.Identifier);
5341     return NameInfo;
5342 
5343   case UnqualifiedIdKind::IK_DeductionGuideName: {
5344     // C++ [temp.deduct.guide]p3:
5345     //   The simple-template-id shall name a class template specialization.
5346     //   The template-name shall be the same identifier as the template-name
5347     //   of the simple-template-id.
5348     // These together intend to imply that the template-name shall name a
5349     // class template.
5350     // FIXME: template<typename T> struct X {};
5351     //        template<typename T> using Y = X<T>;
5352     //        Y(int) -> Y<int>;
5353     //   satisfies these rules but does not name a class template.
5354     TemplateName TN = Name.TemplateName.get().get();
5355     auto *Template = TN.getAsTemplateDecl();
5356     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5357       Diag(Name.StartLocation,
5358            diag::err_deduction_guide_name_not_class_template)
5359         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5360       if (Template)
5361         Diag(Template->getLocation(), diag::note_template_decl_here);
5362       return DeclarationNameInfo();
5363     }
5364 
5365     NameInfo.setName(
5366         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5367     return NameInfo;
5368   }
5369 
5370   case UnqualifiedIdKind::IK_OperatorFunctionId:
5371     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5372                                            Name.OperatorFunctionId.Operator));
5373     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5374       = Name.OperatorFunctionId.SymbolLocations[0];
5375     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5376       = Name.EndLocation.getRawEncoding();
5377     return NameInfo;
5378 
5379   case UnqualifiedIdKind::IK_LiteralOperatorId:
5380     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5381                                                            Name.Identifier));
5382     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5383     return NameInfo;
5384 
5385   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5386     TypeSourceInfo *TInfo;
5387     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5388     if (Ty.isNull())
5389       return DeclarationNameInfo();
5390     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5391                                                Context.getCanonicalType(Ty)));
5392     NameInfo.setNamedTypeInfo(TInfo);
5393     return NameInfo;
5394   }
5395 
5396   case UnqualifiedIdKind::IK_ConstructorName: {
5397     TypeSourceInfo *TInfo;
5398     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5399     if (Ty.isNull())
5400       return DeclarationNameInfo();
5401     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5402                                               Context.getCanonicalType(Ty)));
5403     NameInfo.setNamedTypeInfo(TInfo);
5404     return NameInfo;
5405   }
5406 
5407   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5408     // In well-formed code, we can only have a constructor
5409     // template-id that refers to the current context, so go there
5410     // to find the actual type being constructed.
5411     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5412     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5413       return DeclarationNameInfo();
5414 
5415     // Determine the type of the class being constructed.
5416     QualType CurClassType = Context.getTypeDeclType(CurClass);
5417 
5418     // FIXME: Check two things: that the template-id names the same type as
5419     // CurClassType, and that the template-id does not occur when the name
5420     // was qualified.
5421 
5422     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5423                                     Context.getCanonicalType(CurClassType)));
5424     // FIXME: should we retrieve TypeSourceInfo?
5425     NameInfo.setNamedTypeInfo(nullptr);
5426     return NameInfo;
5427   }
5428 
5429   case UnqualifiedIdKind::IK_DestructorName: {
5430     TypeSourceInfo *TInfo;
5431     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5432     if (Ty.isNull())
5433       return DeclarationNameInfo();
5434     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5435                                               Context.getCanonicalType(Ty)));
5436     NameInfo.setNamedTypeInfo(TInfo);
5437     return NameInfo;
5438   }
5439 
5440   case UnqualifiedIdKind::IK_TemplateId: {
5441     TemplateName TName = Name.TemplateId->Template.get();
5442     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5443     return Context.getNameForTemplate(TName, TNameLoc);
5444   }
5445 
5446   } // switch (Name.getKind())
5447 
5448   llvm_unreachable("Unknown name kind");
5449 }
5450 
5451 static QualType getCoreType(QualType Ty) {
5452   do {
5453     if (Ty->isPointerType() || Ty->isReferenceType())
5454       Ty = Ty->getPointeeType();
5455     else if (Ty->isArrayType())
5456       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5457     else
5458       return Ty.withoutLocalFastQualifiers();
5459   } while (true);
5460 }
5461 
5462 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5463 /// and Definition have "nearly" matching parameters. This heuristic is
5464 /// used to improve diagnostics in the case where an out-of-line function
5465 /// definition doesn't match any declaration within the class or namespace.
5466 /// Also sets Params to the list of indices to the parameters that differ
5467 /// between the declaration and the definition. If hasSimilarParameters
5468 /// returns true and Params is empty, then all of the parameters match.
5469 static bool hasSimilarParameters(ASTContext &Context,
5470                                      FunctionDecl *Declaration,
5471                                      FunctionDecl *Definition,
5472                                      SmallVectorImpl<unsigned> &Params) {
5473   Params.clear();
5474   if (Declaration->param_size() != Definition->param_size())
5475     return false;
5476   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5477     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5478     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5479 
5480     // The parameter types are identical
5481     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5482       continue;
5483 
5484     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5485     QualType DefParamBaseTy = getCoreType(DefParamTy);
5486     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5487     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5488 
5489     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5490         (DeclTyName && DeclTyName == DefTyName))
5491       Params.push_back(Idx);
5492     else  // The two parameters aren't even close
5493       return false;
5494   }
5495 
5496   return true;
5497 }
5498 
5499 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5500 /// declarator needs to be rebuilt in the current instantiation.
5501 /// Any bits of declarator which appear before the name are valid for
5502 /// consideration here.  That's specifically the type in the decl spec
5503 /// and the base type in any member-pointer chunks.
5504 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5505                                                     DeclarationName Name) {
5506   // The types we specifically need to rebuild are:
5507   //   - typenames, typeofs, and decltypes
5508   //   - types which will become injected class names
5509   // Of course, we also need to rebuild any type referencing such a
5510   // type.  It's safest to just say "dependent", but we call out a
5511   // few cases here.
5512 
5513   DeclSpec &DS = D.getMutableDeclSpec();
5514   switch (DS.getTypeSpecType()) {
5515   case DeclSpec::TST_typename:
5516   case DeclSpec::TST_typeofType:
5517   case DeclSpec::TST_underlyingType:
5518   case DeclSpec::TST_atomic: {
5519     // Grab the type from the parser.
5520     TypeSourceInfo *TSI = nullptr;
5521     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5522     if (T.isNull() || !T->isDependentType()) break;
5523 
5524     // Make sure there's a type source info.  This isn't really much
5525     // of a waste; most dependent types should have type source info
5526     // attached already.
5527     if (!TSI)
5528       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5529 
5530     // Rebuild the type in the current instantiation.
5531     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5532     if (!TSI) return true;
5533 
5534     // Store the new type back in the decl spec.
5535     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5536     DS.UpdateTypeRep(LocType);
5537     break;
5538   }
5539 
5540   case DeclSpec::TST_decltype:
5541   case DeclSpec::TST_typeofExpr: {
5542     Expr *E = DS.getRepAsExpr();
5543     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5544     if (Result.isInvalid()) return true;
5545     DS.UpdateExprRep(Result.get());
5546     break;
5547   }
5548 
5549   default:
5550     // Nothing to do for these decl specs.
5551     break;
5552   }
5553 
5554   // It doesn't matter what order we do this in.
5555   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5556     DeclaratorChunk &Chunk = D.getTypeObject(I);
5557 
5558     // The only type information in the declarator which can come
5559     // before the declaration name is the base type of a member
5560     // pointer.
5561     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5562       continue;
5563 
5564     // Rebuild the scope specifier in-place.
5565     CXXScopeSpec &SS = Chunk.Mem.Scope();
5566     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5567       return true;
5568   }
5569 
5570   return false;
5571 }
5572 
5573 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5574   D.setFunctionDefinitionKind(FDK_Declaration);
5575   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5576 
5577   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5578       Dcl && Dcl->getDeclContext()->isFileContext())
5579     Dcl->setTopLevelDeclInObjCContainer();
5580 
5581   if (getLangOpts().OpenCL)
5582     setCurrentOpenCLExtensionForDecl(Dcl);
5583 
5584   return Dcl;
5585 }
5586 
5587 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5588 ///   If T is the name of a class, then each of the following shall have a
5589 ///   name different from T:
5590 ///     - every static data member of class T;
5591 ///     - every member function of class T
5592 ///     - every member of class T that is itself a type;
5593 /// \returns true if the declaration name violates these rules.
5594 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5595                                    DeclarationNameInfo NameInfo) {
5596   DeclarationName Name = NameInfo.getName();
5597 
5598   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5599   while (Record && Record->isAnonymousStructOrUnion())
5600     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5601   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5602     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5603     return true;
5604   }
5605 
5606   return false;
5607 }
5608 
5609 /// Diagnose a declaration whose declarator-id has the given
5610 /// nested-name-specifier.
5611 ///
5612 /// \param SS The nested-name-specifier of the declarator-id.
5613 ///
5614 /// \param DC The declaration context to which the nested-name-specifier
5615 /// resolves.
5616 ///
5617 /// \param Name The name of the entity being declared.
5618 ///
5619 /// \param Loc The location of the name of the entity being declared.
5620 ///
5621 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5622 /// we're declaring an explicit / partial specialization / instantiation.
5623 ///
5624 /// \returns true if we cannot safely recover from this error, false otherwise.
5625 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5626                                         DeclarationName Name,
5627                                         SourceLocation Loc, bool IsTemplateId) {
5628   DeclContext *Cur = CurContext;
5629   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5630     Cur = Cur->getParent();
5631 
5632   // If the user provided a superfluous scope specifier that refers back to the
5633   // class in which the entity is already declared, diagnose and ignore it.
5634   //
5635   // class X {
5636   //   void X::f();
5637   // };
5638   //
5639   // Note, it was once ill-formed to give redundant qualification in all
5640   // contexts, but that rule was removed by DR482.
5641   if (Cur->Equals(DC)) {
5642     if (Cur->isRecord()) {
5643       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5644                                       : diag::err_member_extra_qualification)
5645         << Name << FixItHint::CreateRemoval(SS.getRange());
5646       SS.clear();
5647     } else {
5648       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5649     }
5650     return false;
5651   }
5652 
5653   // Check whether the qualifying scope encloses the scope of the original
5654   // declaration. For a template-id, we perform the checks in
5655   // CheckTemplateSpecializationScope.
5656   if (!Cur->Encloses(DC) && !IsTemplateId) {
5657     if (Cur->isRecord())
5658       Diag(Loc, diag::err_member_qualification)
5659         << Name << SS.getRange();
5660     else if (isa<TranslationUnitDecl>(DC))
5661       Diag(Loc, diag::err_invalid_declarator_global_scope)
5662         << Name << SS.getRange();
5663     else if (isa<FunctionDecl>(Cur))
5664       Diag(Loc, diag::err_invalid_declarator_in_function)
5665         << Name << SS.getRange();
5666     else if (isa<BlockDecl>(Cur))
5667       Diag(Loc, diag::err_invalid_declarator_in_block)
5668         << Name << SS.getRange();
5669     else
5670       Diag(Loc, diag::err_invalid_declarator_scope)
5671       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5672 
5673     return true;
5674   }
5675 
5676   if (Cur->isRecord()) {
5677     // Cannot qualify members within a class.
5678     Diag(Loc, diag::err_member_qualification)
5679       << Name << SS.getRange();
5680     SS.clear();
5681 
5682     // C++ constructors and destructors with incorrect scopes can break
5683     // our AST invariants by having the wrong underlying types. If
5684     // that's the case, then drop this declaration entirely.
5685     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5686          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5687         !Context.hasSameType(Name.getCXXNameType(),
5688                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5689       return true;
5690 
5691     return false;
5692   }
5693 
5694   // C++11 [dcl.meaning]p1:
5695   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5696   //   not begin with a decltype-specifer"
5697   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5698   while (SpecLoc.getPrefix())
5699     SpecLoc = SpecLoc.getPrefix();
5700   if (dyn_cast_or_null<DecltypeType>(
5701         SpecLoc.getNestedNameSpecifier()->getAsType()))
5702     Diag(Loc, diag::err_decltype_in_declarator)
5703       << SpecLoc.getTypeLoc().getSourceRange();
5704 
5705   return false;
5706 }
5707 
5708 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5709                                   MultiTemplateParamsArg TemplateParamLists) {
5710   // TODO: consider using NameInfo for diagnostic.
5711   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5712   DeclarationName Name = NameInfo.getName();
5713 
5714   // All of these full declarators require an identifier.  If it doesn't have
5715   // one, the ParsedFreeStandingDeclSpec action should be used.
5716   if (D.isDecompositionDeclarator()) {
5717     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5718   } else if (!Name) {
5719     if (!D.isInvalidType())  // Reject this if we think it is valid.
5720       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5721           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5722     return nullptr;
5723   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5724     return nullptr;
5725 
5726   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5727   // we find one that is.
5728   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5729          (S->getFlags() & Scope::TemplateParamScope) != 0)
5730     S = S->getParent();
5731 
5732   DeclContext *DC = CurContext;
5733   if (D.getCXXScopeSpec().isInvalid())
5734     D.setInvalidType();
5735   else if (D.getCXXScopeSpec().isSet()) {
5736     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5737                                         UPPC_DeclarationQualifier))
5738       return nullptr;
5739 
5740     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5741     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5742     if (!DC || isa<EnumDecl>(DC)) {
5743       // If we could not compute the declaration context, it's because the
5744       // declaration context is dependent but does not refer to a class,
5745       // class template, or class template partial specialization. Complain
5746       // and return early, to avoid the coming semantic disaster.
5747       Diag(D.getIdentifierLoc(),
5748            diag::err_template_qualified_declarator_no_match)
5749         << D.getCXXScopeSpec().getScopeRep()
5750         << D.getCXXScopeSpec().getRange();
5751       return nullptr;
5752     }
5753     bool IsDependentContext = DC->isDependentContext();
5754 
5755     if (!IsDependentContext &&
5756         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5757       return nullptr;
5758 
5759     // If a class is incomplete, do not parse entities inside it.
5760     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5761       Diag(D.getIdentifierLoc(),
5762            diag::err_member_def_undefined_record)
5763         << Name << DC << D.getCXXScopeSpec().getRange();
5764       return nullptr;
5765     }
5766     if (!D.getDeclSpec().isFriendSpecified()) {
5767       if (diagnoseQualifiedDeclaration(
5768               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5769               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5770         if (DC->isRecord())
5771           return nullptr;
5772 
5773         D.setInvalidType();
5774       }
5775     }
5776 
5777     // Check whether we need to rebuild the type of the given
5778     // declaration in the current instantiation.
5779     if (EnteringContext && IsDependentContext &&
5780         TemplateParamLists.size() != 0) {
5781       ContextRAII SavedContext(*this, DC);
5782       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5783         D.setInvalidType();
5784     }
5785   }
5786 
5787   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5788   QualType R = TInfo->getType();
5789 
5790   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5791                                       UPPC_DeclarationType))
5792     D.setInvalidType();
5793 
5794   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5795                         forRedeclarationInCurContext());
5796 
5797   // See if this is a redefinition of a variable in the same scope.
5798   if (!D.getCXXScopeSpec().isSet()) {
5799     bool IsLinkageLookup = false;
5800     bool CreateBuiltins = false;
5801 
5802     // If the declaration we're planning to build will be a function
5803     // or object with linkage, then look for another declaration with
5804     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5805     //
5806     // If the declaration we're planning to build will be declared with
5807     // external linkage in the translation unit, create any builtin with
5808     // the same name.
5809     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5810       /* Do nothing*/;
5811     else if (CurContext->isFunctionOrMethod() &&
5812              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5813               R->isFunctionType())) {
5814       IsLinkageLookup = true;
5815       CreateBuiltins =
5816           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5817     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5818                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5819       CreateBuiltins = true;
5820 
5821     if (IsLinkageLookup) {
5822       Previous.clear(LookupRedeclarationWithLinkage);
5823       Previous.setRedeclarationKind(ForExternalRedeclaration);
5824     }
5825 
5826     LookupName(Previous, S, CreateBuiltins);
5827   } else { // Something like "int foo::x;"
5828     LookupQualifiedName(Previous, DC);
5829 
5830     // C++ [dcl.meaning]p1:
5831     //   When the declarator-id is qualified, the declaration shall refer to a
5832     //  previously declared member of the class or namespace to which the
5833     //  qualifier refers (or, in the case of a namespace, of an element of the
5834     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5835     //  thereof; [...]
5836     //
5837     // Note that we already checked the context above, and that we do not have
5838     // enough information to make sure that Previous contains the declaration
5839     // we want to match. For example, given:
5840     //
5841     //   class X {
5842     //     void f();
5843     //     void f(float);
5844     //   };
5845     //
5846     //   void X::f(int) { } // ill-formed
5847     //
5848     // In this case, Previous will point to the overload set
5849     // containing the two f's declared in X, but neither of them
5850     // matches.
5851 
5852     // C++ [dcl.meaning]p1:
5853     //   [...] the member shall not merely have been introduced by a
5854     //   using-declaration in the scope of the class or namespace nominated by
5855     //   the nested-name-specifier of the declarator-id.
5856     RemoveUsingDecls(Previous);
5857   }
5858 
5859   if (Previous.isSingleResult() &&
5860       Previous.getFoundDecl()->isTemplateParameter()) {
5861     // Maybe we will complain about the shadowed template parameter.
5862     if (!D.isInvalidType())
5863       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5864                                       Previous.getFoundDecl());
5865 
5866     // Just pretend that we didn't see the previous declaration.
5867     Previous.clear();
5868   }
5869 
5870   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5871     // Forget that the previous declaration is the injected-class-name.
5872     Previous.clear();
5873 
5874   // In C++, the previous declaration we find might be a tag type
5875   // (class or enum). In this case, the new declaration will hide the
5876   // tag type. Note that this applies to functions, function templates, and
5877   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5878   if (Previous.isSingleTagDecl() &&
5879       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5880       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5881     Previous.clear();
5882 
5883   // Check that there are no default arguments other than in the parameters
5884   // of a function declaration (C++ only).
5885   if (getLangOpts().CPlusPlus)
5886     CheckExtraCXXDefaultArguments(D);
5887 
5888   NamedDecl *New;
5889 
5890   bool AddToScope = true;
5891   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5892     if (TemplateParamLists.size()) {
5893       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5894       return nullptr;
5895     }
5896 
5897     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5898   } else if (R->isFunctionType()) {
5899     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5900                                   TemplateParamLists,
5901                                   AddToScope);
5902   } else {
5903     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5904                                   AddToScope);
5905   }
5906 
5907   if (!New)
5908     return nullptr;
5909 
5910   // If this has an identifier and is not a function template specialization,
5911   // add it to the scope stack.
5912   if (New->getDeclName() && AddToScope)
5913     PushOnScopeChains(New, S);
5914 
5915   if (isInOpenMPDeclareTargetContext())
5916     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5917 
5918   return New;
5919 }
5920 
5921 /// Helper method to turn variable array types into constant array
5922 /// types in certain situations which would otherwise be errors (for
5923 /// GCC compatibility).
5924 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5925                                                     ASTContext &Context,
5926                                                     bool &SizeIsNegative,
5927                                                     llvm::APSInt &Oversized) {
5928   // This method tries to turn a variable array into a constant
5929   // array even when the size isn't an ICE.  This is necessary
5930   // for compatibility with code that depends on gcc's buggy
5931   // constant expression folding, like struct {char x[(int)(char*)2];}
5932   SizeIsNegative = false;
5933   Oversized = 0;
5934 
5935   if (T->isDependentType())
5936     return QualType();
5937 
5938   QualifierCollector Qs;
5939   const Type *Ty = Qs.strip(T);
5940 
5941   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5942     QualType Pointee = PTy->getPointeeType();
5943     QualType FixedType =
5944         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5945                                             Oversized);
5946     if (FixedType.isNull()) return FixedType;
5947     FixedType = Context.getPointerType(FixedType);
5948     return Qs.apply(Context, FixedType);
5949   }
5950   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5951     QualType Inner = PTy->getInnerType();
5952     QualType FixedType =
5953         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5954                                             Oversized);
5955     if (FixedType.isNull()) return FixedType;
5956     FixedType = Context.getParenType(FixedType);
5957     return Qs.apply(Context, FixedType);
5958   }
5959 
5960   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5961   if (!VLATy)
5962     return QualType();
5963   // FIXME: We should probably handle this case
5964   if (VLATy->getElementType()->isVariablyModifiedType())
5965     return QualType();
5966 
5967   Expr::EvalResult Result;
5968   if (!VLATy->getSizeExpr() ||
5969       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5970     return QualType();
5971 
5972   llvm::APSInt Res = Result.Val.getInt();
5973 
5974   // Check whether the array size is negative.
5975   if (Res.isSigned() && Res.isNegative()) {
5976     SizeIsNegative = true;
5977     return QualType();
5978   }
5979 
5980   // Check whether the array is too large to be addressed.
5981   unsigned ActiveSizeBits
5982     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5983                                               Res);
5984   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5985     Oversized = Res;
5986     return QualType();
5987   }
5988 
5989   return Context.getConstantArrayType(
5990       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5991 }
5992 
5993 static void
5994 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5995   SrcTL = SrcTL.getUnqualifiedLoc();
5996   DstTL = DstTL.getUnqualifiedLoc();
5997   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5998     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5999     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6000                                       DstPTL.getPointeeLoc());
6001     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6002     return;
6003   }
6004   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6005     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6006     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6007                                       DstPTL.getInnerLoc());
6008     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6009     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6010     return;
6011   }
6012   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6013   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6014   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6015   TypeLoc DstElemTL = DstATL.getElementLoc();
6016   DstElemTL.initializeFullCopy(SrcElemTL);
6017   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6018   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6019   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6020 }
6021 
6022 /// Helper method to turn variable array types into constant array
6023 /// types in certain situations which would otherwise be errors (for
6024 /// GCC compatibility).
6025 static TypeSourceInfo*
6026 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6027                                               ASTContext &Context,
6028                                               bool &SizeIsNegative,
6029                                               llvm::APSInt &Oversized) {
6030   QualType FixedTy
6031     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6032                                           SizeIsNegative, Oversized);
6033   if (FixedTy.isNull())
6034     return nullptr;
6035   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6036   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6037                                     FixedTInfo->getTypeLoc());
6038   return FixedTInfo;
6039 }
6040 
6041 /// Register the given locally-scoped extern "C" declaration so
6042 /// that it can be found later for redeclarations. We include any extern "C"
6043 /// declaration that is not visible in the translation unit here, not just
6044 /// function-scope declarations.
6045 void
6046 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6047   if (!getLangOpts().CPlusPlus &&
6048       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6049     // Don't need to track declarations in the TU in C.
6050     return;
6051 
6052   // Note that we have a locally-scoped external with this name.
6053   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6054 }
6055 
6056 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6057   // FIXME: We can have multiple results via __attribute__((overloadable)).
6058   auto Result = Context.getExternCContextDecl()->lookup(Name);
6059   return Result.empty() ? nullptr : *Result.begin();
6060 }
6061 
6062 /// Diagnose function specifiers on a declaration of an identifier that
6063 /// does not identify a function.
6064 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6065   // FIXME: We should probably indicate the identifier in question to avoid
6066   // confusion for constructs like "virtual int a(), b;"
6067   if (DS.isVirtualSpecified())
6068     Diag(DS.getVirtualSpecLoc(),
6069          diag::err_virtual_non_function);
6070 
6071   if (DS.hasExplicitSpecifier())
6072     Diag(DS.getExplicitSpecLoc(),
6073          diag::err_explicit_non_function);
6074 
6075   if (DS.isNoreturnSpecified())
6076     Diag(DS.getNoreturnSpecLoc(),
6077          diag::err_noreturn_non_function);
6078 }
6079 
6080 NamedDecl*
6081 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6082                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6083   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6084   if (D.getCXXScopeSpec().isSet()) {
6085     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6086       << D.getCXXScopeSpec().getRange();
6087     D.setInvalidType();
6088     // Pretend we didn't see the scope specifier.
6089     DC = CurContext;
6090     Previous.clear();
6091   }
6092 
6093   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6094 
6095   if (D.getDeclSpec().isInlineSpecified())
6096     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6097         << getLangOpts().CPlusPlus17;
6098   if (D.getDeclSpec().hasConstexprSpecifier())
6099     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6100         << 1 << D.getDeclSpec().getConstexprSpecifier();
6101 
6102   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6103     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6104       Diag(D.getName().StartLocation,
6105            diag::err_deduction_guide_invalid_specifier)
6106           << "typedef";
6107     else
6108       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6109           << D.getName().getSourceRange();
6110     return nullptr;
6111   }
6112 
6113   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6114   if (!NewTD) return nullptr;
6115 
6116   // Handle attributes prior to checking for duplicates in MergeVarDecl
6117   ProcessDeclAttributes(S, NewTD, D);
6118 
6119   CheckTypedefForVariablyModifiedType(S, NewTD);
6120 
6121   bool Redeclaration = D.isRedeclaration();
6122   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6123   D.setRedeclaration(Redeclaration);
6124   return ND;
6125 }
6126 
6127 void
6128 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6129   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6130   // then it shall have block scope.
6131   // Note that variably modified types must be fixed before merging the decl so
6132   // that redeclarations will match.
6133   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6134   QualType T = TInfo->getType();
6135   if (T->isVariablyModifiedType()) {
6136     setFunctionHasBranchProtectedScope();
6137 
6138     if (S->getFnParent() == nullptr) {
6139       bool SizeIsNegative;
6140       llvm::APSInt Oversized;
6141       TypeSourceInfo *FixedTInfo =
6142         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6143                                                       SizeIsNegative,
6144                                                       Oversized);
6145       if (FixedTInfo) {
6146         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6147         NewTD->setTypeSourceInfo(FixedTInfo);
6148       } else {
6149         if (SizeIsNegative)
6150           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6151         else if (T->isVariableArrayType())
6152           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6153         else if (Oversized.getBoolValue())
6154           Diag(NewTD->getLocation(), diag::err_array_too_large)
6155             << Oversized.toString(10);
6156         else
6157           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6158         NewTD->setInvalidDecl();
6159       }
6160     }
6161   }
6162 }
6163 
6164 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6165 /// declares a typedef-name, either using the 'typedef' type specifier or via
6166 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6167 NamedDecl*
6168 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6169                            LookupResult &Previous, bool &Redeclaration) {
6170 
6171   // Find the shadowed declaration before filtering for scope.
6172   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6173 
6174   // Merge the decl with the existing one if appropriate. If the decl is
6175   // in an outer scope, it isn't the same thing.
6176   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6177                        /*AllowInlineNamespace*/false);
6178   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6179   if (!Previous.empty()) {
6180     Redeclaration = true;
6181     MergeTypedefNameDecl(S, NewTD, Previous);
6182   } else {
6183     inferGslPointerAttribute(NewTD);
6184   }
6185 
6186   if (ShadowedDecl && !Redeclaration)
6187     CheckShadow(NewTD, ShadowedDecl, Previous);
6188 
6189   // If this is the C FILE type, notify the AST context.
6190   if (IdentifierInfo *II = NewTD->getIdentifier())
6191     if (!NewTD->isInvalidDecl() &&
6192         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6193       if (II->isStr("FILE"))
6194         Context.setFILEDecl(NewTD);
6195       else if (II->isStr("jmp_buf"))
6196         Context.setjmp_bufDecl(NewTD);
6197       else if (II->isStr("sigjmp_buf"))
6198         Context.setsigjmp_bufDecl(NewTD);
6199       else if (II->isStr("ucontext_t"))
6200         Context.setucontext_tDecl(NewTD);
6201     }
6202 
6203   return NewTD;
6204 }
6205 
6206 /// Determines whether the given declaration is an out-of-scope
6207 /// previous declaration.
6208 ///
6209 /// This routine should be invoked when name lookup has found a
6210 /// previous declaration (PrevDecl) that is not in the scope where a
6211 /// new declaration by the same name is being introduced. If the new
6212 /// declaration occurs in a local scope, previous declarations with
6213 /// linkage may still be considered previous declarations (C99
6214 /// 6.2.2p4-5, C++ [basic.link]p6).
6215 ///
6216 /// \param PrevDecl the previous declaration found by name
6217 /// lookup
6218 ///
6219 /// \param DC the context in which the new declaration is being
6220 /// declared.
6221 ///
6222 /// \returns true if PrevDecl is an out-of-scope previous declaration
6223 /// for a new delcaration with the same name.
6224 static bool
6225 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6226                                 ASTContext &Context) {
6227   if (!PrevDecl)
6228     return false;
6229 
6230   if (!PrevDecl->hasLinkage())
6231     return false;
6232 
6233   if (Context.getLangOpts().CPlusPlus) {
6234     // C++ [basic.link]p6:
6235     //   If there is a visible declaration of an entity with linkage
6236     //   having the same name and type, ignoring entities declared
6237     //   outside the innermost enclosing namespace scope, the block
6238     //   scope declaration declares that same entity and receives the
6239     //   linkage of the previous declaration.
6240     DeclContext *OuterContext = DC->getRedeclContext();
6241     if (!OuterContext->isFunctionOrMethod())
6242       // This rule only applies to block-scope declarations.
6243       return false;
6244 
6245     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6246     if (PrevOuterContext->isRecord())
6247       // We found a member function: ignore it.
6248       return false;
6249 
6250     // Find the innermost enclosing namespace for the new and
6251     // previous declarations.
6252     OuterContext = OuterContext->getEnclosingNamespaceContext();
6253     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6254 
6255     // The previous declaration is in a different namespace, so it
6256     // isn't the same function.
6257     if (!OuterContext->Equals(PrevOuterContext))
6258       return false;
6259   }
6260 
6261   return true;
6262 }
6263 
6264 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6265   CXXScopeSpec &SS = D.getCXXScopeSpec();
6266   if (!SS.isSet()) return;
6267   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6268 }
6269 
6270 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6271   QualType type = decl->getType();
6272   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6273   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6274     // Various kinds of declaration aren't allowed to be __autoreleasing.
6275     unsigned kind = -1U;
6276     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6277       if (var->hasAttr<BlocksAttr>())
6278         kind = 0; // __block
6279       else if (!var->hasLocalStorage())
6280         kind = 1; // global
6281     } else if (isa<ObjCIvarDecl>(decl)) {
6282       kind = 3; // ivar
6283     } else if (isa<FieldDecl>(decl)) {
6284       kind = 2; // field
6285     }
6286 
6287     if (kind != -1U) {
6288       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6289         << kind;
6290     }
6291   } else if (lifetime == Qualifiers::OCL_None) {
6292     // Try to infer lifetime.
6293     if (!type->isObjCLifetimeType())
6294       return false;
6295 
6296     lifetime = type->getObjCARCImplicitLifetime();
6297     type = Context.getLifetimeQualifiedType(type, lifetime);
6298     decl->setType(type);
6299   }
6300 
6301   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6302     // Thread-local variables cannot have lifetime.
6303     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6304         var->getTLSKind()) {
6305       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6306         << var->getType();
6307       return true;
6308     }
6309   }
6310 
6311   return false;
6312 }
6313 
6314 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6315   if (Decl->getType().hasAddressSpace())
6316     return;
6317   if (Decl->getType()->isDependentType())
6318     return;
6319   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6320     QualType Type = Var->getType();
6321     if (Type->isSamplerT() || Type->isVoidType())
6322       return;
6323     LangAS ImplAS = LangAS::opencl_private;
6324     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6325         Var->hasGlobalStorage())
6326       ImplAS = LangAS::opencl_global;
6327     // If the original type from a decayed type is an array type and that array
6328     // type has no address space yet, deduce it now.
6329     if (auto DT = dyn_cast<DecayedType>(Type)) {
6330       auto OrigTy = DT->getOriginalType();
6331       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6332         // Add the address space to the original array type and then propagate
6333         // that to the element type through `getAsArrayType`.
6334         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6335         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6336         // Re-generate the decayed type.
6337         Type = Context.getDecayedType(OrigTy);
6338       }
6339     }
6340     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6341     // Apply any qualifiers (including address space) from the array type to
6342     // the element type. This implements C99 6.7.3p8: "If the specification of
6343     // an array type includes any type qualifiers, the element type is so
6344     // qualified, not the array type."
6345     if (Type->isArrayType())
6346       Type = QualType(Context.getAsArrayType(Type), 0);
6347     Decl->setType(Type);
6348   }
6349 }
6350 
6351 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6352   // Ensure that an auto decl is deduced otherwise the checks below might cache
6353   // the wrong linkage.
6354   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6355 
6356   // 'weak' only applies to declarations with external linkage.
6357   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6358     if (!ND.isExternallyVisible()) {
6359       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6360       ND.dropAttr<WeakAttr>();
6361     }
6362   }
6363   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6364     if (ND.isExternallyVisible()) {
6365       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6366       ND.dropAttr<WeakRefAttr>();
6367       ND.dropAttr<AliasAttr>();
6368     }
6369   }
6370 
6371   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6372     if (VD->hasInit()) {
6373       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6374         assert(VD->isThisDeclarationADefinition() &&
6375                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6376         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6377         VD->dropAttr<AliasAttr>();
6378       }
6379     }
6380   }
6381 
6382   // 'selectany' only applies to externally visible variable declarations.
6383   // It does not apply to functions.
6384   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6385     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6386       S.Diag(Attr->getLocation(),
6387              diag::err_attribute_selectany_non_extern_data);
6388       ND.dropAttr<SelectAnyAttr>();
6389     }
6390   }
6391 
6392   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6393     auto *VD = dyn_cast<VarDecl>(&ND);
6394     bool IsAnonymousNS = false;
6395     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6396     if (VD) {
6397       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6398       while (NS && !IsAnonymousNS) {
6399         IsAnonymousNS = NS->isAnonymousNamespace();
6400         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6401       }
6402     }
6403     // dll attributes require external linkage. Static locals may have external
6404     // linkage but still cannot be explicitly imported or exported.
6405     // In Microsoft mode, a variable defined in anonymous namespace must have
6406     // external linkage in order to be exported.
6407     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6408     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6409         (!AnonNSInMicrosoftMode &&
6410          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6411       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6412         << &ND << Attr;
6413       ND.setInvalidDecl();
6414     }
6415   }
6416 
6417   // Virtual functions cannot be marked as 'notail'.
6418   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6419     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6420       if (MD->isVirtual()) {
6421         S.Diag(ND.getLocation(),
6422                diag::err_invalid_attribute_on_virtual_function)
6423             << Attr;
6424         ND.dropAttr<NotTailCalledAttr>();
6425       }
6426 
6427   // Check the attributes on the function type, if any.
6428   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6429     // Don't declare this variable in the second operand of the for-statement;
6430     // GCC miscompiles that by ending its lifetime before evaluating the
6431     // third operand. See gcc.gnu.org/PR86769.
6432     AttributedTypeLoc ATL;
6433     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6434          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6435          TL = ATL.getModifiedLoc()) {
6436       // The [[lifetimebound]] attribute can be applied to the implicit object
6437       // parameter of a non-static member function (other than a ctor or dtor)
6438       // by applying it to the function type.
6439       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6440         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6441         if (!MD || MD->isStatic()) {
6442           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6443               << !MD << A->getRange();
6444         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6445           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6446               << isa<CXXDestructorDecl>(MD) << A->getRange();
6447         }
6448       }
6449     }
6450   }
6451 }
6452 
6453 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6454                                            NamedDecl *NewDecl,
6455                                            bool IsSpecialization,
6456                                            bool IsDefinition) {
6457   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6458     return;
6459 
6460   bool IsTemplate = false;
6461   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6462     OldDecl = OldTD->getTemplatedDecl();
6463     IsTemplate = true;
6464     if (!IsSpecialization)
6465       IsDefinition = false;
6466   }
6467   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6468     NewDecl = NewTD->getTemplatedDecl();
6469     IsTemplate = true;
6470   }
6471 
6472   if (!OldDecl || !NewDecl)
6473     return;
6474 
6475   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6476   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6477   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6478   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6479 
6480   // dllimport and dllexport are inheritable attributes so we have to exclude
6481   // inherited attribute instances.
6482   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6483                     (NewExportAttr && !NewExportAttr->isInherited());
6484 
6485   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6486   // the only exception being explicit specializations.
6487   // Implicitly generated declarations are also excluded for now because there
6488   // is no other way to switch these to use dllimport or dllexport.
6489   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6490 
6491   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6492     // Allow with a warning for free functions and global variables.
6493     bool JustWarn = false;
6494     if (!OldDecl->isCXXClassMember()) {
6495       auto *VD = dyn_cast<VarDecl>(OldDecl);
6496       if (VD && !VD->getDescribedVarTemplate())
6497         JustWarn = true;
6498       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6499       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6500         JustWarn = true;
6501     }
6502 
6503     // We cannot change a declaration that's been used because IR has already
6504     // been emitted. Dllimported functions will still work though (modulo
6505     // address equality) as they can use the thunk.
6506     if (OldDecl->isUsed())
6507       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6508         JustWarn = false;
6509 
6510     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6511                                : diag::err_attribute_dll_redeclaration;
6512     S.Diag(NewDecl->getLocation(), DiagID)
6513         << NewDecl
6514         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6515     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6516     if (!JustWarn) {
6517       NewDecl->setInvalidDecl();
6518       return;
6519     }
6520   }
6521 
6522   // A redeclaration is not allowed to drop a dllimport attribute, the only
6523   // exceptions being inline function definitions (except for function
6524   // templates), local extern declarations, qualified friend declarations or
6525   // special MSVC extension: in the last case, the declaration is treated as if
6526   // it were marked dllexport.
6527   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6528   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6529   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6530     // Ignore static data because out-of-line definitions are diagnosed
6531     // separately.
6532     IsStaticDataMember = VD->isStaticDataMember();
6533     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6534                    VarDecl::DeclarationOnly;
6535   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6536     IsInline = FD->isInlined();
6537     IsQualifiedFriend = FD->getQualifier() &&
6538                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6539   }
6540 
6541   if (OldImportAttr && !HasNewAttr &&
6542       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6543       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6544     if (IsMicrosoft && IsDefinition) {
6545       S.Diag(NewDecl->getLocation(),
6546              diag::warn_redeclaration_without_import_attribute)
6547           << NewDecl;
6548       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6549       NewDecl->dropAttr<DLLImportAttr>();
6550       NewDecl->addAttr(
6551           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6552     } else {
6553       S.Diag(NewDecl->getLocation(),
6554              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6555           << NewDecl << OldImportAttr;
6556       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6557       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6558       OldDecl->dropAttr<DLLImportAttr>();
6559       NewDecl->dropAttr<DLLImportAttr>();
6560     }
6561   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6562     // In MinGW, seeing a function declared inline drops the dllimport
6563     // attribute.
6564     OldDecl->dropAttr<DLLImportAttr>();
6565     NewDecl->dropAttr<DLLImportAttr>();
6566     S.Diag(NewDecl->getLocation(),
6567            diag::warn_dllimport_dropped_from_inline_function)
6568         << NewDecl << OldImportAttr;
6569   }
6570 
6571   // A specialization of a class template member function is processed here
6572   // since it's a redeclaration. If the parent class is dllexport, the
6573   // specialization inherits that attribute. This doesn't happen automatically
6574   // since the parent class isn't instantiated until later.
6575   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6576     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6577         !NewImportAttr && !NewExportAttr) {
6578       if (const DLLExportAttr *ParentExportAttr =
6579               MD->getParent()->getAttr<DLLExportAttr>()) {
6580         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6581         NewAttr->setInherited(true);
6582         NewDecl->addAttr(NewAttr);
6583       }
6584     }
6585   }
6586 }
6587 
6588 /// Given that we are within the definition of the given function,
6589 /// will that definition behave like C99's 'inline', where the
6590 /// definition is discarded except for optimization purposes?
6591 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6592   // Try to avoid calling GetGVALinkageForFunction.
6593 
6594   // All cases of this require the 'inline' keyword.
6595   if (!FD->isInlined()) return false;
6596 
6597   // This is only possible in C++ with the gnu_inline attribute.
6598   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6599     return false;
6600 
6601   // Okay, go ahead and call the relatively-more-expensive function.
6602   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6603 }
6604 
6605 /// Determine whether a variable is extern "C" prior to attaching
6606 /// an initializer. We can't just call isExternC() here, because that
6607 /// will also compute and cache whether the declaration is externally
6608 /// visible, which might change when we attach the initializer.
6609 ///
6610 /// This can only be used if the declaration is known to not be a
6611 /// redeclaration of an internal linkage declaration.
6612 ///
6613 /// For instance:
6614 ///
6615 ///   auto x = []{};
6616 ///
6617 /// Attaching the initializer here makes this declaration not externally
6618 /// visible, because its type has internal linkage.
6619 ///
6620 /// FIXME: This is a hack.
6621 template<typename T>
6622 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6623   if (S.getLangOpts().CPlusPlus) {
6624     // In C++, the overloadable attribute negates the effects of extern "C".
6625     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6626       return false;
6627 
6628     // So do CUDA's host/device attributes.
6629     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6630                                  D->template hasAttr<CUDAHostAttr>()))
6631       return false;
6632   }
6633   return D->isExternC();
6634 }
6635 
6636 static bool shouldConsiderLinkage(const VarDecl *VD) {
6637   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6638   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6639       isa<OMPDeclareMapperDecl>(DC))
6640     return VD->hasExternalStorage();
6641   if (DC->isFileContext())
6642     return true;
6643   if (DC->isRecord())
6644     return false;
6645   if (isa<RequiresExprBodyDecl>(DC))
6646     return false;
6647   llvm_unreachable("Unexpected context");
6648 }
6649 
6650 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6651   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6652   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6653       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6654     return true;
6655   if (DC->isRecord())
6656     return false;
6657   llvm_unreachable("Unexpected context");
6658 }
6659 
6660 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6661                           ParsedAttr::Kind Kind) {
6662   // Check decl attributes on the DeclSpec.
6663   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6664     return true;
6665 
6666   // Walk the declarator structure, checking decl attributes that were in a type
6667   // position to the decl itself.
6668   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6669     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6670       return true;
6671   }
6672 
6673   // Finally, check attributes on the decl itself.
6674   return PD.getAttributes().hasAttribute(Kind);
6675 }
6676 
6677 /// Adjust the \c DeclContext for a function or variable that might be a
6678 /// function-local external declaration.
6679 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6680   if (!DC->isFunctionOrMethod())
6681     return false;
6682 
6683   // If this is a local extern function or variable declared within a function
6684   // template, don't add it into the enclosing namespace scope until it is
6685   // instantiated; it might have a dependent type right now.
6686   if (DC->isDependentContext())
6687     return true;
6688 
6689   // C++11 [basic.link]p7:
6690   //   When a block scope declaration of an entity with linkage is not found to
6691   //   refer to some other declaration, then that entity is a member of the
6692   //   innermost enclosing namespace.
6693   //
6694   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6695   // semantically-enclosing namespace, not a lexically-enclosing one.
6696   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6697     DC = DC->getParent();
6698   return true;
6699 }
6700 
6701 /// Returns true if given declaration has external C language linkage.
6702 static bool isDeclExternC(const Decl *D) {
6703   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6704     return FD->isExternC();
6705   if (const auto *VD = dyn_cast<VarDecl>(D))
6706     return VD->isExternC();
6707 
6708   llvm_unreachable("Unknown type of decl!");
6709 }
6710 /// Returns true if there hasn't been any invalid type diagnosed.
6711 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6712                                 DeclContext *DC, QualType R) {
6713   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6714   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6715   // argument.
6716   if (R->isImageType() || R->isPipeType()) {
6717     Se.Diag(D.getIdentifierLoc(),
6718             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6719         << R;
6720     D.setInvalidType();
6721     return false;
6722   }
6723 
6724   // OpenCL v1.2 s6.9.r:
6725   // The event type cannot be used to declare a program scope variable.
6726   // OpenCL v2.0 s6.9.q:
6727   // The clk_event_t and reserve_id_t types cannot be declared in program
6728   // scope.
6729   if (NULL == S->getParent()) {
6730     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6731       Se.Diag(D.getIdentifierLoc(),
6732               diag::err_invalid_type_for_program_scope_var)
6733           << R;
6734       D.setInvalidType();
6735       return false;
6736     }
6737   }
6738 
6739   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6740   QualType NR = R;
6741   while (NR->isPointerType()) {
6742     if (NR->isFunctionPointerType()) {
6743       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6744       D.setInvalidType();
6745       return false;
6746     }
6747     NR = NR->getPointeeType();
6748   }
6749 
6750   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6751     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6752     // half array type (unless the cl_khr_fp16 extension is enabled).
6753     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6754       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6755       D.setInvalidType();
6756       return false;
6757     }
6758   }
6759 
6760   // OpenCL v1.2 s6.9.r:
6761   // The event type cannot be used with the __local, __constant and __global
6762   // address space qualifiers.
6763   if (R->isEventT()) {
6764     if (R.getAddressSpace() != LangAS::opencl_private) {
6765       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6766       D.setInvalidType();
6767       return false;
6768     }
6769   }
6770 
6771   // C++ for OpenCL does not allow the thread_local storage qualifier.
6772   // OpenCL C does not support thread_local either, and
6773   // also reject all other thread storage class specifiers.
6774   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6775   if (TSC != TSCS_unspecified) {
6776     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6777     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6778             diag::err_opencl_unknown_type_specifier)
6779         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6780         << DeclSpec::getSpecifierName(TSC) << 1;
6781     D.setInvalidType();
6782     return false;
6783   }
6784 
6785   if (R->isSamplerT()) {
6786     // OpenCL v1.2 s6.9.b p4:
6787     // The sampler type cannot be used with the __local and __global address
6788     // space qualifiers.
6789     if (R.getAddressSpace() == LangAS::opencl_local ||
6790         R.getAddressSpace() == LangAS::opencl_global) {
6791       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6792       D.setInvalidType();
6793     }
6794 
6795     // OpenCL v1.2 s6.12.14.1:
6796     // A global sampler must be declared with either the constant address
6797     // space qualifier or with the const qualifier.
6798     if (DC->isTranslationUnit() &&
6799         !(R.getAddressSpace() == LangAS::opencl_constant ||
6800           R.isConstQualified())) {
6801       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6802       D.setInvalidType();
6803     }
6804     if (D.isInvalidType())
6805       return false;
6806   }
6807   return true;
6808 }
6809 
6810 NamedDecl *Sema::ActOnVariableDeclarator(
6811     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6812     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6813     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6814   QualType R = TInfo->getType();
6815   DeclarationName Name = GetNameForDeclarator(D).getName();
6816 
6817   IdentifierInfo *II = Name.getAsIdentifierInfo();
6818 
6819   if (D.isDecompositionDeclarator()) {
6820     // Take the name of the first declarator as our name for diagnostic
6821     // purposes.
6822     auto &Decomp = D.getDecompositionDeclarator();
6823     if (!Decomp.bindings().empty()) {
6824       II = Decomp.bindings()[0].Name;
6825       Name = II;
6826     }
6827   } else if (!II) {
6828     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6829     return nullptr;
6830   }
6831 
6832 
6833   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6834   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6835 
6836   // dllimport globals without explicit storage class are treated as extern. We
6837   // have to change the storage class this early to get the right DeclContext.
6838   if (SC == SC_None && !DC->isRecord() &&
6839       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6840       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6841     SC = SC_Extern;
6842 
6843   DeclContext *OriginalDC = DC;
6844   bool IsLocalExternDecl = SC == SC_Extern &&
6845                            adjustContextForLocalExternDecl(DC);
6846 
6847   if (SCSpec == DeclSpec::SCS_mutable) {
6848     // mutable can only appear on non-static class members, so it's always
6849     // an error here
6850     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6851     D.setInvalidType();
6852     SC = SC_None;
6853   }
6854 
6855   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6856       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6857                               D.getDeclSpec().getStorageClassSpecLoc())) {
6858     // In C++11, the 'register' storage class specifier is deprecated.
6859     // Suppress the warning in system macros, it's used in macros in some
6860     // popular C system headers, such as in glibc's htonl() macro.
6861     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6862          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6863                                    : diag::warn_deprecated_register)
6864       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6865   }
6866 
6867   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6868 
6869   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6870     // C99 6.9p2: The storage-class specifiers auto and register shall not
6871     // appear in the declaration specifiers in an external declaration.
6872     // Global Register+Asm is a GNU extension we support.
6873     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6874       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6875       D.setInvalidType();
6876     }
6877   }
6878 
6879   bool IsMemberSpecialization = false;
6880   bool IsVariableTemplateSpecialization = false;
6881   bool IsPartialSpecialization = false;
6882   bool IsVariableTemplate = false;
6883   VarDecl *NewVD = nullptr;
6884   VarTemplateDecl *NewTemplate = nullptr;
6885   TemplateParameterList *TemplateParams = nullptr;
6886   if (!getLangOpts().CPlusPlus) {
6887     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6888                             II, R, TInfo, SC);
6889 
6890     if (R->getContainedDeducedType())
6891       ParsingInitForAutoVars.insert(NewVD);
6892 
6893     if (D.isInvalidType())
6894       NewVD->setInvalidDecl();
6895 
6896     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6897         NewVD->hasLocalStorage())
6898       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6899                             NTCUC_AutoVar, NTCUK_Destruct);
6900   } else {
6901     bool Invalid = false;
6902 
6903     if (DC->isRecord() && !CurContext->isRecord()) {
6904       // This is an out-of-line definition of a static data member.
6905       switch (SC) {
6906       case SC_None:
6907         break;
6908       case SC_Static:
6909         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6910              diag::err_static_out_of_line)
6911           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6912         break;
6913       case SC_Auto:
6914       case SC_Register:
6915       case SC_Extern:
6916         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6917         // to names of variables declared in a block or to function parameters.
6918         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6919         // of class members
6920 
6921         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6922              diag::err_storage_class_for_static_member)
6923           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6924         break;
6925       case SC_PrivateExtern:
6926         llvm_unreachable("C storage class in c++!");
6927       }
6928     }
6929 
6930     if (SC == SC_Static && CurContext->isRecord()) {
6931       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6932         // Walk up the enclosing DeclContexts to check for any that are
6933         // incompatible with static data members.
6934         const DeclContext *FunctionOrMethod = nullptr;
6935         const CXXRecordDecl *AnonStruct = nullptr;
6936         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6937           if (Ctxt->isFunctionOrMethod()) {
6938             FunctionOrMethod = Ctxt;
6939             break;
6940           }
6941           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6942           if (ParentDecl && !ParentDecl->getDeclName()) {
6943             AnonStruct = ParentDecl;
6944             break;
6945           }
6946         }
6947         if (FunctionOrMethod) {
6948           // C++ [class.static.data]p5: A local class shall not have static data
6949           // members.
6950           Diag(D.getIdentifierLoc(),
6951                diag::err_static_data_member_not_allowed_in_local_class)
6952             << Name << RD->getDeclName() << RD->getTagKind();
6953         } else if (AnonStruct) {
6954           // C++ [class.static.data]p4: Unnamed classes and classes contained
6955           // directly or indirectly within unnamed classes shall not contain
6956           // static data members.
6957           Diag(D.getIdentifierLoc(),
6958                diag::err_static_data_member_not_allowed_in_anon_struct)
6959             << Name << AnonStruct->getTagKind();
6960           Invalid = true;
6961         } else if (RD->isUnion()) {
6962           // C++98 [class.union]p1: If a union contains a static data member,
6963           // the program is ill-formed. C++11 drops this restriction.
6964           Diag(D.getIdentifierLoc(),
6965                getLangOpts().CPlusPlus11
6966                  ? diag::warn_cxx98_compat_static_data_member_in_union
6967                  : diag::ext_static_data_member_in_union) << Name;
6968         }
6969       }
6970     }
6971 
6972     // Match up the template parameter lists with the scope specifier, then
6973     // determine whether we have a template or a template specialization.
6974     bool InvalidScope = false;
6975     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6976         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6977         D.getCXXScopeSpec(),
6978         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6979             ? D.getName().TemplateId
6980             : nullptr,
6981         TemplateParamLists,
6982         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6983     Invalid |= InvalidScope;
6984 
6985     if (TemplateParams) {
6986       if (!TemplateParams->size() &&
6987           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6988         // There is an extraneous 'template<>' for this variable. Complain
6989         // about it, but allow the declaration of the variable.
6990         Diag(TemplateParams->getTemplateLoc(),
6991              diag::err_template_variable_noparams)
6992           << II
6993           << SourceRange(TemplateParams->getTemplateLoc(),
6994                          TemplateParams->getRAngleLoc());
6995         TemplateParams = nullptr;
6996       } else {
6997         // Check that we can declare a template here.
6998         if (CheckTemplateDeclScope(S, TemplateParams))
6999           return nullptr;
7000 
7001         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7002           // This is an explicit specialization or a partial specialization.
7003           IsVariableTemplateSpecialization = true;
7004           IsPartialSpecialization = TemplateParams->size() > 0;
7005         } else { // if (TemplateParams->size() > 0)
7006           // This is a template declaration.
7007           IsVariableTemplate = true;
7008 
7009           // Only C++1y supports variable templates (N3651).
7010           Diag(D.getIdentifierLoc(),
7011                getLangOpts().CPlusPlus14
7012                    ? diag::warn_cxx11_compat_variable_template
7013                    : diag::ext_variable_template);
7014         }
7015       }
7016     } else {
7017       // Check that we can declare a member specialization here.
7018       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7019           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7020         return nullptr;
7021       assert((Invalid ||
7022               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7023              "should have a 'template<>' for this decl");
7024     }
7025 
7026     if (IsVariableTemplateSpecialization) {
7027       SourceLocation TemplateKWLoc =
7028           TemplateParamLists.size() > 0
7029               ? TemplateParamLists[0]->getTemplateLoc()
7030               : SourceLocation();
7031       DeclResult Res = ActOnVarTemplateSpecialization(
7032           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7033           IsPartialSpecialization);
7034       if (Res.isInvalid())
7035         return nullptr;
7036       NewVD = cast<VarDecl>(Res.get());
7037       AddToScope = false;
7038     } else if (D.isDecompositionDeclarator()) {
7039       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7040                                         D.getIdentifierLoc(), R, TInfo, SC,
7041                                         Bindings);
7042     } else
7043       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7044                               D.getIdentifierLoc(), II, R, TInfo, SC);
7045 
7046     // If this is supposed to be a variable template, create it as such.
7047     if (IsVariableTemplate) {
7048       NewTemplate =
7049           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7050                                   TemplateParams, NewVD);
7051       NewVD->setDescribedVarTemplate(NewTemplate);
7052     }
7053 
7054     // If this decl has an auto type in need of deduction, make a note of the
7055     // Decl so we can diagnose uses of it in its own initializer.
7056     if (R->getContainedDeducedType())
7057       ParsingInitForAutoVars.insert(NewVD);
7058 
7059     if (D.isInvalidType() || Invalid) {
7060       NewVD->setInvalidDecl();
7061       if (NewTemplate)
7062         NewTemplate->setInvalidDecl();
7063     }
7064 
7065     SetNestedNameSpecifier(*this, NewVD, D);
7066 
7067     // If we have any template parameter lists that don't directly belong to
7068     // the variable (matching the scope specifier), store them.
7069     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7070     if (TemplateParamLists.size() > VDTemplateParamLists)
7071       NewVD->setTemplateParameterListsInfo(
7072           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7073   }
7074 
7075   if (D.getDeclSpec().isInlineSpecified()) {
7076     if (!getLangOpts().CPlusPlus) {
7077       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7078           << 0;
7079     } else if (CurContext->isFunctionOrMethod()) {
7080       // 'inline' is not allowed on block scope variable declaration.
7081       Diag(D.getDeclSpec().getInlineSpecLoc(),
7082            diag::err_inline_declaration_block_scope) << Name
7083         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7084     } else {
7085       Diag(D.getDeclSpec().getInlineSpecLoc(),
7086            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7087                                      : diag::ext_inline_variable);
7088       NewVD->setInlineSpecified();
7089     }
7090   }
7091 
7092   // Set the lexical context. If the declarator has a C++ scope specifier, the
7093   // lexical context will be different from the semantic context.
7094   NewVD->setLexicalDeclContext(CurContext);
7095   if (NewTemplate)
7096     NewTemplate->setLexicalDeclContext(CurContext);
7097 
7098   if (IsLocalExternDecl) {
7099     if (D.isDecompositionDeclarator())
7100       for (auto *B : Bindings)
7101         B->setLocalExternDecl();
7102     else
7103       NewVD->setLocalExternDecl();
7104   }
7105 
7106   bool EmitTLSUnsupportedError = false;
7107   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7108     // C++11 [dcl.stc]p4:
7109     //   When thread_local is applied to a variable of block scope the
7110     //   storage-class-specifier static is implied if it does not appear
7111     //   explicitly.
7112     // Core issue: 'static' is not implied if the variable is declared
7113     //   'extern'.
7114     if (NewVD->hasLocalStorage() &&
7115         (SCSpec != DeclSpec::SCS_unspecified ||
7116          TSCS != DeclSpec::TSCS_thread_local ||
7117          !DC->isFunctionOrMethod()))
7118       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7119            diag::err_thread_non_global)
7120         << DeclSpec::getSpecifierName(TSCS);
7121     else if (!Context.getTargetInfo().isTLSSupported()) {
7122       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7123           getLangOpts().SYCLIsDevice) {
7124         // Postpone error emission until we've collected attributes required to
7125         // figure out whether it's a host or device variable and whether the
7126         // error should be ignored.
7127         EmitTLSUnsupportedError = true;
7128         // We still need to mark the variable as TLS so it shows up in AST with
7129         // proper storage class for other tools to use even if we're not going
7130         // to emit any code for it.
7131         NewVD->setTSCSpec(TSCS);
7132       } else
7133         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7134              diag::err_thread_unsupported);
7135     } else
7136       NewVD->setTSCSpec(TSCS);
7137   }
7138 
7139   switch (D.getDeclSpec().getConstexprSpecifier()) {
7140   case CSK_unspecified:
7141     break;
7142 
7143   case CSK_consteval:
7144     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7145         diag::err_constexpr_wrong_decl_kind)
7146       << D.getDeclSpec().getConstexprSpecifier();
7147     LLVM_FALLTHROUGH;
7148 
7149   case CSK_constexpr:
7150     NewVD->setConstexpr(true);
7151     MaybeAddCUDAConstantAttr(NewVD);
7152     // C++1z [dcl.spec.constexpr]p1:
7153     //   A static data member declared with the constexpr specifier is
7154     //   implicitly an inline variable.
7155     if (NewVD->isStaticDataMember() &&
7156         (getLangOpts().CPlusPlus17 ||
7157          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7158       NewVD->setImplicitlyInline();
7159     break;
7160 
7161   case CSK_constinit:
7162     if (!NewVD->hasGlobalStorage())
7163       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7164            diag::err_constinit_local_variable);
7165     else
7166       NewVD->addAttr(ConstInitAttr::Create(
7167           Context, D.getDeclSpec().getConstexprSpecLoc(),
7168           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7169     break;
7170   }
7171 
7172   // C99 6.7.4p3
7173   //   An inline definition of a function with external linkage shall
7174   //   not contain a definition of a modifiable object with static or
7175   //   thread storage duration...
7176   // We only apply this when the function is required to be defined
7177   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7178   // that a local variable with thread storage duration still has to
7179   // be marked 'static'.  Also note that it's possible to get these
7180   // semantics in C++ using __attribute__((gnu_inline)).
7181   if (SC == SC_Static && S->getFnParent() != nullptr &&
7182       !NewVD->getType().isConstQualified()) {
7183     FunctionDecl *CurFD = getCurFunctionDecl();
7184     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7185       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7186            diag::warn_static_local_in_extern_inline);
7187       MaybeSuggestAddingStaticToDecl(CurFD);
7188     }
7189   }
7190 
7191   if (D.getDeclSpec().isModulePrivateSpecified()) {
7192     if (IsVariableTemplateSpecialization)
7193       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7194           << (IsPartialSpecialization ? 1 : 0)
7195           << FixItHint::CreateRemoval(
7196                  D.getDeclSpec().getModulePrivateSpecLoc());
7197     else if (IsMemberSpecialization)
7198       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7199         << 2
7200         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7201     else if (NewVD->hasLocalStorage())
7202       Diag(NewVD->getLocation(), diag::err_module_private_local)
7203           << 0 << NewVD
7204           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7205           << FixItHint::CreateRemoval(
7206                  D.getDeclSpec().getModulePrivateSpecLoc());
7207     else {
7208       NewVD->setModulePrivate();
7209       if (NewTemplate)
7210         NewTemplate->setModulePrivate();
7211       for (auto *B : Bindings)
7212         B->setModulePrivate();
7213     }
7214   }
7215 
7216   if (getLangOpts().OpenCL) {
7217 
7218     deduceOpenCLAddressSpace(NewVD);
7219 
7220     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7221   }
7222 
7223   // Handle attributes prior to checking for duplicates in MergeVarDecl
7224   ProcessDeclAttributes(S, NewVD, D);
7225 
7226   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7227       getLangOpts().SYCLIsDevice) {
7228     if (EmitTLSUnsupportedError &&
7229         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7230          (getLangOpts().OpenMPIsDevice &&
7231           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7232       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7233            diag::err_thread_unsupported);
7234 
7235     if (EmitTLSUnsupportedError &&
7236         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7237       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7238     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7239     // storage [duration]."
7240     if (SC == SC_None && S->getFnParent() != nullptr &&
7241         (NewVD->hasAttr<CUDASharedAttr>() ||
7242          NewVD->hasAttr<CUDAConstantAttr>())) {
7243       NewVD->setStorageClass(SC_Static);
7244     }
7245   }
7246 
7247   // Ensure that dllimport globals without explicit storage class are treated as
7248   // extern. The storage class is set above using parsed attributes. Now we can
7249   // check the VarDecl itself.
7250   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7251          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7252          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7253 
7254   // In auto-retain/release, infer strong retension for variables of
7255   // retainable type.
7256   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7257     NewVD->setInvalidDecl();
7258 
7259   // Handle GNU asm-label extension (encoded as an attribute).
7260   if (Expr *E = (Expr*)D.getAsmLabel()) {
7261     // The parser guarantees this is a string.
7262     StringLiteral *SE = cast<StringLiteral>(E);
7263     StringRef Label = SE->getString();
7264     if (S->getFnParent() != nullptr) {
7265       switch (SC) {
7266       case SC_None:
7267       case SC_Auto:
7268         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7269         break;
7270       case SC_Register:
7271         // Local Named register
7272         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7273             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7274           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7275         break;
7276       case SC_Static:
7277       case SC_Extern:
7278       case SC_PrivateExtern:
7279         break;
7280       }
7281     } else if (SC == SC_Register) {
7282       // Global Named register
7283       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7284         const auto &TI = Context.getTargetInfo();
7285         bool HasSizeMismatch;
7286 
7287         if (!TI.isValidGCCRegisterName(Label))
7288           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7289         else if (!TI.validateGlobalRegisterVariable(Label,
7290                                                     Context.getTypeSize(R),
7291                                                     HasSizeMismatch))
7292           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7293         else if (HasSizeMismatch)
7294           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7295       }
7296 
7297       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7298         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7299         NewVD->setInvalidDecl(true);
7300       }
7301     }
7302 
7303     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7304                                         /*IsLiteralLabel=*/true,
7305                                         SE->getStrTokenLoc(0)));
7306   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7307     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7308       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7309     if (I != ExtnameUndeclaredIdentifiers.end()) {
7310       if (isDeclExternC(NewVD)) {
7311         NewVD->addAttr(I->second);
7312         ExtnameUndeclaredIdentifiers.erase(I);
7313       } else
7314         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7315             << /*Variable*/1 << NewVD;
7316     }
7317   }
7318 
7319   // Find the shadowed declaration before filtering for scope.
7320   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7321                                 ? getShadowedDeclaration(NewVD, Previous)
7322                                 : nullptr;
7323 
7324   // Don't consider existing declarations that are in a different
7325   // scope and are out-of-semantic-context declarations (if the new
7326   // declaration has linkage).
7327   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7328                        D.getCXXScopeSpec().isNotEmpty() ||
7329                        IsMemberSpecialization ||
7330                        IsVariableTemplateSpecialization);
7331 
7332   // Check whether the previous declaration is in the same block scope. This
7333   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7334   if (getLangOpts().CPlusPlus &&
7335       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7336     NewVD->setPreviousDeclInSameBlockScope(
7337         Previous.isSingleResult() && !Previous.isShadowed() &&
7338         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7339 
7340   if (!getLangOpts().CPlusPlus) {
7341     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7342   } else {
7343     // If this is an explicit specialization of a static data member, check it.
7344     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7345         CheckMemberSpecialization(NewVD, Previous))
7346       NewVD->setInvalidDecl();
7347 
7348     // Merge the decl with the existing one if appropriate.
7349     if (!Previous.empty()) {
7350       if (Previous.isSingleResult() &&
7351           isa<FieldDecl>(Previous.getFoundDecl()) &&
7352           D.getCXXScopeSpec().isSet()) {
7353         // The user tried to define a non-static data member
7354         // out-of-line (C++ [dcl.meaning]p1).
7355         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7356           << D.getCXXScopeSpec().getRange();
7357         Previous.clear();
7358         NewVD->setInvalidDecl();
7359       }
7360     } else if (D.getCXXScopeSpec().isSet()) {
7361       // No previous declaration in the qualifying scope.
7362       Diag(D.getIdentifierLoc(), diag::err_no_member)
7363         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7364         << D.getCXXScopeSpec().getRange();
7365       NewVD->setInvalidDecl();
7366     }
7367 
7368     if (!IsVariableTemplateSpecialization)
7369       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7370 
7371     if (NewTemplate) {
7372       VarTemplateDecl *PrevVarTemplate =
7373           NewVD->getPreviousDecl()
7374               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7375               : nullptr;
7376 
7377       // Check the template parameter list of this declaration, possibly
7378       // merging in the template parameter list from the previous variable
7379       // template declaration.
7380       if (CheckTemplateParameterList(
7381               TemplateParams,
7382               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7383                               : nullptr,
7384               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7385                DC->isDependentContext())
7386                   ? TPC_ClassTemplateMember
7387                   : TPC_VarTemplate))
7388         NewVD->setInvalidDecl();
7389 
7390       // If we are providing an explicit specialization of a static variable
7391       // template, make a note of that.
7392       if (PrevVarTemplate &&
7393           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7394         PrevVarTemplate->setMemberSpecialization();
7395     }
7396   }
7397 
7398   // Diagnose shadowed variables iff this isn't a redeclaration.
7399   if (ShadowedDecl && !D.isRedeclaration())
7400     CheckShadow(NewVD, ShadowedDecl, Previous);
7401 
7402   ProcessPragmaWeak(S, NewVD);
7403 
7404   // If this is the first declaration of an extern C variable, update
7405   // the map of such variables.
7406   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7407       isIncompleteDeclExternC(*this, NewVD))
7408     RegisterLocallyScopedExternCDecl(NewVD, S);
7409 
7410   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7411     MangleNumberingContext *MCtx;
7412     Decl *ManglingContextDecl;
7413     std::tie(MCtx, ManglingContextDecl) =
7414         getCurrentMangleNumberContext(NewVD->getDeclContext());
7415     if (MCtx) {
7416       Context.setManglingNumber(
7417           NewVD, MCtx->getManglingNumber(
7418                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7419       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7420     }
7421   }
7422 
7423   // Special handling of variable named 'main'.
7424   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7425       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7426       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7427 
7428     // C++ [basic.start.main]p3
7429     // A program that declares a variable main at global scope is ill-formed.
7430     if (getLangOpts().CPlusPlus)
7431       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7432 
7433     // In C, and external-linkage variable named main results in undefined
7434     // behavior.
7435     else if (NewVD->hasExternalFormalLinkage())
7436       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7437   }
7438 
7439   if (D.isRedeclaration() && !Previous.empty()) {
7440     NamedDecl *Prev = Previous.getRepresentativeDecl();
7441     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7442                                    D.isFunctionDefinition());
7443   }
7444 
7445   if (NewTemplate) {
7446     if (NewVD->isInvalidDecl())
7447       NewTemplate->setInvalidDecl();
7448     ActOnDocumentableDecl(NewTemplate);
7449     return NewTemplate;
7450   }
7451 
7452   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7453     CompleteMemberSpecialization(NewVD, Previous);
7454 
7455   return NewVD;
7456 }
7457 
7458 /// Enum describing the %select options in diag::warn_decl_shadow.
7459 enum ShadowedDeclKind {
7460   SDK_Local,
7461   SDK_Global,
7462   SDK_StaticMember,
7463   SDK_Field,
7464   SDK_Typedef,
7465   SDK_Using
7466 };
7467 
7468 /// Determine what kind of declaration we're shadowing.
7469 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7470                                                 const DeclContext *OldDC) {
7471   if (isa<TypeAliasDecl>(ShadowedDecl))
7472     return SDK_Using;
7473   else if (isa<TypedefDecl>(ShadowedDecl))
7474     return SDK_Typedef;
7475   else if (isa<RecordDecl>(OldDC))
7476     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7477 
7478   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7479 }
7480 
7481 /// Return the location of the capture if the given lambda captures the given
7482 /// variable \p VD, or an invalid source location otherwise.
7483 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7484                                          const VarDecl *VD) {
7485   for (const Capture &Capture : LSI->Captures) {
7486     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7487       return Capture.getLocation();
7488   }
7489   return SourceLocation();
7490 }
7491 
7492 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7493                                      const LookupResult &R) {
7494   // Only diagnose if we're shadowing an unambiguous field or variable.
7495   if (R.getResultKind() != LookupResult::Found)
7496     return false;
7497 
7498   // Return false if warning is ignored.
7499   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7500 }
7501 
7502 /// Return the declaration shadowed by the given variable \p D, or null
7503 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7504 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7505                                         const LookupResult &R) {
7506   if (!shouldWarnIfShadowedDecl(Diags, R))
7507     return nullptr;
7508 
7509   // Don't diagnose declarations at file scope.
7510   if (D->hasGlobalStorage())
7511     return nullptr;
7512 
7513   NamedDecl *ShadowedDecl = R.getFoundDecl();
7514   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7515              ? ShadowedDecl
7516              : nullptr;
7517 }
7518 
7519 /// Return the declaration shadowed by the given typedef \p D, or null
7520 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7521 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7522                                         const LookupResult &R) {
7523   // Don't warn if typedef declaration is part of a class
7524   if (D->getDeclContext()->isRecord())
7525     return nullptr;
7526 
7527   if (!shouldWarnIfShadowedDecl(Diags, R))
7528     return nullptr;
7529 
7530   NamedDecl *ShadowedDecl = R.getFoundDecl();
7531   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7532 }
7533 
7534 /// Diagnose variable or built-in function shadowing.  Implements
7535 /// -Wshadow.
7536 ///
7537 /// This method is called whenever a VarDecl is added to a "useful"
7538 /// scope.
7539 ///
7540 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7541 /// \param R the lookup of the name
7542 ///
7543 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7544                        const LookupResult &R) {
7545   DeclContext *NewDC = D->getDeclContext();
7546 
7547   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7548     // Fields are not shadowed by variables in C++ static methods.
7549     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7550       if (MD->isStatic())
7551         return;
7552 
7553     // Fields shadowed by constructor parameters are a special case. Usually
7554     // the constructor initializes the field with the parameter.
7555     if (isa<CXXConstructorDecl>(NewDC))
7556       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7557         // Remember that this was shadowed so we can either warn about its
7558         // modification or its existence depending on warning settings.
7559         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7560         return;
7561       }
7562   }
7563 
7564   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7565     if (shadowedVar->isExternC()) {
7566       // For shadowing external vars, make sure that we point to the global
7567       // declaration, not a locally scoped extern declaration.
7568       for (auto I : shadowedVar->redecls())
7569         if (I->isFileVarDecl()) {
7570           ShadowedDecl = I;
7571           break;
7572         }
7573     }
7574 
7575   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7576 
7577   unsigned WarningDiag = diag::warn_decl_shadow;
7578   SourceLocation CaptureLoc;
7579   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7580       isa<CXXMethodDecl>(NewDC)) {
7581     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7582       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7583         if (RD->getLambdaCaptureDefault() == LCD_None) {
7584           // Try to avoid warnings for lambdas with an explicit capture list.
7585           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7586           // Warn only when the lambda captures the shadowed decl explicitly.
7587           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7588           if (CaptureLoc.isInvalid())
7589             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7590         } else {
7591           // Remember that this was shadowed so we can avoid the warning if the
7592           // shadowed decl isn't captured and the warning settings allow it.
7593           cast<LambdaScopeInfo>(getCurFunction())
7594               ->ShadowingDecls.push_back(
7595                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7596           return;
7597         }
7598       }
7599 
7600       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7601         // A variable can't shadow a local variable in an enclosing scope, if
7602         // they are separated by a non-capturing declaration context.
7603         for (DeclContext *ParentDC = NewDC;
7604              ParentDC && !ParentDC->Equals(OldDC);
7605              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7606           // Only block literals, captured statements, and lambda expressions
7607           // can capture; other scopes don't.
7608           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7609               !isLambdaCallOperator(ParentDC)) {
7610             return;
7611           }
7612         }
7613       }
7614     }
7615   }
7616 
7617   // Only warn about certain kinds of shadowing for class members.
7618   if (NewDC && NewDC->isRecord()) {
7619     // In particular, don't warn about shadowing non-class members.
7620     if (!OldDC->isRecord())
7621       return;
7622 
7623     // TODO: should we warn about static data members shadowing
7624     // static data members from base classes?
7625 
7626     // TODO: don't diagnose for inaccessible shadowed members.
7627     // This is hard to do perfectly because we might friend the
7628     // shadowing context, but that's just a false negative.
7629   }
7630 
7631 
7632   DeclarationName Name = R.getLookupName();
7633 
7634   // Emit warning and note.
7635   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7636     return;
7637   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7638   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7639   if (!CaptureLoc.isInvalid())
7640     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7641         << Name << /*explicitly*/ 1;
7642   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7643 }
7644 
7645 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7646 /// when these variables are captured by the lambda.
7647 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7648   for (const auto &Shadow : LSI->ShadowingDecls) {
7649     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7650     // Try to avoid the warning when the shadowed decl isn't captured.
7651     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7652     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7653     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7654                                        ? diag::warn_decl_shadow_uncaptured_local
7655                                        : diag::warn_decl_shadow)
7656         << Shadow.VD->getDeclName()
7657         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7658     if (!CaptureLoc.isInvalid())
7659       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7660           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7661     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7662   }
7663 }
7664 
7665 /// Check -Wshadow without the advantage of a previous lookup.
7666 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7667   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7668     return;
7669 
7670   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7671                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7672   LookupName(R, S);
7673   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7674     CheckShadow(D, ShadowedDecl, R);
7675 }
7676 
7677 /// Check if 'E', which is an expression that is about to be modified, refers
7678 /// to a constructor parameter that shadows a field.
7679 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7680   // Quickly ignore expressions that can't be shadowing ctor parameters.
7681   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7682     return;
7683   E = E->IgnoreParenImpCasts();
7684   auto *DRE = dyn_cast<DeclRefExpr>(E);
7685   if (!DRE)
7686     return;
7687   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7688   auto I = ShadowingDecls.find(D);
7689   if (I == ShadowingDecls.end())
7690     return;
7691   const NamedDecl *ShadowedDecl = I->second;
7692   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7693   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7694   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7695   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7696 
7697   // Avoid issuing multiple warnings about the same decl.
7698   ShadowingDecls.erase(I);
7699 }
7700 
7701 /// Check for conflict between this global or extern "C" declaration and
7702 /// previous global or extern "C" declarations. This is only used in C++.
7703 template<typename T>
7704 static bool checkGlobalOrExternCConflict(
7705     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7706   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7707   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7708 
7709   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7710     // The common case: this global doesn't conflict with any extern "C"
7711     // declaration.
7712     return false;
7713   }
7714 
7715   if (Prev) {
7716     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7717       // Both the old and new declarations have C language linkage. This is a
7718       // redeclaration.
7719       Previous.clear();
7720       Previous.addDecl(Prev);
7721       return true;
7722     }
7723 
7724     // This is a global, non-extern "C" declaration, and there is a previous
7725     // non-global extern "C" declaration. Diagnose if this is a variable
7726     // declaration.
7727     if (!isa<VarDecl>(ND))
7728       return false;
7729   } else {
7730     // The declaration is extern "C". Check for any declaration in the
7731     // translation unit which might conflict.
7732     if (IsGlobal) {
7733       // We have already performed the lookup into the translation unit.
7734       IsGlobal = false;
7735       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7736            I != E; ++I) {
7737         if (isa<VarDecl>(*I)) {
7738           Prev = *I;
7739           break;
7740         }
7741       }
7742     } else {
7743       DeclContext::lookup_result R =
7744           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7745       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7746            I != E; ++I) {
7747         if (isa<VarDecl>(*I)) {
7748           Prev = *I;
7749           break;
7750         }
7751         // FIXME: If we have any other entity with this name in global scope,
7752         // the declaration is ill-formed, but that is a defect: it breaks the
7753         // 'stat' hack, for instance. Only variables can have mangled name
7754         // clashes with extern "C" declarations, so only they deserve a
7755         // diagnostic.
7756       }
7757     }
7758 
7759     if (!Prev)
7760       return false;
7761   }
7762 
7763   // Use the first declaration's location to ensure we point at something which
7764   // is lexically inside an extern "C" linkage-spec.
7765   assert(Prev && "should have found a previous declaration to diagnose");
7766   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7767     Prev = FD->getFirstDecl();
7768   else
7769     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7770 
7771   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7772     << IsGlobal << ND;
7773   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7774     << IsGlobal;
7775   return false;
7776 }
7777 
7778 /// Apply special rules for handling extern "C" declarations. Returns \c true
7779 /// if we have found that this is a redeclaration of some prior entity.
7780 ///
7781 /// Per C++ [dcl.link]p6:
7782 ///   Two declarations [for a function or variable] with C language linkage
7783 ///   with the same name that appear in different scopes refer to the same
7784 ///   [entity]. An entity with C language linkage shall not be declared with
7785 ///   the same name as an entity in global scope.
7786 template<typename T>
7787 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7788                                                   LookupResult &Previous) {
7789   if (!S.getLangOpts().CPlusPlus) {
7790     // In C, when declaring a global variable, look for a corresponding 'extern'
7791     // variable declared in function scope. We don't need this in C++, because
7792     // we find local extern decls in the surrounding file-scope DeclContext.
7793     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7794       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7795         Previous.clear();
7796         Previous.addDecl(Prev);
7797         return true;
7798       }
7799     }
7800     return false;
7801   }
7802 
7803   // A declaration in the translation unit can conflict with an extern "C"
7804   // declaration.
7805   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7806     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7807 
7808   // An extern "C" declaration can conflict with a declaration in the
7809   // translation unit or can be a redeclaration of an extern "C" declaration
7810   // in another scope.
7811   if (isIncompleteDeclExternC(S,ND))
7812     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7813 
7814   // Neither global nor extern "C": nothing to do.
7815   return false;
7816 }
7817 
7818 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7819   // If the decl is already known invalid, don't check it.
7820   if (NewVD->isInvalidDecl())
7821     return;
7822 
7823   QualType T = NewVD->getType();
7824 
7825   // Defer checking an 'auto' type until its initializer is attached.
7826   if (T->isUndeducedType())
7827     return;
7828 
7829   if (NewVD->hasAttrs())
7830     CheckAlignasUnderalignment(NewVD);
7831 
7832   if (T->isObjCObjectType()) {
7833     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7834       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7835     T = Context.getObjCObjectPointerType(T);
7836     NewVD->setType(T);
7837   }
7838 
7839   // Emit an error if an address space was applied to decl with local storage.
7840   // This includes arrays of objects with address space qualifiers, but not
7841   // automatic variables that point to other address spaces.
7842   // ISO/IEC TR 18037 S5.1.2
7843   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7844       T.getAddressSpace() != LangAS::Default) {
7845     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7846     NewVD->setInvalidDecl();
7847     return;
7848   }
7849 
7850   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7851   // scope.
7852   if (getLangOpts().OpenCLVersion == 120 &&
7853       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7854       NewVD->isStaticLocal()) {
7855     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7856     NewVD->setInvalidDecl();
7857     return;
7858   }
7859 
7860   if (getLangOpts().OpenCL) {
7861     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7862     if (NewVD->hasAttr<BlocksAttr>()) {
7863       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7864       return;
7865     }
7866 
7867     if (T->isBlockPointerType()) {
7868       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7869       // can't use 'extern' storage class.
7870       if (!T.isConstQualified()) {
7871         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7872             << 0 /*const*/;
7873         NewVD->setInvalidDecl();
7874         return;
7875       }
7876       if (NewVD->hasExternalStorage()) {
7877         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7878         NewVD->setInvalidDecl();
7879         return;
7880       }
7881     }
7882     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7883     // __constant address space.
7884     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7885     // variables inside a function can also be declared in the global
7886     // address space.
7887     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7888     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7889     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7890         NewVD->hasExternalStorage()) {
7891       if (!T->isSamplerT() &&
7892           !T->isDependentType() &&
7893           !(T.getAddressSpace() == LangAS::opencl_constant ||
7894             (T.getAddressSpace() == LangAS::opencl_global &&
7895              (getLangOpts().OpenCLVersion == 200 ||
7896               getLangOpts().OpenCLCPlusPlus)))) {
7897         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7898         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7899           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7900               << Scope << "global or constant";
7901         else
7902           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7903               << Scope << "constant";
7904         NewVD->setInvalidDecl();
7905         return;
7906       }
7907     } else {
7908       if (T.getAddressSpace() == LangAS::opencl_global) {
7909         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7910             << 1 /*is any function*/ << "global";
7911         NewVD->setInvalidDecl();
7912         return;
7913       }
7914       if (T.getAddressSpace() == LangAS::opencl_constant ||
7915           T.getAddressSpace() == LangAS::opencl_local) {
7916         FunctionDecl *FD = getCurFunctionDecl();
7917         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7918         // in functions.
7919         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7920           if (T.getAddressSpace() == LangAS::opencl_constant)
7921             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7922                 << 0 /*non-kernel only*/ << "constant";
7923           else
7924             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7925                 << 0 /*non-kernel only*/ << "local";
7926           NewVD->setInvalidDecl();
7927           return;
7928         }
7929         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7930         // in the outermost scope of a kernel function.
7931         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7932           if (!getCurScope()->isFunctionScope()) {
7933             if (T.getAddressSpace() == LangAS::opencl_constant)
7934               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7935                   << "constant";
7936             else
7937               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7938                   << "local";
7939             NewVD->setInvalidDecl();
7940             return;
7941           }
7942         }
7943       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7944                  // If we are parsing a template we didn't deduce an addr
7945                  // space yet.
7946                  T.getAddressSpace() != LangAS::Default) {
7947         // Do not allow other address spaces on automatic variable.
7948         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7949         NewVD->setInvalidDecl();
7950         return;
7951       }
7952     }
7953   }
7954 
7955   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7956       && !NewVD->hasAttr<BlocksAttr>()) {
7957     if (getLangOpts().getGC() != LangOptions::NonGC)
7958       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7959     else {
7960       assert(!getLangOpts().ObjCAutoRefCount);
7961       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7962     }
7963   }
7964 
7965   bool isVM = T->isVariablyModifiedType();
7966   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7967       NewVD->hasAttr<BlocksAttr>())
7968     setFunctionHasBranchProtectedScope();
7969 
7970   if ((isVM && NewVD->hasLinkage()) ||
7971       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7972     bool SizeIsNegative;
7973     llvm::APSInt Oversized;
7974     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7975         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7976     QualType FixedT;
7977     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7978       FixedT = FixedTInfo->getType();
7979     else if (FixedTInfo) {
7980       // Type and type-as-written are canonically different. We need to fix up
7981       // both types separately.
7982       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7983                                                    Oversized);
7984     }
7985     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7986       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7987       // FIXME: This won't give the correct result for
7988       // int a[10][n];
7989       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7990 
7991       if (NewVD->isFileVarDecl())
7992         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7993         << SizeRange;
7994       else if (NewVD->isStaticLocal())
7995         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7996         << SizeRange;
7997       else
7998         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7999         << SizeRange;
8000       NewVD->setInvalidDecl();
8001       return;
8002     }
8003 
8004     if (!FixedTInfo) {
8005       if (NewVD->isFileVarDecl())
8006         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8007       else
8008         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8009       NewVD->setInvalidDecl();
8010       return;
8011     }
8012 
8013     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
8014     NewVD->setType(FixedT);
8015     NewVD->setTypeSourceInfo(FixedTInfo);
8016   }
8017 
8018   if (T->isVoidType()) {
8019     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8020     //                    of objects and functions.
8021     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8022       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8023         << T;
8024       NewVD->setInvalidDecl();
8025       return;
8026     }
8027   }
8028 
8029   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8030     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8031     NewVD->setInvalidDecl();
8032     return;
8033   }
8034 
8035   if (!NewVD->hasLocalStorage() && T->isSizelessType() && !T->isVLST()) {
8036     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8037     NewVD->setInvalidDecl();
8038     return;
8039   }
8040 
8041   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8042     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8043     NewVD->setInvalidDecl();
8044     return;
8045   }
8046 
8047   if (NewVD->isConstexpr() && !T->isDependentType() &&
8048       RequireLiteralType(NewVD->getLocation(), T,
8049                          diag::err_constexpr_var_non_literal)) {
8050     NewVD->setInvalidDecl();
8051     return;
8052   }
8053 }
8054 
8055 /// Perform semantic checking on a newly-created variable
8056 /// declaration.
8057 ///
8058 /// This routine performs all of the type-checking required for a
8059 /// variable declaration once it has been built. It is used both to
8060 /// check variables after they have been parsed and their declarators
8061 /// have been translated into a declaration, and to check variables
8062 /// that have been instantiated from a template.
8063 ///
8064 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8065 ///
8066 /// Returns true if the variable declaration is a redeclaration.
8067 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8068   CheckVariableDeclarationType(NewVD);
8069 
8070   // If the decl is already known invalid, don't check it.
8071   if (NewVD->isInvalidDecl())
8072     return false;
8073 
8074   // If we did not find anything by this name, look for a non-visible
8075   // extern "C" declaration with the same name.
8076   if (Previous.empty() &&
8077       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8078     Previous.setShadowed();
8079 
8080   if (!Previous.empty()) {
8081     MergeVarDecl(NewVD, Previous);
8082     return true;
8083   }
8084   return false;
8085 }
8086 
8087 namespace {
8088 struct FindOverriddenMethod {
8089   Sema *S;
8090   CXXMethodDecl *Method;
8091 
8092   /// Member lookup function that determines whether a given C++
8093   /// method overrides a method in a base class, to be used with
8094   /// CXXRecordDecl::lookupInBases().
8095   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8096     RecordDecl *BaseRecord =
8097         Specifier->getType()->castAs<RecordType>()->getDecl();
8098 
8099     DeclarationName Name = Method->getDeclName();
8100 
8101     // FIXME: Do we care about other names here too?
8102     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8103       // We really want to find the base class destructor here.
8104       QualType T = S->Context.getTypeDeclType(BaseRecord);
8105       CanQualType CT = S->Context.getCanonicalType(T);
8106 
8107       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8108     }
8109 
8110     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8111          Path.Decls = Path.Decls.slice(1)) {
8112       NamedDecl *D = Path.Decls.front();
8113       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8114         if (MD->isVirtual() &&
8115             !S->IsOverload(
8116                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8117                 /*ConsiderCudaAttrs=*/true,
8118                 // C++2a [class.virtual]p2 does not consider requires clauses
8119                 // when overriding.
8120                 /*ConsiderRequiresClauses=*/false))
8121           return true;
8122       }
8123     }
8124 
8125     return false;
8126   }
8127 };
8128 } // end anonymous namespace
8129 
8130 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8131 /// and if so, check that it's a valid override and remember it.
8132 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8133   // Look for methods in base classes that this method might override.
8134   CXXBasePaths Paths;
8135   FindOverriddenMethod FOM;
8136   FOM.Method = MD;
8137   FOM.S = this;
8138   bool AddedAny = false;
8139   if (DC->lookupInBases(FOM, Paths)) {
8140     for (auto *I : Paths.found_decls()) {
8141       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8142         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8143         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8144             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8145             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8146             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8147           AddedAny = true;
8148         }
8149       }
8150     }
8151   }
8152 
8153   return AddedAny;
8154 }
8155 
8156 namespace {
8157   // Struct for holding all of the extra arguments needed by
8158   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8159   struct ActOnFDArgs {
8160     Scope *S;
8161     Declarator &D;
8162     MultiTemplateParamsArg TemplateParamLists;
8163     bool AddToScope;
8164   };
8165 } // end anonymous namespace
8166 
8167 namespace {
8168 
8169 // Callback to only accept typo corrections that have a non-zero edit distance.
8170 // Also only accept corrections that have the same parent decl.
8171 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8172  public:
8173   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8174                             CXXRecordDecl *Parent)
8175       : Context(Context), OriginalFD(TypoFD),
8176         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8177 
8178   bool ValidateCandidate(const TypoCorrection &candidate) override {
8179     if (candidate.getEditDistance() == 0)
8180       return false;
8181 
8182     SmallVector<unsigned, 1> MismatchedParams;
8183     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8184                                           CDeclEnd = candidate.end();
8185          CDecl != CDeclEnd; ++CDecl) {
8186       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8187 
8188       if (FD && !FD->hasBody() &&
8189           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8190         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8191           CXXRecordDecl *Parent = MD->getParent();
8192           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8193             return true;
8194         } else if (!ExpectedParent) {
8195           return true;
8196         }
8197       }
8198     }
8199 
8200     return false;
8201   }
8202 
8203   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8204     return std::make_unique<DifferentNameValidatorCCC>(*this);
8205   }
8206 
8207  private:
8208   ASTContext &Context;
8209   FunctionDecl *OriginalFD;
8210   CXXRecordDecl *ExpectedParent;
8211 };
8212 
8213 } // end anonymous namespace
8214 
8215 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8216   TypoCorrectedFunctionDefinitions.insert(F);
8217 }
8218 
8219 /// Generate diagnostics for an invalid function redeclaration.
8220 ///
8221 /// This routine handles generating the diagnostic messages for an invalid
8222 /// function redeclaration, including finding possible similar declarations
8223 /// or performing typo correction if there are no previous declarations with
8224 /// the same name.
8225 ///
8226 /// Returns a NamedDecl iff typo correction was performed and substituting in
8227 /// the new declaration name does not cause new errors.
8228 static NamedDecl *DiagnoseInvalidRedeclaration(
8229     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8230     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8231   DeclarationName Name = NewFD->getDeclName();
8232   DeclContext *NewDC = NewFD->getDeclContext();
8233   SmallVector<unsigned, 1> MismatchedParams;
8234   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8235   TypoCorrection Correction;
8236   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8237   unsigned DiagMsg =
8238     IsLocalFriend ? diag::err_no_matching_local_friend :
8239     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8240     diag::err_member_decl_does_not_match;
8241   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8242                     IsLocalFriend ? Sema::LookupLocalFriendName
8243                                   : Sema::LookupOrdinaryName,
8244                     Sema::ForVisibleRedeclaration);
8245 
8246   NewFD->setInvalidDecl();
8247   if (IsLocalFriend)
8248     SemaRef.LookupName(Prev, S);
8249   else
8250     SemaRef.LookupQualifiedName(Prev, NewDC);
8251   assert(!Prev.isAmbiguous() &&
8252          "Cannot have an ambiguity in previous-declaration lookup");
8253   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8254   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8255                                 MD ? MD->getParent() : nullptr);
8256   if (!Prev.empty()) {
8257     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8258          Func != FuncEnd; ++Func) {
8259       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8260       if (FD &&
8261           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8262         // Add 1 to the index so that 0 can mean the mismatch didn't
8263         // involve a parameter
8264         unsigned ParamNum =
8265             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8266         NearMatches.push_back(std::make_pair(FD, ParamNum));
8267       }
8268     }
8269   // If the qualified name lookup yielded nothing, try typo correction
8270   } else if ((Correction = SemaRef.CorrectTypo(
8271                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8272                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8273                   IsLocalFriend ? nullptr : NewDC))) {
8274     // Set up everything for the call to ActOnFunctionDeclarator
8275     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8276                               ExtraArgs.D.getIdentifierLoc());
8277     Previous.clear();
8278     Previous.setLookupName(Correction.getCorrection());
8279     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8280                                     CDeclEnd = Correction.end();
8281          CDecl != CDeclEnd; ++CDecl) {
8282       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8283       if (FD && !FD->hasBody() &&
8284           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8285         Previous.addDecl(FD);
8286       }
8287     }
8288     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8289 
8290     NamedDecl *Result;
8291     // Retry building the function declaration with the new previous
8292     // declarations, and with errors suppressed.
8293     {
8294       // Trap errors.
8295       Sema::SFINAETrap Trap(SemaRef);
8296 
8297       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8298       // pieces need to verify the typo-corrected C++ declaration and hopefully
8299       // eliminate the need for the parameter pack ExtraArgs.
8300       Result = SemaRef.ActOnFunctionDeclarator(
8301           ExtraArgs.S, ExtraArgs.D,
8302           Correction.getCorrectionDecl()->getDeclContext(),
8303           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8304           ExtraArgs.AddToScope);
8305 
8306       if (Trap.hasErrorOccurred())
8307         Result = nullptr;
8308     }
8309 
8310     if (Result) {
8311       // Determine which correction we picked.
8312       Decl *Canonical = Result->getCanonicalDecl();
8313       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8314            I != E; ++I)
8315         if ((*I)->getCanonicalDecl() == Canonical)
8316           Correction.setCorrectionDecl(*I);
8317 
8318       // Let Sema know about the correction.
8319       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8320       SemaRef.diagnoseTypo(
8321           Correction,
8322           SemaRef.PDiag(IsLocalFriend
8323                           ? diag::err_no_matching_local_friend_suggest
8324                           : diag::err_member_decl_does_not_match_suggest)
8325             << Name << NewDC << IsDefinition);
8326       return Result;
8327     }
8328 
8329     // Pretend the typo correction never occurred
8330     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8331                               ExtraArgs.D.getIdentifierLoc());
8332     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8333     Previous.clear();
8334     Previous.setLookupName(Name);
8335   }
8336 
8337   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8338       << Name << NewDC << IsDefinition << NewFD->getLocation();
8339 
8340   bool NewFDisConst = false;
8341   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8342     NewFDisConst = NewMD->isConst();
8343 
8344   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8345        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8346        NearMatch != NearMatchEnd; ++NearMatch) {
8347     FunctionDecl *FD = NearMatch->first;
8348     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8349     bool FDisConst = MD && MD->isConst();
8350     bool IsMember = MD || !IsLocalFriend;
8351 
8352     // FIXME: These notes are poorly worded for the local friend case.
8353     if (unsigned Idx = NearMatch->second) {
8354       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8355       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8356       if (Loc.isInvalid()) Loc = FD->getLocation();
8357       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8358                                  : diag::note_local_decl_close_param_match)
8359         << Idx << FDParam->getType()
8360         << NewFD->getParamDecl(Idx - 1)->getType();
8361     } else if (FDisConst != NewFDisConst) {
8362       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8363           << NewFDisConst << FD->getSourceRange().getEnd();
8364     } else
8365       SemaRef.Diag(FD->getLocation(),
8366                    IsMember ? diag::note_member_def_close_match
8367                             : diag::note_local_decl_close_match);
8368   }
8369   return nullptr;
8370 }
8371 
8372 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8373   switch (D.getDeclSpec().getStorageClassSpec()) {
8374   default: llvm_unreachable("Unknown storage class!");
8375   case DeclSpec::SCS_auto:
8376   case DeclSpec::SCS_register:
8377   case DeclSpec::SCS_mutable:
8378     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8379                  diag::err_typecheck_sclass_func);
8380     D.getMutableDeclSpec().ClearStorageClassSpecs();
8381     D.setInvalidType();
8382     break;
8383   case DeclSpec::SCS_unspecified: break;
8384   case DeclSpec::SCS_extern:
8385     if (D.getDeclSpec().isExternInLinkageSpec())
8386       return SC_None;
8387     return SC_Extern;
8388   case DeclSpec::SCS_static: {
8389     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8390       // C99 6.7.1p5:
8391       //   The declaration of an identifier for a function that has
8392       //   block scope shall have no explicit storage-class specifier
8393       //   other than extern
8394       // See also (C++ [dcl.stc]p4).
8395       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8396                    diag::err_static_block_func);
8397       break;
8398     } else
8399       return SC_Static;
8400   }
8401   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8402   }
8403 
8404   // No explicit storage class has already been returned
8405   return SC_None;
8406 }
8407 
8408 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8409                                            DeclContext *DC, QualType &R,
8410                                            TypeSourceInfo *TInfo,
8411                                            StorageClass SC,
8412                                            bool &IsVirtualOkay) {
8413   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8414   DeclarationName Name = NameInfo.getName();
8415 
8416   FunctionDecl *NewFD = nullptr;
8417   bool isInline = D.getDeclSpec().isInlineSpecified();
8418 
8419   if (!SemaRef.getLangOpts().CPlusPlus) {
8420     // Determine whether the function was written with a
8421     // prototype. This true when:
8422     //   - there is a prototype in the declarator, or
8423     //   - the type R of the function is some kind of typedef or other non-
8424     //     attributed reference to a type name (which eventually refers to a
8425     //     function type).
8426     bool HasPrototype =
8427       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8428       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8429 
8430     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8431                                  R, TInfo, SC, isInline, HasPrototype,
8432                                  CSK_unspecified,
8433                                  /*TrailingRequiresClause=*/nullptr);
8434     if (D.isInvalidType())
8435       NewFD->setInvalidDecl();
8436 
8437     return NewFD;
8438   }
8439 
8440   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8441 
8442   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8443   if (ConstexprKind == CSK_constinit) {
8444     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8445                  diag::err_constexpr_wrong_decl_kind)
8446         << ConstexprKind;
8447     ConstexprKind = CSK_unspecified;
8448     D.getMutableDeclSpec().ClearConstexprSpec();
8449   }
8450   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8451 
8452   // Check that the return type is not an abstract class type.
8453   // For record types, this is done by the AbstractClassUsageDiagnoser once
8454   // the class has been completely parsed.
8455   if (!DC->isRecord() &&
8456       SemaRef.RequireNonAbstractType(
8457           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8458           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8459     D.setInvalidType();
8460 
8461   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8462     // This is a C++ constructor declaration.
8463     assert(DC->isRecord() &&
8464            "Constructors can only be declared in a member context");
8465 
8466     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8467     return CXXConstructorDecl::Create(
8468         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8469         TInfo, ExplicitSpecifier, isInline,
8470         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8471         TrailingRequiresClause);
8472 
8473   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8474     // This is a C++ destructor declaration.
8475     if (DC->isRecord()) {
8476       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8477       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8478       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8479           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8480           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8481           TrailingRequiresClause);
8482 
8483       // If the destructor needs an implicit exception specification, set it
8484       // now. FIXME: It'd be nice to be able to create the right type to start
8485       // with, but the type needs to reference the destructor declaration.
8486       if (SemaRef.getLangOpts().CPlusPlus11)
8487         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8488 
8489       IsVirtualOkay = true;
8490       return NewDD;
8491 
8492     } else {
8493       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8494       D.setInvalidType();
8495 
8496       // Create a FunctionDecl to satisfy the function definition parsing
8497       // code path.
8498       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8499                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8500                                   isInline,
8501                                   /*hasPrototype=*/true, ConstexprKind,
8502                                   TrailingRequiresClause);
8503     }
8504 
8505   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8506     if (!DC->isRecord()) {
8507       SemaRef.Diag(D.getIdentifierLoc(),
8508            diag::err_conv_function_not_member);
8509       return nullptr;
8510     }
8511 
8512     SemaRef.CheckConversionDeclarator(D, R, SC);
8513     if (D.isInvalidType())
8514       return nullptr;
8515 
8516     IsVirtualOkay = true;
8517     return CXXConversionDecl::Create(
8518         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8519         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8520         TrailingRequiresClause);
8521 
8522   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8523     if (TrailingRequiresClause)
8524       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8525                    diag::err_trailing_requires_clause_on_deduction_guide)
8526           << TrailingRequiresClause->getSourceRange();
8527     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8528 
8529     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8530                                          ExplicitSpecifier, NameInfo, R, TInfo,
8531                                          D.getEndLoc());
8532   } else if (DC->isRecord()) {
8533     // If the name of the function is the same as the name of the record,
8534     // then this must be an invalid constructor that has a return type.
8535     // (The parser checks for a return type and makes the declarator a
8536     // constructor if it has no return type).
8537     if (Name.getAsIdentifierInfo() &&
8538         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8539       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8540         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8541         << SourceRange(D.getIdentifierLoc());
8542       return nullptr;
8543     }
8544 
8545     // This is a C++ method declaration.
8546     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8547         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8548         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8549         TrailingRequiresClause);
8550     IsVirtualOkay = !Ret->isStatic();
8551     return Ret;
8552   } else {
8553     bool isFriend =
8554         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8555     if (!isFriend && SemaRef.CurContext->isRecord())
8556       return nullptr;
8557 
8558     // Determine whether the function was written with a
8559     // prototype. This true when:
8560     //   - we're in C++ (where every function has a prototype),
8561     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8562                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8563                                 ConstexprKind, TrailingRequiresClause);
8564   }
8565 }
8566 
8567 enum OpenCLParamType {
8568   ValidKernelParam,
8569   PtrPtrKernelParam,
8570   PtrKernelParam,
8571   InvalidAddrSpacePtrKernelParam,
8572   InvalidKernelParam,
8573   RecordKernelParam
8574 };
8575 
8576 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8577   // Size dependent types are just typedefs to normal integer types
8578   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8579   // integers other than by their names.
8580   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8581 
8582   // Remove typedefs one by one until we reach a typedef
8583   // for a size dependent type.
8584   QualType DesugaredTy = Ty;
8585   do {
8586     ArrayRef<StringRef> Names(SizeTypeNames);
8587     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8588     if (Names.end() != Match)
8589       return true;
8590 
8591     Ty = DesugaredTy;
8592     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8593   } while (DesugaredTy != Ty);
8594 
8595   return false;
8596 }
8597 
8598 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8599   if (PT->isPointerType()) {
8600     QualType PointeeType = PT->getPointeeType();
8601     if (PointeeType->isPointerType())
8602       return PtrPtrKernelParam;
8603     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8604         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8605         PointeeType.getAddressSpace() == LangAS::Default)
8606       return InvalidAddrSpacePtrKernelParam;
8607     return PtrKernelParam;
8608   }
8609 
8610   // OpenCL v1.2 s6.9.k:
8611   // Arguments to kernel functions in a program cannot be declared with the
8612   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8613   // uintptr_t or a struct and/or union that contain fields declared to be one
8614   // of these built-in scalar types.
8615   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8616     return InvalidKernelParam;
8617 
8618   if (PT->isImageType())
8619     return PtrKernelParam;
8620 
8621   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8622     return InvalidKernelParam;
8623 
8624   // OpenCL extension spec v1.2 s9.5:
8625   // This extension adds support for half scalar and vector types as built-in
8626   // types that can be used for arithmetic operations, conversions etc.
8627   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8628     return InvalidKernelParam;
8629 
8630   if (PT->isRecordType())
8631     return RecordKernelParam;
8632 
8633   // Look into an array argument to check if it has a forbidden type.
8634   if (PT->isArrayType()) {
8635     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8636     // Call ourself to check an underlying type of an array. Since the
8637     // getPointeeOrArrayElementType returns an innermost type which is not an
8638     // array, this recursive call only happens once.
8639     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8640   }
8641 
8642   return ValidKernelParam;
8643 }
8644 
8645 static void checkIsValidOpenCLKernelParameter(
8646   Sema &S,
8647   Declarator &D,
8648   ParmVarDecl *Param,
8649   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8650   QualType PT = Param->getType();
8651 
8652   // Cache the valid types we encounter to avoid rechecking structs that are
8653   // used again
8654   if (ValidTypes.count(PT.getTypePtr()))
8655     return;
8656 
8657   switch (getOpenCLKernelParameterType(S, PT)) {
8658   case PtrPtrKernelParam:
8659     // OpenCL v1.2 s6.9.a:
8660     // A kernel function argument cannot be declared as a
8661     // pointer to a pointer type.
8662     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8663     D.setInvalidType();
8664     return;
8665 
8666   case InvalidAddrSpacePtrKernelParam:
8667     // OpenCL v1.0 s6.5:
8668     // __kernel function arguments declared to be a pointer of a type can point
8669     // to one of the following address spaces only : __global, __local or
8670     // __constant.
8671     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8672     D.setInvalidType();
8673     return;
8674 
8675     // OpenCL v1.2 s6.9.k:
8676     // Arguments to kernel functions in a program cannot be declared with the
8677     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8678     // uintptr_t or a struct and/or union that contain fields declared to be
8679     // one of these built-in scalar types.
8680 
8681   case InvalidKernelParam:
8682     // OpenCL v1.2 s6.8 n:
8683     // A kernel function argument cannot be declared
8684     // of event_t type.
8685     // Do not diagnose half type since it is diagnosed as invalid argument
8686     // type for any function elsewhere.
8687     if (!PT->isHalfType()) {
8688       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8689 
8690       // Explain what typedefs are involved.
8691       const TypedefType *Typedef = nullptr;
8692       while ((Typedef = PT->getAs<TypedefType>())) {
8693         SourceLocation Loc = Typedef->getDecl()->getLocation();
8694         // SourceLocation may be invalid for a built-in type.
8695         if (Loc.isValid())
8696           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8697         PT = Typedef->desugar();
8698       }
8699     }
8700 
8701     D.setInvalidType();
8702     return;
8703 
8704   case PtrKernelParam:
8705   case ValidKernelParam:
8706     ValidTypes.insert(PT.getTypePtr());
8707     return;
8708 
8709   case RecordKernelParam:
8710     break;
8711   }
8712 
8713   // Track nested structs we will inspect
8714   SmallVector<const Decl *, 4> VisitStack;
8715 
8716   // Track where we are in the nested structs. Items will migrate from
8717   // VisitStack to HistoryStack as we do the DFS for bad field.
8718   SmallVector<const FieldDecl *, 4> HistoryStack;
8719   HistoryStack.push_back(nullptr);
8720 
8721   // At this point we already handled everything except of a RecordType or
8722   // an ArrayType of a RecordType.
8723   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8724   const RecordType *RecTy =
8725       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8726   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8727 
8728   VisitStack.push_back(RecTy->getDecl());
8729   assert(VisitStack.back() && "First decl null?");
8730 
8731   do {
8732     const Decl *Next = VisitStack.pop_back_val();
8733     if (!Next) {
8734       assert(!HistoryStack.empty());
8735       // Found a marker, we have gone up a level
8736       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8737         ValidTypes.insert(Hist->getType().getTypePtr());
8738 
8739       continue;
8740     }
8741 
8742     // Adds everything except the original parameter declaration (which is not a
8743     // field itself) to the history stack.
8744     const RecordDecl *RD;
8745     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8746       HistoryStack.push_back(Field);
8747 
8748       QualType FieldTy = Field->getType();
8749       // Other field types (known to be valid or invalid) are handled while we
8750       // walk around RecordDecl::fields().
8751       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8752              "Unexpected type.");
8753       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8754 
8755       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8756     } else {
8757       RD = cast<RecordDecl>(Next);
8758     }
8759 
8760     // Add a null marker so we know when we've gone back up a level
8761     VisitStack.push_back(nullptr);
8762 
8763     for (const auto *FD : RD->fields()) {
8764       QualType QT = FD->getType();
8765 
8766       if (ValidTypes.count(QT.getTypePtr()))
8767         continue;
8768 
8769       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8770       if (ParamType == ValidKernelParam)
8771         continue;
8772 
8773       if (ParamType == RecordKernelParam) {
8774         VisitStack.push_back(FD);
8775         continue;
8776       }
8777 
8778       // OpenCL v1.2 s6.9.p:
8779       // Arguments to kernel functions that are declared to be a struct or union
8780       // do not allow OpenCL objects to be passed as elements of the struct or
8781       // union.
8782       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8783           ParamType == InvalidAddrSpacePtrKernelParam) {
8784         S.Diag(Param->getLocation(),
8785                diag::err_record_with_pointers_kernel_param)
8786           << PT->isUnionType()
8787           << PT;
8788       } else {
8789         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8790       }
8791 
8792       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8793           << OrigRecDecl->getDeclName();
8794 
8795       // We have an error, now let's go back up through history and show where
8796       // the offending field came from
8797       for (ArrayRef<const FieldDecl *>::const_iterator
8798                I = HistoryStack.begin() + 1,
8799                E = HistoryStack.end();
8800            I != E; ++I) {
8801         const FieldDecl *OuterField = *I;
8802         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8803           << OuterField->getType();
8804       }
8805 
8806       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8807         << QT->isPointerType()
8808         << QT;
8809       D.setInvalidType();
8810       return;
8811     }
8812   } while (!VisitStack.empty());
8813 }
8814 
8815 /// Find the DeclContext in which a tag is implicitly declared if we see an
8816 /// elaborated type specifier in the specified context, and lookup finds
8817 /// nothing.
8818 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8819   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8820     DC = DC->getParent();
8821   return DC;
8822 }
8823 
8824 /// Find the Scope in which a tag is implicitly declared if we see an
8825 /// elaborated type specifier in the specified context, and lookup finds
8826 /// nothing.
8827 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8828   while (S->isClassScope() ||
8829          (LangOpts.CPlusPlus &&
8830           S->isFunctionPrototypeScope()) ||
8831          ((S->getFlags() & Scope::DeclScope) == 0) ||
8832          (S->getEntity() && S->getEntity()->isTransparentContext()))
8833     S = S->getParent();
8834   return S;
8835 }
8836 
8837 NamedDecl*
8838 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8839                               TypeSourceInfo *TInfo, LookupResult &Previous,
8840                               MultiTemplateParamsArg TemplateParamListsRef,
8841                               bool &AddToScope) {
8842   QualType R = TInfo->getType();
8843 
8844   assert(R->isFunctionType());
8845   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8846     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8847 
8848   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8849   for (TemplateParameterList *TPL : TemplateParamListsRef)
8850     TemplateParamLists.push_back(TPL);
8851   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8852     if (!TemplateParamLists.empty() &&
8853         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8854       TemplateParamLists.back() = Invented;
8855     else
8856       TemplateParamLists.push_back(Invented);
8857   }
8858 
8859   // TODO: consider using NameInfo for diagnostic.
8860   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8861   DeclarationName Name = NameInfo.getName();
8862   StorageClass SC = getFunctionStorageClass(*this, D);
8863 
8864   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8865     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8866          diag::err_invalid_thread)
8867       << DeclSpec::getSpecifierName(TSCS);
8868 
8869   if (D.isFirstDeclarationOfMember())
8870     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8871                            D.getIdentifierLoc());
8872 
8873   bool isFriend = false;
8874   FunctionTemplateDecl *FunctionTemplate = nullptr;
8875   bool isMemberSpecialization = false;
8876   bool isFunctionTemplateSpecialization = false;
8877 
8878   bool isDependentClassScopeExplicitSpecialization = false;
8879   bool HasExplicitTemplateArgs = false;
8880   TemplateArgumentListInfo TemplateArgs;
8881 
8882   bool isVirtualOkay = false;
8883 
8884   DeclContext *OriginalDC = DC;
8885   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8886 
8887   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8888                                               isVirtualOkay);
8889   if (!NewFD) return nullptr;
8890 
8891   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8892     NewFD->setTopLevelDeclInObjCContainer();
8893 
8894   // Set the lexical context. If this is a function-scope declaration, or has a
8895   // C++ scope specifier, or is the object of a friend declaration, the lexical
8896   // context will be different from the semantic context.
8897   NewFD->setLexicalDeclContext(CurContext);
8898 
8899   if (IsLocalExternDecl)
8900     NewFD->setLocalExternDecl();
8901 
8902   if (getLangOpts().CPlusPlus) {
8903     bool isInline = D.getDeclSpec().isInlineSpecified();
8904     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8905     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8906     isFriend = D.getDeclSpec().isFriendSpecified();
8907     if (isFriend && !isInline && D.isFunctionDefinition()) {
8908       // C++ [class.friend]p5
8909       //   A function can be defined in a friend declaration of a
8910       //   class . . . . Such a function is implicitly inline.
8911       NewFD->setImplicitlyInline();
8912     }
8913 
8914     // If this is a method defined in an __interface, and is not a constructor
8915     // or an overloaded operator, then set the pure flag (isVirtual will already
8916     // return true).
8917     if (const CXXRecordDecl *Parent =
8918           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8919       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8920         NewFD->setPure(true);
8921 
8922       // C++ [class.union]p2
8923       //   A union can have member functions, but not virtual functions.
8924       if (isVirtual && Parent->isUnion())
8925         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8926     }
8927 
8928     SetNestedNameSpecifier(*this, NewFD, D);
8929     isMemberSpecialization = false;
8930     isFunctionTemplateSpecialization = false;
8931     if (D.isInvalidType())
8932       NewFD->setInvalidDecl();
8933 
8934     // Match up the template parameter lists with the scope specifier, then
8935     // determine whether we have a template or a template specialization.
8936     bool Invalid = false;
8937     TemplateParameterList *TemplateParams =
8938         MatchTemplateParametersToScopeSpecifier(
8939             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8940             D.getCXXScopeSpec(),
8941             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8942                 ? D.getName().TemplateId
8943                 : nullptr,
8944             TemplateParamLists, isFriend, isMemberSpecialization,
8945             Invalid);
8946     if (TemplateParams) {
8947       // Check that we can declare a template here.
8948       if (CheckTemplateDeclScope(S, TemplateParams))
8949         NewFD->setInvalidDecl();
8950 
8951       if (TemplateParams->size() > 0) {
8952         // This is a function template
8953 
8954         // A destructor cannot be a template.
8955         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8956           Diag(NewFD->getLocation(), diag::err_destructor_template);
8957           NewFD->setInvalidDecl();
8958         }
8959 
8960         // If we're adding a template to a dependent context, we may need to
8961         // rebuilding some of the types used within the template parameter list,
8962         // now that we know what the current instantiation is.
8963         if (DC->isDependentContext()) {
8964           ContextRAII SavedContext(*this, DC);
8965           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8966             Invalid = true;
8967         }
8968 
8969         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8970                                                         NewFD->getLocation(),
8971                                                         Name, TemplateParams,
8972                                                         NewFD);
8973         FunctionTemplate->setLexicalDeclContext(CurContext);
8974         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8975 
8976         // For source fidelity, store the other template param lists.
8977         if (TemplateParamLists.size() > 1) {
8978           NewFD->setTemplateParameterListsInfo(Context,
8979               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8980                   .drop_back(1));
8981         }
8982       } else {
8983         // This is a function template specialization.
8984         isFunctionTemplateSpecialization = true;
8985         // For source fidelity, store all the template param lists.
8986         if (TemplateParamLists.size() > 0)
8987           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8988 
8989         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8990         if (isFriend) {
8991           // We want to remove the "template<>", found here.
8992           SourceRange RemoveRange = TemplateParams->getSourceRange();
8993 
8994           // If we remove the template<> and the name is not a
8995           // template-id, we're actually silently creating a problem:
8996           // the friend declaration will refer to an untemplated decl,
8997           // and clearly the user wants a template specialization.  So
8998           // we need to insert '<>' after the name.
8999           SourceLocation InsertLoc;
9000           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9001             InsertLoc = D.getName().getSourceRange().getEnd();
9002             InsertLoc = getLocForEndOfToken(InsertLoc);
9003           }
9004 
9005           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9006             << Name << RemoveRange
9007             << FixItHint::CreateRemoval(RemoveRange)
9008             << FixItHint::CreateInsertion(InsertLoc, "<>");
9009         }
9010       }
9011     } else {
9012       // Check that we can declare a template here.
9013       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9014           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9015         NewFD->setInvalidDecl();
9016 
9017       // All template param lists were matched against the scope specifier:
9018       // this is NOT (an explicit specialization of) a template.
9019       if (TemplateParamLists.size() > 0)
9020         // For source fidelity, store all the template param lists.
9021         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9022     }
9023 
9024     if (Invalid) {
9025       NewFD->setInvalidDecl();
9026       if (FunctionTemplate)
9027         FunctionTemplate->setInvalidDecl();
9028     }
9029 
9030     // C++ [dcl.fct.spec]p5:
9031     //   The virtual specifier shall only be used in declarations of
9032     //   nonstatic class member functions that appear within a
9033     //   member-specification of a class declaration; see 10.3.
9034     //
9035     if (isVirtual && !NewFD->isInvalidDecl()) {
9036       if (!isVirtualOkay) {
9037         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9038              diag::err_virtual_non_function);
9039       } else if (!CurContext->isRecord()) {
9040         // 'virtual' was specified outside of the class.
9041         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9042              diag::err_virtual_out_of_class)
9043           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9044       } else if (NewFD->getDescribedFunctionTemplate()) {
9045         // C++ [temp.mem]p3:
9046         //  A member function template shall not be virtual.
9047         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9048              diag::err_virtual_member_function_template)
9049           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9050       } else {
9051         // Okay: Add virtual to the method.
9052         NewFD->setVirtualAsWritten(true);
9053       }
9054 
9055       if (getLangOpts().CPlusPlus14 &&
9056           NewFD->getReturnType()->isUndeducedType())
9057         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9058     }
9059 
9060     if (getLangOpts().CPlusPlus14 &&
9061         (NewFD->isDependentContext() ||
9062          (isFriend && CurContext->isDependentContext())) &&
9063         NewFD->getReturnType()->isUndeducedType()) {
9064       // If the function template is referenced directly (for instance, as a
9065       // member of the current instantiation), pretend it has a dependent type.
9066       // This is not really justified by the standard, but is the only sane
9067       // thing to do.
9068       // FIXME: For a friend function, we have not marked the function as being
9069       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9070       const FunctionProtoType *FPT =
9071           NewFD->getType()->castAs<FunctionProtoType>();
9072       QualType Result =
9073           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9074       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9075                                              FPT->getExtProtoInfo()));
9076     }
9077 
9078     // C++ [dcl.fct.spec]p3:
9079     //  The inline specifier shall not appear on a block scope function
9080     //  declaration.
9081     if (isInline && !NewFD->isInvalidDecl()) {
9082       if (CurContext->isFunctionOrMethod()) {
9083         // 'inline' is not allowed on block scope function declaration.
9084         Diag(D.getDeclSpec().getInlineSpecLoc(),
9085              diag::err_inline_declaration_block_scope) << Name
9086           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9087       }
9088     }
9089 
9090     // C++ [dcl.fct.spec]p6:
9091     //  The explicit specifier shall be used only in the declaration of a
9092     //  constructor or conversion function within its class definition;
9093     //  see 12.3.1 and 12.3.2.
9094     if (hasExplicit && !NewFD->isInvalidDecl() &&
9095         !isa<CXXDeductionGuideDecl>(NewFD)) {
9096       if (!CurContext->isRecord()) {
9097         // 'explicit' was specified outside of the class.
9098         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9099              diag::err_explicit_out_of_class)
9100             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9101       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9102                  !isa<CXXConversionDecl>(NewFD)) {
9103         // 'explicit' was specified on a function that wasn't a constructor
9104         // or conversion function.
9105         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9106              diag::err_explicit_non_ctor_or_conv_function)
9107             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9108       }
9109     }
9110 
9111     if (ConstexprSpecKind ConstexprKind =
9112             D.getDeclSpec().getConstexprSpecifier()) {
9113       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9114       // are implicitly inline.
9115       NewFD->setImplicitlyInline();
9116 
9117       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9118       // be either constructors or to return a literal type. Therefore,
9119       // destructors cannot be declared constexpr.
9120       if (isa<CXXDestructorDecl>(NewFD) &&
9121           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9122         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9123             << ConstexprKind;
9124         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9125       }
9126       // C++20 [dcl.constexpr]p2: An allocation function, or a
9127       // deallocation function shall not be declared with the consteval
9128       // specifier.
9129       if (ConstexprKind == CSK_consteval &&
9130           (NewFD->getOverloadedOperator() == OO_New ||
9131            NewFD->getOverloadedOperator() == OO_Array_New ||
9132            NewFD->getOverloadedOperator() == OO_Delete ||
9133            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9134         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9135              diag::err_invalid_consteval_decl_kind)
9136             << NewFD;
9137         NewFD->setConstexprKind(CSK_constexpr);
9138       }
9139     }
9140 
9141     // If __module_private__ was specified, mark the function accordingly.
9142     if (D.getDeclSpec().isModulePrivateSpecified()) {
9143       if (isFunctionTemplateSpecialization) {
9144         SourceLocation ModulePrivateLoc
9145           = D.getDeclSpec().getModulePrivateSpecLoc();
9146         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9147           << 0
9148           << FixItHint::CreateRemoval(ModulePrivateLoc);
9149       } else {
9150         NewFD->setModulePrivate();
9151         if (FunctionTemplate)
9152           FunctionTemplate->setModulePrivate();
9153       }
9154     }
9155 
9156     if (isFriend) {
9157       if (FunctionTemplate) {
9158         FunctionTemplate->setObjectOfFriendDecl();
9159         FunctionTemplate->setAccess(AS_public);
9160       }
9161       NewFD->setObjectOfFriendDecl();
9162       NewFD->setAccess(AS_public);
9163     }
9164 
9165     // If a function is defined as defaulted or deleted, mark it as such now.
9166     // We'll do the relevant checks on defaulted / deleted functions later.
9167     switch (D.getFunctionDefinitionKind()) {
9168       case FDK_Declaration:
9169       case FDK_Definition:
9170         break;
9171 
9172       case FDK_Defaulted:
9173         NewFD->setDefaulted();
9174         break;
9175 
9176       case FDK_Deleted:
9177         NewFD->setDeletedAsWritten();
9178         break;
9179     }
9180 
9181     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9182         D.isFunctionDefinition()) {
9183       // C++ [class.mfct]p2:
9184       //   A member function may be defined (8.4) in its class definition, in
9185       //   which case it is an inline member function (7.1.2)
9186       NewFD->setImplicitlyInline();
9187     }
9188 
9189     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9190         !CurContext->isRecord()) {
9191       // C++ [class.static]p1:
9192       //   A data or function member of a class may be declared static
9193       //   in a class definition, in which case it is a static member of
9194       //   the class.
9195 
9196       // Complain about the 'static' specifier if it's on an out-of-line
9197       // member function definition.
9198 
9199       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9200       // member function template declaration and class member template
9201       // declaration (MSVC versions before 2015), warn about this.
9202       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9203            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9204              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9205            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9206            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9207         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9208     }
9209 
9210     // C++11 [except.spec]p15:
9211     //   A deallocation function with no exception-specification is treated
9212     //   as if it were specified with noexcept(true).
9213     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9214     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9215          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9216         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9217       NewFD->setType(Context.getFunctionType(
9218           FPT->getReturnType(), FPT->getParamTypes(),
9219           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9220   }
9221 
9222   // Filter out previous declarations that don't match the scope.
9223   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9224                        D.getCXXScopeSpec().isNotEmpty() ||
9225                        isMemberSpecialization ||
9226                        isFunctionTemplateSpecialization);
9227 
9228   // Handle GNU asm-label extension (encoded as an attribute).
9229   if (Expr *E = (Expr*) D.getAsmLabel()) {
9230     // The parser guarantees this is a string.
9231     StringLiteral *SE = cast<StringLiteral>(E);
9232     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9233                                         /*IsLiteralLabel=*/true,
9234                                         SE->getStrTokenLoc(0)));
9235   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9236     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9237       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9238     if (I != ExtnameUndeclaredIdentifiers.end()) {
9239       if (isDeclExternC(NewFD)) {
9240         NewFD->addAttr(I->second);
9241         ExtnameUndeclaredIdentifiers.erase(I);
9242       } else
9243         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9244             << /*Variable*/0 << NewFD;
9245     }
9246   }
9247 
9248   // Copy the parameter declarations from the declarator D to the function
9249   // declaration NewFD, if they are available.  First scavenge them into Params.
9250   SmallVector<ParmVarDecl*, 16> Params;
9251   unsigned FTIIdx;
9252   if (D.isFunctionDeclarator(FTIIdx)) {
9253     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9254 
9255     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9256     // function that takes no arguments, not a function that takes a
9257     // single void argument.
9258     // We let through "const void" here because Sema::GetTypeForDeclarator
9259     // already checks for that case.
9260     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9261       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9262         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9263         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9264         Param->setDeclContext(NewFD);
9265         Params.push_back(Param);
9266 
9267         if (Param->isInvalidDecl())
9268           NewFD->setInvalidDecl();
9269       }
9270     }
9271 
9272     if (!getLangOpts().CPlusPlus) {
9273       // In C, find all the tag declarations from the prototype and move them
9274       // into the function DeclContext. Remove them from the surrounding tag
9275       // injection context of the function, which is typically but not always
9276       // the TU.
9277       DeclContext *PrototypeTagContext =
9278           getTagInjectionContext(NewFD->getLexicalDeclContext());
9279       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9280         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9281 
9282         // We don't want to reparent enumerators. Look at their parent enum
9283         // instead.
9284         if (!TD) {
9285           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9286             TD = cast<EnumDecl>(ECD->getDeclContext());
9287         }
9288         if (!TD)
9289           continue;
9290         DeclContext *TagDC = TD->getLexicalDeclContext();
9291         if (!TagDC->containsDecl(TD))
9292           continue;
9293         TagDC->removeDecl(TD);
9294         TD->setDeclContext(NewFD);
9295         NewFD->addDecl(TD);
9296 
9297         // Preserve the lexical DeclContext if it is not the surrounding tag
9298         // injection context of the FD. In this example, the semantic context of
9299         // E will be f and the lexical context will be S, while both the
9300         // semantic and lexical contexts of S will be f:
9301         //   void f(struct S { enum E { a } f; } s);
9302         if (TagDC != PrototypeTagContext)
9303           TD->setLexicalDeclContext(TagDC);
9304       }
9305     }
9306   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9307     // When we're declaring a function with a typedef, typeof, etc as in the
9308     // following example, we'll need to synthesize (unnamed)
9309     // parameters for use in the declaration.
9310     //
9311     // @code
9312     // typedef void fn(int);
9313     // fn f;
9314     // @endcode
9315 
9316     // Synthesize a parameter for each argument type.
9317     for (const auto &AI : FT->param_types()) {
9318       ParmVarDecl *Param =
9319           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9320       Param->setScopeInfo(0, Params.size());
9321       Params.push_back(Param);
9322     }
9323   } else {
9324     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9325            "Should not need args for typedef of non-prototype fn");
9326   }
9327 
9328   // Finally, we know we have the right number of parameters, install them.
9329   NewFD->setParams(Params);
9330 
9331   if (D.getDeclSpec().isNoreturnSpecified())
9332     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9333                                            D.getDeclSpec().getNoreturnSpecLoc(),
9334                                            AttributeCommonInfo::AS_Keyword));
9335 
9336   // Functions returning a variably modified type violate C99 6.7.5.2p2
9337   // because all functions have linkage.
9338   if (!NewFD->isInvalidDecl() &&
9339       NewFD->getReturnType()->isVariablyModifiedType()) {
9340     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9341     NewFD->setInvalidDecl();
9342   }
9343 
9344   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9345   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9346       !NewFD->hasAttr<SectionAttr>())
9347     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9348         Context, PragmaClangTextSection.SectionName,
9349         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9350 
9351   // Apply an implicit SectionAttr if #pragma code_seg is active.
9352   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9353       !NewFD->hasAttr<SectionAttr>()) {
9354     NewFD->addAttr(SectionAttr::CreateImplicit(
9355         Context, CodeSegStack.CurrentValue->getString(),
9356         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9357         SectionAttr::Declspec_allocate));
9358     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9359                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9360                          ASTContext::PSF_Read,
9361                      NewFD))
9362       NewFD->dropAttr<SectionAttr>();
9363   }
9364 
9365   // Apply an implicit CodeSegAttr from class declspec or
9366   // apply an implicit SectionAttr from #pragma code_seg if active.
9367   if (!NewFD->hasAttr<CodeSegAttr>()) {
9368     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9369                                                                  D.isFunctionDefinition())) {
9370       NewFD->addAttr(SAttr);
9371     }
9372   }
9373 
9374   // Handle attributes.
9375   ProcessDeclAttributes(S, NewFD, D);
9376 
9377   if (getLangOpts().OpenCL) {
9378     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9379     // type declaration will generate a compilation error.
9380     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9381     if (AddressSpace != LangAS::Default) {
9382       Diag(NewFD->getLocation(),
9383            diag::err_opencl_return_value_with_address_space);
9384       NewFD->setInvalidDecl();
9385     }
9386   }
9387 
9388   if (!getLangOpts().CPlusPlus) {
9389     // Perform semantic checking on the function declaration.
9390     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9391       CheckMain(NewFD, D.getDeclSpec());
9392 
9393     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9394       CheckMSVCRTEntryPoint(NewFD);
9395 
9396     if (!NewFD->isInvalidDecl())
9397       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9398                                                   isMemberSpecialization));
9399     else if (!Previous.empty())
9400       // Recover gracefully from an invalid redeclaration.
9401       D.setRedeclaration(true);
9402     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9403             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9404            "previous declaration set still overloaded");
9405 
9406     // Diagnose no-prototype function declarations with calling conventions that
9407     // don't support variadic calls. Only do this in C and do it after merging
9408     // possibly prototyped redeclarations.
9409     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9410     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9411       CallingConv CC = FT->getExtInfo().getCC();
9412       if (!supportsVariadicCall(CC)) {
9413         // Windows system headers sometimes accidentally use stdcall without
9414         // (void) parameters, so we relax this to a warning.
9415         int DiagID =
9416             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9417         Diag(NewFD->getLocation(), DiagID)
9418             << FunctionType::getNameForCallConv(CC);
9419       }
9420     }
9421 
9422    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9423        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9424      checkNonTrivialCUnion(NewFD->getReturnType(),
9425                            NewFD->getReturnTypeSourceRange().getBegin(),
9426                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9427   } else {
9428     // C++11 [replacement.functions]p3:
9429     //  The program's definitions shall not be specified as inline.
9430     //
9431     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9432     //
9433     // Suppress the diagnostic if the function is __attribute__((used)), since
9434     // that forces an external definition to be emitted.
9435     if (D.getDeclSpec().isInlineSpecified() &&
9436         NewFD->isReplaceableGlobalAllocationFunction() &&
9437         !NewFD->hasAttr<UsedAttr>())
9438       Diag(D.getDeclSpec().getInlineSpecLoc(),
9439            diag::ext_operator_new_delete_declared_inline)
9440         << NewFD->getDeclName();
9441 
9442     // If the declarator is a template-id, translate the parser's template
9443     // argument list into our AST format.
9444     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9445       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9446       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9447       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9448       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9449                                          TemplateId->NumArgs);
9450       translateTemplateArguments(TemplateArgsPtr,
9451                                  TemplateArgs);
9452 
9453       HasExplicitTemplateArgs = true;
9454 
9455       if (NewFD->isInvalidDecl()) {
9456         HasExplicitTemplateArgs = false;
9457       } else if (FunctionTemplate) {
9458         // Function template with explicit template arguments.
9459         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9460           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9461 
9462         HasExplicitTemplateArgs = false;
9463       } else {
9464         assert((isFunctionTemplateSpecialization ||
9465                 D.getDeclSpec().isFriendSpecified()) &&
9466                "should have a 'template<>' for this decl");
9467         // "friend void foo<>(int);" is an implicit specialization decl.
9468         isFunctionTemplateSpecialization = true;
9469       }
9470     } else if (isFriend && isFunctionTemplateSpecialization) {
9471       // This combination is only possible in a recovery case;  the user
9472       // wrote something like:
9473       //   template <> friend void foo(int);
9474       // which we're recovering from as if the user had written:
9475       //   friend void foo<>(int);
9476       // Go ahead and fake up a template id.
9477       HasExplicitTemplateArgs = true;
9478       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9479       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9480     }
9481 
9482     // We do not add HD attributes to specializations here because
9483     // they may have different constexpr-ness compared to their
9484     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9485     // may end up with different effective targets. Instead, a
9486     // specialization inherits its target attributes from its template
9487     // in the CheckFunctionTemplateSpecialization() call below.
9488     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9489       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9490 
9491     // If it's a friend (and only if it's a friend), it's possible
9492     // that either the specialized function type or the specialized
9493     // template is dependent, and therefore matching will fail.  In
9494     // this case, don't check the specialization yet.
9495     bool InstantiationDependent = false;
9496     if (isFunctionTemplateSpecialization && isFriend &&
9497         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9498          TemplateSpecializationType::anyDependentTemplateArguments(
9499             TemplateArgs,
9500             InstantiationDependent))) {
9501       assert(HasExplicitTemplateArgs &&
9502              "friend function specialization without template args");
9503       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9504                                                        Previous))
9505         NewFD->setInvalidDecl();
9506     } else if (isFunctionTemplateSpecialization) {
9507       if (CurContext->isDependentContext() && CurContext->isRecord()
9508           && !isFriend) {
9509         isDependentClassScopeExplicitSpecialization = true;
9510       } else if (!NewFD->isInvalidDecl() &&
9511                  CheckFunctionTemplateSpecialization(
9512                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9513                      Previous))
9514         NewFD->setInvalidDecl();
9515 
9516       // C++ [dcl.stc]p1:
9517       //   A storage-class-specifier shall not be specified in an explicit
9518       //   specialization (14.7.3)
9519       FunctionTemplateSpecializationInfo *Info =
9520           NewFD->getTemplateSpecializationInfo();
9521       if (Info && SC != SC_None) {
9522         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9523           Diag(NewFD->getLocation(),
9524                diag::err_explicit_specialization_inconsistent_storage_class)
9525             << SC
9526             << FixItHint::CreateRemoval(
9527                                       D.getDeclSpec().getStorageClassSpecLoc());
9528 
9529         else
9530           Diag(NewFD->getLocation(),
9531                diag::ext_explicit_specialization_storage_class)
9532             << FixItHint::CreateRemoval(
9533                                       D.getDeclSpec().getStorageClassSpecLoc());
9534       }
9535     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9536       if (CheckMemberSpecialization(NewFD, Previous))
9537           NewFD->setInvalidDecl();
9538     }
9539 
9540     // Perform semantic checking on the function declaration.
9541     if (!isDependentClassScopeExplicitSpecialization) {
9542       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9543         CheckMain(NewFD, D.getDeclSpec());
9544 
9545       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9546         CheckMSVCRTEntryPoint(NewFD);
9547 
9548       if (!NewFD->isInvalidDecl())
9549         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9550                                                     isMemberSpecialization));
9551       else if (!Previous.empty())
9552         // Recover gracefully from an invalid redeclaration.
9553         D.setRedeclaration(true);
9554     }
9555 
9556     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9557             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9558            "previous declaration set still overloaded");
9559 
9560     NamedDecl *PrincipalDecl = (FunctionTemplate
9561                                 ? cast<NamedDecl>(FunctionTemplate)
9562                                 : NewFD);
9563 
9564     if (isFriend && NewFD->getPreviousDecl()) {
9565       AccessSpecifier Access = AS_public;
9566       if (!NewFD->isInvalidDecl())
9567         Access = NewFD->getPreviousDecl()->getAccess();
9568 
9569       NewFD->setAccess(Access);
9570       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9571     }
9572 
9573     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9574         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9575       PrincipalDecl->setNonMemberOperator();
9576 
9577     // If we have a function template, check the template parameter
9578     // list. This will check and merge default template arguments.
9579     if (FunctionTemplate) {
9580       FunctionTemplateDecl *PrevTemplate =
9581                                      FunctionTemplate->getPreviousDecl();
9582       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9583                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9584                                     : nullptr,
9585                             D.getDeclSpec().isFriendSpecified()
9586                               ? (D.isFunctionDefinition()
9587                                    ? TPC_FriendFunctionTemplateDefinition
9588                                    : TPC_FriendFunctionTemplate)
9589                               : (D.getCXXScopeSpec().isSet() &&
9590                                  DC && DC->isRecord() &&
9591                                  DC->isDependentContext())
9592                                   ? TPC_ClassTemplateMember
9593                                   : TPC_FunctionTemplate);
9594     }
9595 
9596     if (NewFD->isInvalidDecl()) {
9597       // Ignore all the rest of this.
9598     } else if (!D.isRedeclaration()) {
9599       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9600                                        AddToScope };
9601       // Fake up an access specifier if it's supposed to be a class member.
9602       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9603         NewFD->setAccess(AS_public);
9604 
9605       // Qualified decls generally require a previous declaration.
9606       if (D.getCXXScopeSpec().isSet()) {
9607         // ...with the major exception of templated-scope or
9608         // dependent-scope friend declarations.
9609 
9610         // TODO: we currently also suppress this check in dependent
9611         // contexts because (1) the parameter depth will be off when
9612         // matching friend templates and (2) we might actually be
9613         // selecting a friend based on a dependent factor.  But there
9614         // are situations where these conditions don't apply and we
9615         // can actually do this check immediately.
9616         //
9617         // Unless the scope is dependent, it's always an error if qualified
9618         // redeclaration lookup found nothing at all. Diagnose that now;
9619         // nothing will diagnose that error later.
9620         if (isFriend &&
9621             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9622              (!Previous.empty() && CurContext->isDependentContext()))) {
9623           // ignore these
9624         } else {
9625           // The user tried to provide an out-of-line definition for a
9626           // function that is a member of a class or namespace, but there
9627           // was no such member function declared (C++ [class.mfct]p2,
9628           // C++ [namespace.memdef]p2). For example:
9629           //
9630           // class X {
9631           //   void f() const;
9632           // };
9633           //
9634           // void X::f() { } // ill-formed
9635           //
9636           // Complain about this problem, and attempt to suggest close
9637           // matches (e.g., those that differ only in cv-qualifiers and
9638           // whether the parameter types are references).
9639 
9640           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9641                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9642             AddToScope = ExtraArgs.AddToScope;
9643             return Result;
9644           }
9645         }
9646 
9647         // Unqualified local friend declarations are required to resolve
9648         // to something.
9649       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9650         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9651                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9652           AddToScope = ExtraArgs.AddToScope;
9653           return Result;
9654         }
9655       }
9656     } else if (!D.isFunctionDefinition() &&
9657                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9658                !isFriend && !isFunctionTemplateSpecialization &&
9659                !isMemberSpecialization) {
9660       // An out-of-line member function declaration must also be a
9661       // definition (C++ [class.mfct]p2).
9662       // Note that this is not the case for explicit specializations of
9663       // function templates or member functions of class templates, per
9664       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9665       // extension for compatibility with old SWIG code which likes to
9666       // generate them.
9667       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9668         << D.getCXXScopeSpec().getRange();
9669     }
9670   }
9671 
9672   ProcessPragmaWeak(S, NewFD);
9673   checkAttributesAfterMerging(*this, *NewFD);
9674 
9675   AddKnownFunctionAttributes(NewFD);
9676 
9677   if (NewFD->hasAttr<OverloadableAttr>() &&
9678       !NewFD->getType()->getAs<FunctionProtoType>()) {
9679     Diag(NewFD->getLocation(),
9680          diag::err_attribute_overloadable_no_prototype)
9681       << NewFD;
9682 
9683     // Turn this into a variadic function with no parameters.
9684     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9685     FunctionProtoType::ExtProtoInfo EPI(
9686         Context.getDefaultCallingConvention(true, false));
9687     EPI.Variadic = true;
9688     EPI.ExtInfo = FT->getExtInfo();
9689 
9690     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9691     NewFD->setType(R);
9692   }
9693 
9694   // If there's a #pragma GCC visibility in scope, and this isn't a class
9695   // member, set the visibility of this function.
9696   if (!DC->isRecord() && NewFD->isExternallyVisible())
9697     AddPushedVisibilityAttribute(NewFD);
9698 
9699   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9700   // marking the function.
9701   AddCFAuditedAttribute(NewFD);
9702 
9703   // If this is a function definition, check if we have to apply optnone due to
9704   // a pragma.
9705   if(D.isFunctionDefinition())
9706     AddRangeBasedOptnone(NewFD);
9707 
9708   // If this is the first declaration of an extern C variable, update
9709   // the map of such variables.
9710   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9711       isIncompleteDeclExternC(*this, NewFD))
9712     RegisterLocallyScopedExternCDecl(NewFD, S);
9713 
9714   // Set this FunctionDecl's range up to the right paren.
9715   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9716 
9717   if (D.isRedeclaration() && !Previous.empty()) {
9718     NamedDecl *Prev = Previous.getRepresentativeDecl();
9719     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9720                                    isMemberSpecialization ||
9721                                        isFunctionTemplateSpecialization,
9722                                    D.isFunctionDefinition());
9723   }
9724 
9725   if (getLangOpts().CUDA) {
9726     IdentifierInfo *II = NewFD->getIdentifier();
9727     if (II && II->isStr(getCudaConfigureFuncName()) &&
9728         !NewFD->isInvalidDecl() &&
9729         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9730       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9731         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9732             << getCudaConfigureFuncName();
9733       Context.setcudaConfigureCallDecl(NewFD);
9734     }
9735 
9736     // Variadic functions, other than a *declaration* of printf, are not allowed
9737     // in device-side CUDA code, unless someone passed
9738     // -fcuda-allow-variadic-functions.
9739     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9740         (NewFD->hasAttr<CUDADeviceAttr>() ||
9741          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9742         !(II && II->isStr("printf") && NewFD->isExternC() &&
9743           !D.isFunctionDefinition())) {
9744       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9745     }
9746   }
9747 
9748   MarkUnusedFileScopedDecl(NewFD);
9749 
9750 
9751 
9752   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9753     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9754     if ((getLangOpts().OpenCLVersion >= 120)
9755         && (SC == SC_Static)) {
9756       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9757       D.setInvalidType();
9758     }
9759 
9760     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9761     if (!NewFD->getReturnType()->isVoidType()) {
9762       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9763       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9764           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9765                                 : FixItHint());
9766       D.setInvalidType();
9767     }
9768 
9769     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9770     for (auto Param : NewFD->parameters())
9771       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9772 
9773     if (getLangOpts().OpenCLCPlusPlus) {
9774       if (DC->isRecord()) {
9775         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9776         D.setInvalidType();
9777       }
9778       if (FunctionTemplate) {
9779         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9780         D.setInvalidType();
9781       }
9782     }
9783   }
9784 
9785   if (getLangOpts().CPlusPlus) {
9786     if (FunctionTemplate) {
9787       if (NewFD->isInvalidDecl())
9788         FunctionTemplate->setInvalidDecl();
9789       return FunctionTemplate;
9790     }
9791 
9792     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9793       CompleteMemberSpecialization(NewFD, Previous);
9794   }
9795 
9796   for (const ParmVarDecl *Param : NewFD->parameters()) {
9797     QualType PT = Param->getType();
9798 
9799     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9800     // types.
9801     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9802       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9803         QualType ElemTy = PipeTy->getElementType();
9804           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9805             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9806             D.setInvalidType();
9807           }
9808       }
9809     }
9810   }
9811 
9812   // Here we have an function template explicit specialization at class scope.
9813   // The actual specialization will be postponed to template instatiation
9814   // time via the ClassScopeFunctionSpecializationDecl node.
9815   if (isDependentClassScopeExplicitSpecialization) {
9816     ClassScopeFunctionSpecializationDecl *NewSpec =
9817                          ClassScopeFunctionSpecializationDecl::Create(
9818                                 Context, CurContext, NewFD->getLocation(),
9819                                 cast<CXXMethodDecl>(NewFD),
9820                                 HasExplicitTemplateArgs, TemplateArgs);
9821     CurContext->addDecl(NewSpec);
9822     AddToScope = false;
9823   }
9824 
9825   // Diagnose availability attributes. Availability cannot be used on functions
9826   // that are run during load/unload.
9827   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9828     if (NewFD->hasAttr<ConstructorAttr>()) {
9829       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9830           << 1;
9831       NewFD->dropAttr<AvailabilityAttr>();
9832     }
9833     if (NewFD->hasAttr<DestructorAttr>()) {
9834       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9835           << 2;
9836       NewFD->dropAttr<AvailabilityAttr>();
9837     }
9838   }
9839 
9840   // Diagnose no_builtin attribute on function declaration that are not a
9841   // definition.
9842   // FIXME: We should really be doing this in
9843   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9844   // the FunctionDecl and at this point of the code
9845   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9846   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9847   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9848     switch (D.getFunctionDefinitionKind()) {
9849     case FDK_Defaulted:
9850     case FDK_Deleted:
9851       Diag(NBA->getLocation(),
9852            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9853           << NBA->getSpelling();
9854       break;
9855     case FDK_Declaration:
9856       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9857           << NBA->getSpelling();
9858       break;
9859     case FDK_Definition:
9860       break;
9861     }
9862 
9863   return NewFD;
9864 }
9865 
9866 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9867 /// when __declspec(code_seg) "is applied to a class, all member functions of
9868 /// the class and nested classes -- this includes compiler-generated special
9869 /// member functions -- are put in the specified segment."
9870 /// The actual behavior is a little more complicated. The Microsoft compiler
9871 /// won't check outer classes if there is an active value from #pragma code_seg.
9872 /// The CodeSeg is always applied from the direct parent but only from outer
9873 /// classes when the #pragma code_seg stack is empty. See:
9874 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9875 /// available since MS has removed the page.
9876 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9877   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9878   if (!Method)
9879     return nullptr;
9880   const CXXRecordDecl *Parent = Method->getParent();
9881   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9882     Attr *NewAttr = SAttr->clone(S.getASTContext());
9883     NewAttr->setImplicit(true);
9884     return NewAttr;
9885   }
9886 
9887   // The Microsoft compiler won't check outer classes for the CodeSeg
9888   // when the #pragma code_seg stack is active.
9889   if (S.CodeSegStack.CurrentValue)
9890    return nullptr;
9891 
9892   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9893     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9894       Attr *NewAttr = SAttr->clone(S.getASTContext());
9895       NewAttr->setImplicit(true);
9896       return NewAttr;
9897     }
9898   }
9899   return nullptr;
9900 }
9901 
9902 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9903 /// containing class. Otherwise it will return implicit SectionAttr if the
9904 /// function is a definition and there is an active value on CodeSegStack
9905 /// (from the current #pragma code-seg value).
9906 ///
9907 /// \param FD Function being declared.
9908 /// \param IsDefinition Whether it is a definition or just a declarartion.
9909 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9910 ///          nullptr if no attribute should be added.
9911 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9912                                                        bool IsDefinition) {
9913   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9914     return A;
9915   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9916       CodeSegStack.CurrentValue)
9917     return SectionAttr::CreateImplicit(
9918         getASTContext(), CodeSegStack.CurrentValue->getString(),
9919         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9920         SectionAttr::Declspec_allocate);
9921   return nullptr;
9922 }
9923 
9924 /// Determines if we can perform a correct type check for \p D as a
9925 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9926 /// best-effort check.
9927 ///
9928 /// \param NewD The new declaration.
9929 /// \param OldD The old declaration.
9930 /// \param NewT The portion of the type of the new declaration to check.
9931 /// \param OldT The portion of the type of the old declaration to check.
9932 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9933                                           QualType NewT, QualType OldT) {
9934   if (!NewD->getLexicalDeclContext()->isDependentContext())
9935     return true;
9936 
9937   // For dependently-typed local extern declarations and friends, we can't
9938   // perform a correct type check in general until instantiation:
9939   //
9940   //   int f();
9941   //   template<typename T> void g() { T f(); }
9942   //
9943   // (valid if g() is only instantiated with T = int).
9944   if (NewT->isDependentType() &&
9945       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9946     return false;
9947 
9948   // Similarly, if the previous declaration was a dependent local extern
9949   // declaration, we don't really know its type yet.
9950   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9951     return false;
9952 
9953   return true;
9954 }
9955 
9956 /// Checks if the new declaration declared in dependent context must be
9957 /// put in the same redeclaration chain as the specified declaration.
9958 ///
9959 /// \param D Declaration that is checked.
9960 /// \param PrevDecl Previous declaration found with proper lookup method for the
9961 ///                 same declaration name.
9962 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9963 ///          belongs to.
9964 ///
9965 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9966   if (!D->getLexicalDeclContext()->isDependentContext())
9967     return true;
9968 
9969   // Don't chain dependent friend function definitions until instantiation, to
9970   // permit cases like
9971   //
9972   //   void func();
9973   //   template<typename T> class C1 { friend void func() {} };
9974   //   template<typename T> class C2 { friend void func() {} };
9975   //
9976   // ... which is valid if only one of C1 and C2 is ever instantiated.
9977   //
9978   // FIXME: This need only apply to function definitions. For now, we proxy
9979   // this by checking for a file-scope function. We do not want this to apply
9980   // to friend declarations nominating member functions, because that gets in
9981   // the way of access checks.
9982   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9983     return false;
9984 
9985   auto *VD = dyn_cast<ValueDecl>(D);
9986   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9987   return !VD || !PrevVD ||
9988          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9989                                         PrevVD->getType());
9990 }
9991 
9992 /// Check the target attribute of the function for MultiVersion
9993 /// validity.
9994 ///
9995 /// Returns true if there was an error, false otherwise.
9996 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9997   const auto *TA = FD->getAttr<TargetAttr>();
9998   assert(TA && "MultiVersion Candidate requires a target attribute");
9999   ParsedTargetAttr ParseInfo = TA->parse();
10000   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10001   enum ErrType { Feature = 0, Architecture = 1 };
10002 
10003   if (!ParseInfo.Architecture.empty() &&
10004       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10005     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10006         << Architecture << ParseInfo.Architecture;
10007     return true;
10008   }
10009 
10010   for (const auto &Feat : ParseInfo.Features) {
10011     auto BareFeat = StringRef{Feat}.substr(1);
10012     if (Feat[0] == '-') {
10013       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10014           << Feature << ("no-" + BareFeat).str();
10015       return true;
10016     }
10017 
10018     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10019         !TargetInfo.isValidFeatureName(BareFeat)) {
10020       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10021           << Feature << BareFeat;
10022       return true;
10023     }
10024   }
10025   return false;
10026 }
10027 
10028 // Provide a white-list of attributes that are allowed to be combined with
10029 // multiversion functions.
10030 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10031                                            MultiVersionKind MVType) {
10032   // Note: this list/diagnosis must match the list in
10033   // checkMultiversionAttributesAllSame.
10034   switch (Kind) {
10035   default:
10036     return false;
10037   case attr::Used:
10038     return MVType == MultiVersionKind::Target;
10039   case attr::NonNull:
10040   case attr::NoThrow:
10041     return true;
10042   }
10043 }
10044 
10045 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10046                                                  const FunctionDecl *FD,
10047                                                  const FunctionDecl *CausedFD,
10048                                                  MultiVersionKind MVType) {
10049   bool IsCPUSpecificCPUDispatchMVType =
10050       MVType == MultiVersionKind::CPUDispatch ||
10051       MVType == MultiVersionKind::CPUSpecific;
10052   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10053                             Sema &S, const Attr *A) {
10054     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10055         << IsCPUSpecificCPUDispatchMVType << A;
10056     if (CausedFD)
10057       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10058     return true;
10059   };
10060 
10061   for (const Attr *A : FD->attrs()) {
10062     switch (A->getKind()) {
10063     case attr::CPUDispatch:
10064     case attr::CPUSpecific:
10065       if (MVType != MultiVersionKind::CPUDispatch &&
10066           MVType != MultiVersionKind::CPUSpecific)
10067         return Diagnose(S, A);
10068       break;
10069     case attr::Target:
10070       if (MVType != MultiVersionKind::Target)
10071         return Diagnose(S, A);
10072       break;
10073     default:
10074       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10075         return Diagnose(S, A);
10076       break;
10077     }
10078   }
10079   return false;
10080 }
10081 
10082 bool Sema::areMultiversionVariantFunctionsCompatible(
10083     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10084     const PartialDiagnostic &NoProtoDiagID,
10085     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10086     const PartialDiagnosticAt &NoSupportDiagIDAt,
10087     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10088     bool ConstexprSupported, bool CLinkageMayDiffer) {
10089   enum DoesntSupport {
10090     FuncTemplates = 0,
10091     VirtFuncs = 1,
10092     DeducedReturn = 2,
10093     Constructors = 3,
10094     Destructors = 4,
10095     DeletedFuncs = 5,
10096     DefaultedFuncs = 6,
10097     ConstexprFuncs = 7,
10098     ConstevalFuncs = 8,
10099   };
10100   enum Different {
10101     CallingConv = 0,
10102     ReturnType = 1,
10103     ConstexprSpec = 2,
10104     InlineSpec = 3,
10105     StorageClass = 4,
10106     Linkage = 5,
10107   };
10108 
10109   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10110       !OldFD->getType()->getAs<FunctionProtoType>()) {
10111     Diag(OldFD->getLocation(), NoProtoDiagID);
10112     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10113     return true;
10114   }
10115 
10116   if (NoProtoDiagID.getDiagID() != 0 &&
10117       !NewFD->getType()->getAs<FunctionProtoType>())
10118     return Diag(NewFD->getLocation(), NoProtoDiagID);
10119 
10120   if (!TemplatesSupported &&
10121       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10122     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10123            << FuncTemplates;
10124 
10125   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10126     if (NewCXXFD->isVirtual())
10127       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10128              << VirtFuncs;
10129 
10130     if (isa<CXXConstructorDecl>(NewCXXFD))
10131       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10132              << Constructors;
10133 
10134     if (isa<CXXDestructorDecl>(NewCXXFD))
10135       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10136              << Destructors;
10137   }
10138 
10139   if (NewFD->isDeleted())
10140     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10141            << DeletedFuncs;
10142 
10143   if (NewFD->isDefaulted())
10144     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10145            << DefaultedFuncs;
10146 
10147   if (!ConstexprSupported && NewFD->isConstexpr())
10148     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10149            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10150 
10151   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10152   const auto *NewType = cast<FunctionType>(NewQType);
10153   QualType NewReturnType = NewType->getReturnType();
10154 
10155   if (NewReturnType->isUndeducedType())
10156     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10157            << DeducedReturn;
10158 
10159   // Ensure the return type is identical.
10160   if (OldFD) {
10161     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10162     const auto *OldType = cast<FunctionType>(OldQType);
10163     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10164     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10165 
10166     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10167       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10168 
10169     QualType OldReturnType = OldType->getReturnType();
10170 
10171     if (OldReturnType != NewReturnType)
10172       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10173 
10174     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10175       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10176 
10177     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10178       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10179 
10180     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10181       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10182 
10183     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10184       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10185 
10186     if (CheckEquivalentExceptionSpec(
10187             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10188             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10189       return true;
10190   }
10191   return false;
10192 }
10193 
10194 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10195                                              const FunctionDecl *NewFD,
10196                                              bool CausesMV,
10197                                              MultiVersionKind MVType) {
10198   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10199     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10200     if (OldFD)
10201       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10202     return true;
10203   }
10204 
10205   bool IsCPUSpecificCPUDispatchMVType =
10206       MVType == MultiVersionKind::CPUDispatch ||
10207       MVType == MultiVersionKind::CPUSpecific;
10208 
10209   if (CausesMV && OldFD &&
10210       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10211     return true;
10212 
10213   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10214     return true;
10215 
10216   // Only allow transition to MultiVersion if it hasn't been used.
10217   if (OldFD && CausesMV && OldFD->isUsed(false))
10218     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10219 
10220   return S.areMultiversionVariantFunctionsCompatible(
10221       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10222       PartialDiagnosticAt(NewFD->getLocation(),
10223                           S.PDiag(diag::note_multiversioning_caused_here)),
10224       PartialDiagnosticAt(NewFD->getLocation(),
10225                           S.PDiag(diag::err_multiversion_doesnt_support)
10226                               << IsCPUSpecificCPUDispatchMVType),
10227       PartialDiagnosticAt(NewFD->getLocation(),
10228                           S.PDiag(diag::err_multiversion_diff)),
10229       /*TemplatesSupported=*/false,
10230       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10231       /*CLinkageMayDiffer=*/false);
10232 }
10233 
10234 /// Check the validity of a multiversion function declaration that is the
10235 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10236 ///
10237 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10238 ///
10239 /// Returns true if there was an error, false otherwise.
10240 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10241                                            MultiVersionKind MVType,
10242                                            const TargetAttr *TA) {
10243   assert(MVType != MultiVersionKind::None &&
10244          "Function lacks multiversion attribute");
10245 
10246   // Target only causes MV if it is default, otherwise this is a normal
10247   // function.
10248   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10249     return false;
10250 
10251   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10252     FD->setInvalidDecl();
10253     return true;
10254   }
10255 
10256   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10257     FD->setInvalidDecl();
10258     return true;
10259   }
10260 
10261   FD->setIsMultiVersion();
10262   return false;
10263 }
10264 
10265 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10266   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10267     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10268       return true;
10269   }
10270 
10271   return false;
10272 }
10273 
10274 static bool CheckTargetCausesMultiVersioning(
10275     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10276     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10277     LookupResult &Previous) {
10278   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10279   ParsedTargetAttr NewParsed = NewTA->parse();
10280   // Sort order doesn't matter, it just needs to be consistent.
10281   llvm::sort(NewParsed.Features);
10282 
10283   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10284   // to change, this is a simple redeclaration.
10285   if (!NewTA->isDefaultVersion() &&
10286       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10287     return false;
10288 
10289   // Otherwise, this decl causes MultiVersioning.
10290   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10291     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10292     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10293     NewFD->setInvalidDecl();
10294     return true;
10295   }
10296 
10297   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10298                                        MultiVersionKind::Target)) {
10299     NewFD->setInvalidDecl();
10300     return true;
10301   }
10302 
10303   if (CheckMultiVersionValue(S, NewFD)) {
10304     NewFD->setInvalidDecl();
10305     return true;
10306   }
10307 
10308   // If this is 'default', permit the forward declaration.
10309   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10310     Redeclaration = true;
10311     OldDecl = OldFD;
10312     OldFD->setIsMultiVersion();
10313     NewFD->setIsMultiVersion();
10314     return false;
10315   }
10316 
10317   if (CheckMultiVersionValue(S, OldFD)) {
10318     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10319     NewFD->setInvalidDecl();
10320     return true;
10321   }
10322 
10323   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10324 
10325   if (OldParsed == NewParsed) {
10326     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10327     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10328     NewFD->setInvalidDecl();
10329     return true;
10330   }
10331 
10332   for (const auto *FD : OldFD->redecls()) {
10333     const auto *CurTA = FD->getAttr<TargetAttr>();
10334     // We allow forward declarations before ANY multiversioning attributes, but
10335     // nothing after the fact.
10336     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10337         (!CurTA || CurTA->isInherited())) {
10338       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10339           << 0;
10340       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10341       NewFD->setInvalidDecl();
10342       return true;
10343     }
10344   }
10345 
10346   OldFD->setIsMultiVersion();
10347   NewFD->setIsMultiVersion();
10348   Redeclaration = false;
10349   MergeTypeWithPrevious = false;
10350   OldDecl = nullptr;
10351   Previous.clear();
10352   return false;
10353 }
10354 
10355 /// Check the validity of a new function declaration being added to an existing
10356 /// multiversioned declaration collection.
10357 static bool CheckMultiVersionAdditionalDecl(
10358     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10359     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10360     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10361     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10362     LookupResult &Previous) {
10363 
10364   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10365   // Disallow mixing of multiversioning types.
10366   if ((OldMVType == MultiVersionKind::Target &&
10367        NewMVType != MultiVersionKind::Target) ||
10368       (NewMVType == MultiVersionKind::Target &&
10369        OldMVType != MultiVersionKind::Target)) {
10370     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10371     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10372     NewFD->setInvalidDecl();
10373     return true;
10374   }
10375 
10376   ParsedTargetAttr NewParsed;
10377   if (NewTA) {
10378     NewParsed = NewTA->parse();
10379     llvm::sort(NewParsed.Features);
10380   }
10381 
10382   bool UseMemberUsingDeclRules =
10383       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10384 
10385   // Next, check ALL non-overloads to see if this is a redeclaration of a
10386   // previous member of the MultiVersion set.
10387   for (NamedDecl *ND : Previous) {
10388     FunctionDecl *CurFD = ND->getAsFunction();
10389     if (!CurFD)
10390       continue;
10391     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10392       continue;
10393 
10394     if (NewMVType == MultiVersionKind::Target) {
10395       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10396       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10397         NewFD->setIsMultiVersion();
10398         Redeclaration = true;
10399         OldDecl = ND;
10400         return false;
10401       }
10402 
10403       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10404       if (CurParsed == NewParsed) {
10405         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10406         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10407         NewFD->setInvalidDecl();
10408         return true;
10409       }
10410     } else {
10411       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10412       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10413       // Handle CPUDispatch/CPUSpecific versions.
10414       // Only 1 CPUDispatch function is allowed, this will make it go through
10415       // the redeclaration errors.
10416       if (NewMVType == MultiVersionKind::CPUDispatch &&
10417           CurFD->hasAttr<CPUDispatchAttr>()) {
10418         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10419             std::equal(
10420                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10421                 NewCPUDisp->cpus_begin(),
10422                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10423                   return Cur->getName() == New->getName();
10424                 })) {
10425           NewFD->setIsMultiVersion();
10426           Redeclaration = true;
10427           OldDecl = ND;
10428           return false;
10429         }
10430 
10431         // If the declarations don't match, this is an error condition.
10432         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10433         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10434         NewFD->setInvalidDecl();
10435         return true;
10436       }
10437       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10438 
10439         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10440             std::equal(
10441                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10442                 NewCPUSpec->cpus_begin(),
10443                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10444                   return Cur->getName() == New->getName();
10445                 })) {
10446           NewFD->setIsMultiVersion();
10447           Redeclaration = true;
10448           OldDecl = ND;
10449           return false;
10450         }
10451 
10452         // Only 1 version of CPUSpecific is allowed for each CPU.
10453         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10454           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10455             if (CurII == NewII) {
10456               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10457                   << NewII;
10458               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10459               NewFD->setInvalidDecl();
10460               return true;
10461             }
10462           }
10463         }
10464       }
10465       // If the two decls aren't the same MVType, there is no possible error
10466       // condition.
10467     }
10468   }
10469 
10470   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10471   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10472   // handled in the attribute adding step.
10473   if (NewMVType == MultiVersionKind::Target &&
10474       CheckMultiVersionValue(S, NewFD)) {
10475     NewFD->setInvalidDecl();
10476     return true;
10477   }
10478 
10479   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10480                                        !OldFD->isMultiVersion(), NewMVType)) {
10481     NewFD->setInvalidDecl();
10482     return true;
10483   }
10484 
10485   // Permit forward declarations in the case where these two are compatible.
10486   if (!OldFD->isMultiVersion()) {
10487     OldFD->setIsMultiVersion();
10488     NewFD->setIsMultiVersion();
10489     Redeclaration = true;
10490     OldDecl = OldFD;
10491     return false;
10492   }
10493 
10494   NewFD->setIsMultiVersion();
10495   Redeclaration = false;
10496   MergeTypeWithPrevious = false;
10497   OldDecl = nullptr;
10498   Previous.clear();
10499   return false;
10500 }
10501 
10502 
10503 /// Check the validity of a mulitversion function declaration.
10504 /// Also sets the multiversion'ness' of the function itself.
10505 ///
10506 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10507 ///
10508 /// Returns true if there was an error, false otherwise.
10509 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10510                                       bool &Redeclaration, NamedDecl *&OldDecl,
10511                                       bool &MergeTypeWithPrevious,
10512                                       LookupResult &Previous) {
10513   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10514   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10515   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10516 
10517   // Mixing Multiversioning types is prohibited.
10518   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10519       (NewCPUDisp && NewCPUSpec)) {
10520     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10521     NewFD->setInvalidDecl();
10522     return true;
10523   }
10524 
10525   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10526 
10527   // Main isn't allowed to become a multiversion function, however it IS
10528   // permitted to have 'main' be marked with the 'target' optimization hint.
10529   if (NewFD->isMain()) {
10530     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10531         MVType == MultiVersionKind::CPUDispatch ||
10532         MVType == MultiVersionKind::CPUSpecific) {
10533       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10534       NewFD->setInvalidDecl();
10535       return true;
10536     }
10537     return false;
10538   }
10539 
10540   if (!OldDecl || !OldDecl->getAsFunction() ||
10541       OldDecl->getDeclContext()->getRedeclContext() !=
10542           NewFD->getDeclContext()->getRedeclContext()) {
10543     // If there's no previous declaration, AND this isn't attempting to cause
10544     // multiversioning, this isn't an error condition.
10545     if (MVType == MultiVersionKind::None)
10546       return false;
10547     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10548   }
10549 
10550   FunctionDecl *OldFD = OldDecl->getAsFunction();
10551 
10552   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10553     return false;
10554 
10555   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10556     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10557         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10558     NewFD->setInvalidDecl();
10559     return true;
10560   }
10561 
10562   // Handle the target potentially causes multiversioning case.
10563   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10564     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10565                                             Redeclaration, OldDecl,
10566                                             MergeTypeWithPrevious, Previous);
10567 
10568   // At this point, we have a multiversion function decl (in OldFD) AND an
10569   // appropriate attribute in the current function decl.  Resolve that these are
10570   // still compatible with previous declarations.
10571   return CheckMultiVersionAdditionalDecl(
10572       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10573       OldDecl, MergeTypeWithPrevious, Previous);
10574 }
10575 
10576 /// Perform semantic checking of a new function declaration.
10577 ///
10578 /// Performs semantic analysis of the new function declaration
10579 /// NewFD. This routine performs all semantic checking that does not
10580 /// require the actual declarator involved in the declaration, and is
10581 /// used both for the declaration of functions as they are parsed
10582 /// (called via ActOnDeclarator) and for the declaration of functions
10583 /// that have been instantiated via C++ template instantiation (called
10584 /// via InstantiateDecl).
10585 ///
10586 /// \param IsMemberSpecialization whether this new function declaration is
10587 /// a member specialization (that replaces any definition provided by the
10588 /// previous declaration).
10589 ///
10590 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10591 ///
10592 /// \returns true if the function declaration is a redeclaration.
10593 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10594                                     LookupResult &Previous,
10595                                     bool IsMemberSpecialization) {
10596   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10597          "Variably modified return types are not handled here");
10598 
10599   // Determine whether the type of this function should be merged with
10600   // a previous visible declaration. This never happens for functions in C++,
10601   // and always happens in C if the previous declaration was visible.
10602   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10603                                !Previous.isShadowed();
10604 
10605   bool Redeclaration = false;
10606   NamedDecl *OldDecl = nullptr;
10607   bool MayNeedOverloadableChecks = false;
10608 
10609   // Merge or overload the declaration with an existing declaration of
10610   // the same name, if appropriate.
10611   if (!Previous.empty()) {
10612     // Determine whether NewFD is an overload of PrevDecl or
10613     // a declaration that requires merging. If it's an overload,
10614     // there's no more work to do here; we'll just add the new
10615     // function to the scope.
10616     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10617       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10618       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10619         Redeclaration = true;
10620         OldDecl = Candidate;
10621       }
10622     } else {
10623       MayNeedOverloadableChecks = true;
10624       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10625                             /*NewIsUsingDecl*/ false)) {
10626       case Ovl_Match:
10627         Redeclaration = true;
10628         break;
10629 
10630       case Ovl_NonFunction:
10631         Redeclaration = true;
10632         break;
10633 
10634       case Ovl_Overload:
10635         Redeclaration = false;
10636         break;
10637       }
10638     }
10639   }
10640 
10641   // Check for a previous extern "C" declaration with this name.
10642   if (!Redeclaration &&
10643       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10644     if (!Previous.empty()) {
10645       // This is an extern "C" declaration with the same name as a previous
10646       // declaration, and thus redeclares that entity...
10647       Redeclaration = true;
10648       OldDecl = Previous.getFoundDecl();
10649       MergeTypeWithPrevious = false;
10650 
10651       // ... except in the presence of __attribute__((overloadable)).
10652       if (OldDecl->hasAttr<OverloadableAttr>() ||
10653           NewFD->hasAttr<OverloadableAttr>()) {
10654         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10655           MayNeedOverloadableChecks = true;
10656           Redeclaration = false;
10657           OldDecl = nullptr;
10658         }
10659       }
10660     }
10661   }
10662 
10663   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10664                                 MergeTypeWithPrevious, Previous))
10665     return Redeclaration;
10666 
10667   // C++11 [dcl.constexpr]p8:
10668   //   A constexpr specifier for a non-static member function that is not
10669   //   a constructor declares that member function to be const.
10670   //
10671   // This needs to be delayed until we know whether this is an out-of-line
10672   // definition of a static member function.
10673   //
10674   // This rule is not present in C++1y, so we produce a backwards
10675   // compatibility warning whenever it happens in C++11.
10676   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10677   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10678       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10679       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10680     CXXMethodDecl *OldMD = nullptr;
10681     if (OldDecl)
10682       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10683     if (!OldMD || !OldMD->isStatic()) {
10684       const FunctionProtoType *FPT =
10685         MD->getType()->castAs<FunctionProtoType>();
10686       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10687       EPI.TypeQuals.addConst();
10688       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10689                                           FPT->getParamTypes(), EPI));
10690 
10691       // Warn that we did this, if we're not performing template instantiation.
10692       // In that case, we'll have warned already when the template was defined.
10693       if (!inTemplateInstantiation()) {
10694         SourceLocation AddConstLoc;
10695         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10696                 .IgnoreParens().getAs<FunctionTypeLoc>())
10697           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10698 
10699         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10700           << FixItHint::CreateInsertion(AddConstLoc, " const");
10701       }
10702     }
10703   }
10704 
10705   if (Redeclaration) {
10706     // NewFD and OldDecl represent declarations that need to be
10707     // merged.
10708     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10709       NewFD->setInvalidDecl();
10710       return Redeclaration;
10711     }
10712 
10713     Previous.clear();
10714     Previous.addDecl(OldDecl);
10715 
10716     if (FunctionTemplateDecl *OldTemplateDecl =
10717             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10718       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10719       FunctionTemplateDecl *NewTemplateDecl
10720         = NewFD->getDescribedFunctionTemplate();
10721       assert(NewTemplateDecl && "Template/non-template mismatch");
10722 
10723       // The call to MergeFunctionDecl above may have created some state in
10724       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10725       // can add it as a redeclaration.
10726       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10727 
10728       NewFD->setPreviousDeclaration(OldFD);
10729       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10730       if (NewFD->isCXXClassMember()) {
10731         NewFD->setAccess(OldTemplateDecl->getAccess());
10732         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10733       }
10734 
10735       // If this is an explicit specialization of a member that is a function
10736       // template, mark it as a member specialization.
10737       if (IsMemberSpecialization &&
10738           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10739         NewTemplateDecl->setMemberSpecialization();
10740         assert(OldTemplateDecl->isMemberSpecialization());
10741         // Explicit specializations of a member template do not inherit deleted
10742         // status from the parent member template that they are specializing.
10743         if (OldFD->isDeleted()) {
10744           // FIXME: This assert will not hold in the presence of modules.
10745           assert(OldFD->getCanonicalDecl() == OldFD);
10746           // FIXME: We need an update record for this AST mutation.
10747           OldFD->setDeletedAsWritten(false);
10748         }
10749       }
10750 
10751     } else {
10752       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10753         auto *OldFD = cast<FunctionDecl>(OldDecl);
10754         // This needs to happen first so that 'inline' propagates.
10755         NewFD->setPreviousDeclaration(OldFD);
10756         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10757         if (NewFD->isCXXClassMember())
10758           NewFD->setAccess(OldFD->getAccess());
10759       }
10760     }
10761   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10762              !NewFD->getAttr<OverloadableAttr>()) {
10763     assert((Previous.empty() ||
10764             llvm::any_of(Previous,
10765                          [](const NamedDecl *ND) {
10766                            return ND->hasAttr<OverloadableAttr>();
10767                          })) &&
10768            "Non-redecls shouldn't happen without overloadable present");
10769 
10770     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10771       const auto *FD = dyn_cast<FunctionDecl>(ND);
10772       return FD && !FD->hasAttr<OverloadableAttr>();
10773     });
10774 
10775     if (OtherUnmarkedIter != Previous.end()) {
10776       Diag(NewFD->getLocation(),
10777            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10778       Diag((*OtherUnmarkedIter)->getLocation(),
10779            diag::note_attribute_overloadable_prev_overload)
10780           << false;
10781 
10782       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10783     }
10784   }
10785 
10786   // Semantic checking for this function declaration (in isolation).
10787 
10788   if (getLangOpts().CPlusPlus) {
10789     // C++-specific checks.
10790     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10791       CheckConstructor(Constructor);
10792     } else if (CXXDestructorDecl *Destructor =
10793                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10794       CXXRecordDecl *Record = Destructor->getParent();
10795       QualType ClassType = Context.getTypeDeclType(Record);
10796 
10797       // FIXME: Shouldn't we be able to perform this check even when the class
10798       // type is dependent? Both gcc and edg can handle that.
10799       if (!ClassType->isDependentType()) {
10800         DeclarationName Name
10801           = Context.DeclarationNames.getCXXDestructorName(
10802                                         Context.getCanonicalType(ClassType));
10803         if (NewFD->getDeclName() != Name) {
10804           Diag(NewFD->getLocation(), diag::err_destructor_name);
10805           NewFD->setInvalidDecl();
10806           return Redeclaration;
10807         }
10808       }
10809     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10810       if (auto *TD = Guide->getDescribedFunctionTemplate())
10811         CheckDeductionGuideTemplate(TD);
10812 
10813       // A deduction guide is not on the list of entities that can be
10814       // explicitly specialized.
10815       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10816         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10817             << /*explicit specialization*/ 1;
10818     }
10819 
10820     // Find any virtual functions that this function overrides.
10821     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10822       if (!Method->isFunctionTemplateSpecialization() &&
10823           !Method->getDescribedFunctionTemplate() &&
10824           Method->isCanonicalDecl()) {
10825         AddOverriddenMethods(Method->getParent(), Method);
10826       }
10827       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10828         // C++2a [class.virtual]p6
10829         // A virtual method shall not have a requires-clause.
10830         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10831              diag::err_constrained_virtual_method);
10832 
10833       if (Method->isStatic())
10834         checkThisInStaticMemberFunctionType(Method);
10835     }
10836 
10837     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10838       ActOnConversionDeclarator(Conversion);
10839 
10840     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10841     if (NewFD->isOverloadedOperator() &&
10842         CheckOverloadedOperatorDeclaration(NewFD)) {
10843       NewFD->setInvalidDecl();
10844       return Redeclaration;
10845     }
10846 
10847     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10848     if (NewFD->getLiteralIdentifier() &&
10849         CheckLiteralOperatorDeclaration(NewFD)) {
10850       NewFD->setInvalidDecl();
10851       return Redeclaration;
10852     }
10853 
10854     // In C++, check default arguments now that we have merged decls. Unless
10855     // the lexical context is the class, because in this case this is done
10856     // during delayed parsing anyway.
10857     if (!CurContext->isRecord())
10858       CheckCXXDefaultArguments(NewFD);
10859 
10860     // If this function declares a builtin function, check the type of this
10861     // declaration against the expected type for the builtin.
10862     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10863       ASTContext::GetBuiltinTypeError Error;
10864       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10865       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10866       // If the type of the builtin differs only in its exception
10867       // specification, that's OK.
10868       // FIXME: If the types do differ in this way, it would be better to
10869       // retain the 'noexcept' form of the type.
10870       if (!T.isNull() &&
10871           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10872                                                             NewFD->getType()))
10873         // The type of this function differs from the type of the builtin,
10874         // so forget about the builtin entirely.
10875         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10876     }
10877 
10878     // If this function is declared as being extern "C", then check to see if
10879     // the function returns a UDT (class, struct, or union type) that is not C
10880     // compatible, and if it does, warn the user.
10881     // But, issue any diagnostic on the first declaration only.
10882     if (Previous.empty() && NewFD->isExternC()) {
10883       QualType R = NewFD->getReturnType();
10884       if (R->isIncompleteType() && !R->isVoidType())
10885         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10886             << NewFD << R;
10887       else if (!R.isPODType(Context) && !R->isVoidType() &&
10888                !R->isObjCObjectPointerType())
10889         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10890     }
10891 
10892     // C++1z [dcl.fct]p6:
10893     //   [...] whether the function has a non-throwing exception-specification
10894     //   [is] part of the function type
10895     //
10896     // This results in an ABI break between C++14 and C++17 for functions whose
10897     // declared type includes an exception-specification in a parameter or
10898     // return type. (Exception specifications on the function itself are OK in
10899     // most cases, and exception specifications are not permitted in most other
10900     // contexts where they could make it into a mangling.)
10901     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10902       auto HasNoexcept = [&](QualType T) -> bool {
10903         // Strip off declarator chunks that could be between us and a function
10904         // type. We don't need to look far, exception specifications are very
10905         // restricted prior to C++17.
10906         if (auto *RT = T->getAs<ReferenceType>())
10907           T = RT->getPointeeType();
10908         else if (T->isAnyPointerType())
10909           T = T->getPointeeType();
10910         else if (auto *MPT = T->getAs<MemberPointerType>())
10911           T = MPT->getPointeeType();
10912         if (auto *FPT = T->getAs<FunctionProtoType>())
10913           if (FPT->isNothrow())
10914             return true;
10915         return false;
10916       };
10917 
10918       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10919       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10920       for (QualType T : FPT->param_types())
10921         AnyNoexcept |= HasNoexcept(T);
10922       if (AnyNoexcept)
10923         Diag(NewFD->getLocation(),
10924              diag::warn_cxx17_compat_exception_spec_in_signature)
10925             << NewFD;
10926     }
10927 
10928     if (!Redeclaration && LangOpts.CUDA)
10929       checkCUDATargetOverload(NewFD, Previous);
10930   }
10931   return Redeclaration;
10932 }
10933 
10934 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10935   // C++11 [basic.start.main]p3:
10936   //   A program that [...] declares main to be inline, static or
10937   //   constexpr is ill-formed.
10938   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10939   //   appear in a declaration of main.
10940   // static main is not an error under C99, but we should warn about it.
10941   // We accept _Noreturn main as an extension.
10942   if (FD->getStorageClass() == SC_Static)
10943     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10944          ? diag::err_static_main : diag::warn_static_main)
10945       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10946   if (FD->isInlineSpecified())
10947     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10948       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10949   if (DS.isNoreturnSpecified()) {
10950     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10951     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10952     Diag(NoreturnLoc, diag::ext_noreturn_main);
10953     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10954       << FixItHint::CreateRemoval(NoreturnRange);
10955   }
10956   if (FD->isConstexpr()) {
10957     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10958         << FD->isConsteval()
10959         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10960     FD->setConstexprKind(CSK_unspecified);
10961   }
10962 
10963   if (getLangOpts().OpenCL) {
10964     Diag(FD->getLocation(), diag::err_opencl_no_main)
10965         << FD->hasAttr<OpenCLKernelAttr>();
10966     FD->setInvalidDecl();
10967     return;
10968   }
10969 
10970   QualType T = FD->getType();
10971   assert(T->isFunctionType() && "function decl is not of function type");
10972   const FunctionType* FT = T->castAs<FunctionType>();
10973 
10974   // Set default calling convention for main()
10975   if (FT->getCallConv() != CC_C) {
10976     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10977     FD->setType(QualType(FT, 0));
10978     T = Context.getCanonicalType(FD->getType());
10979   }
10980 
10981   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10982     // In C with GNU extensions we allow main() to have non-integer return
10983     // type, but we should warn about the extension, and we disable the
10984     // implicit-return-zero rule.
10985 
10986     // GCC in C mode accepts qualified 'int'.
10987     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10988       FD->setHasImplicitReturnZero(true);
10989     else {
10990       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10991       SourceRange RTRange = FD->getReturnTypeSourceRange();
10992       if (RTRange.isValid())
10993         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10994             << FixItHint::CreateReplacement(RTRange, "int");
10995     }
10996   } else {
10997     // In C and C++, main magically returns 0 if you fall off the end;
10998     // set the flag which tells us that.
10999     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11000 
11001     // All the standards say that main() should return 'int'.
11002     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11003       FD->setHasImplicitReturnZero(true);
11004     else {
11005       // Otherwise, this is just a flat-out error.
11006       SourceRange RTRange = FD->getReturnTypeSourceRange();
11007       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11008           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11009                                 : FixItHint());
11010       FD->setInvalidDecl(true);
11011     }
11012   }
11013 
11014   // Treat protoless main() as nullary.
11015   if (isa<FunctionNoProtoType>(FT)) return;
11016 
11017   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11018   unsigned nparams = FTP->getNumParams();
11019   assert(FD->getNumParams() == nparams);
11020 
11021   bool HasExtraParameters = (nparams > 3);
11022 
11023   if (FTP->isVariadic()) {
11024     Diag(FD->getLocation(), diag::ext_variadic_main);
11025     // FIXME: if we had information about the location of the ellipsis, we
11026     // could add a FixIt hint to remove it as a parameter.
11027   }
11028 
11029   // Darwin passes an undocumented fourth argument of type char**.  If
11030   // other platforms start sprouting these, the logic below will start
11031   // getting shifty.
11032   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11033     HasExtraParameters = false;
11034 
11035   if (HasExtraParameters) {
11036     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11037     FD->setInvalidDecl(true);
11038     nparams = 3;
11039   }
11040 
11041   // FIXME: a lot of the following diagnostics would be improved
11042   // if we had some location information about types.
11043 
11044   QualType CharPP =
11045     Context.getPointerType(Context.getPointerType(Context.CharTy));
11046   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11047 
11048   for (unsigned i = 0; i < nparams; ++i) {
11049     QualType AT = FTP->getParamType(i);
11050 
11051     bool mismatch = true;
11052 
11053     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11054       mismatch = false;
11055     else if (Expected[i] == CharPP) {
11056       // As an extension, the following forms are okay:
11057       //   char const **
11058       //   char const * const *
11059       //   char * const *
11060 
11061       QualifierCollector qs;
11062       const PointerType* PT;
11063       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11064           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11065           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11066                               Context.CharTy)) {
11067         qs.removeConst();
11068         mismatch = !qs.empty();
11069       }
11070     }
11071 
11072     if (mismatch) {
11073       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11074       // TODO: suggest replacing given type with expected type
11075       FD->setInvalidDecl(true);
11076     }
11077   }
11078 
11079   if (nparams == 1 && !FD->isInvalidDecl()) {
11080     Diag(FD->getLocation(), diag::warn_main_one_arg);
11081   }
11082 
11083   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11084     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11085     FD->setInvalidDecl();
11086   }
11087 }
11088 
11089 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11090   QualType T = FD->getType();
11091   assert(T->isFunctionType() && "function decl is not of function type");
11092   const FunctionType *FT = T->castAs<FunctionType>();
11093 
11094   // Set an implicit return of 'zero' if the function can return some integral,
11095   // enumeration, pointer or nullptr type.
11096   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11097       FT->getReturnType()->isAnyPointerType() ||
11098       FT->getReturnType()->isNullPtrType())
11099     // DllMain is exempt because a return value of zero means it failed.
11100     if (FD->getName() != "DllMain")
11101       FD->setHasImplicitReturnZero(true);
11102 
11103   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11104     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11105     FD->setInvalidDecl();
11106   }
11107 }
11108 
11109 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11110   // FIXME: Need strict checking.  In C89, we need to check for
11111   // any assignment, increment, decrement, function-calls, or
11112   // commas outside of a sizeof.  In C99, it's the same list,
11113   // except that the aforementioned are allowed in unevaluated
11114   // expressions.  Everything else falls under the
11115   // "may accept other forms of constant expressions" exception.
11116   //
11117   // Regular C++ code will not end up here (exceptions: language extensions,
11118   // OpenCL C++ etc), so the constant expression rules there don't matter.
11119   if (Init->isValueDependent()) {
11120     assert(Init->containsErrors() &&
11121            "Dependent code should only occur in error-recovery path.");
11122     return true;
11123   }
11124   const Expr *Culprit;
11125   if (Init->isConstantInitializer(Context, false, &Culprit))
11126     return false;
11127   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11128     << Culprit->getSourceRange();
11129   return true;
11130 }
11131 
11132 namespace {
11133   // Visits an initialization expression to see if OrigDecl is evaluated in
11134   // its own initialization and throws a warning if it does.
11135   class SelfReferenceChecker
11136       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11137     Sema &S;
11138     Decl *OrigDecl;
11139     bool isRecordType;
11140     bool isPODType;
11141     bool isReferenceType;
11142 
11143     bool isInitList;
11144     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11145 
11146   public:
11147     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11148 
11149     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11150                                                     S(S), OrigDecl(OrigDecl) {
11151       isPODType = false;
11152       isRecordType = false;
11153       isReferenceType = false;
11154       isInitList = false;
11155       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11156         isPODType = VD->getType().isPODType(S.Context);
11157         isRecordType = VD->getType()->isRecordType();
11158         isReferenceType = VD->getType()->isReferenceType();
11159       }
11160     }
11161 
11162     // For most expressions, just call the visitor.  For initializer lists,
11163     // track the index of the field being initialized since fields are
11164     // initialized in order allowing use of previously initialized fields.
11165     void CheckExpr(Expr *E) {
11166       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11167       if (!InitList) {
11168         Visit(E);
11169         return;
11170       }
11171 
11172       // Track and increment the index here.
11173       isInitList = true;
11174       InitFieldIndex.push_back(0);
11175       for (auto Child : InitList->children()) {
11176         CheckExpr(cast<Expr>(Child));
11177         ++InitFieldIndex.back();
11178       }
11179       InitFieldIndex.pop_back();
11180     }
11181 
11182     // Returns true if MemberExpr is checked and no further checking is needed.
11183     // Returns false if additional checking is required.
11184     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11185       llvm::SmallVector<FieldDecl*, 4> Fields;
11186       Expr *Base = E;
11187       bool ReferenceField = false;
11188 
11189       // Get the field members used.
11190       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11191         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11192         if (!FD)
11193           return false;
11194         Fields.push_back(FD);
11195         if (FD->getType()->isReferenceType())
11196           ReferenceField = true;
11197         Base = ME->getBase()->IgnoreParenImpCasts();
11198       }
11199 
11200       // Keep checking only if the base Decl is the same.
11201       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11202       if (!DRE || DRE->getDecl() != OrigDecl)
11203         return false;
11204 
11205       // A reference field can be bound to an unininitialized field.
11206       if (CheckReference && !ReferenceField)
11207         return true;
11208 
11209       // Convert FieldDecls to their index number.
11210       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11211       for (const FieldDecl *I : llvm::reverse(Fields))
11212         UsedFieldIndex.push_back(I->getFieldIndex());
11213 
11214       // See if a warning is needed by checking the first difference in index
11215       // numbers.  If field being used has index less than the field being
11216       // initialized, then the use is safe.
11217       for (auto UsedIter = UsedFieldIndex.begin(),
11218                 UsedEnd = UsedFieldIndex.end(),
11219                 OrigIter = InitFieldIndex.begin(),
11220                 OrigEnd = InitFieldIndex.end();
11221            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11222         if (*UsedIter < *OrigIter)
11223           return true;
11224         if (*UsedIter > *OrigIter)
11225           break;
11226       }
11227 
11228       // TODO: Add a different warning which will print the field names.
11229       HandleDeclRefExpr(DRE);
11230       return true;
11231     }
11232 
11233     // For most expressions, the cast is directly above the DeclRefExpr.
11234     // For conditional operators, the cast can be outside the conditional
11235     // operator if both expressions are DeclRefExpr's.
11236     void HandleValue(Expr *E) {
11237       E = E->IgnoreParens();
11238       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11239         HandleDeclRefExpr(DRE);
11240         return;
11241       }
11242 
11243       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11244         Visit(CO->getCond());
11245         HandleValue(CO->getTrueExpr());
11246         HandleValue(CO->getFalseExpr());
11247         return;
11248       }
11249 
11250       if (BinaryConditionalOperator *BCO =
11251               dyn_cast<BinaryConditionalOperator>(E)) {
11252         Visit(BCO->getCond());
11253         HandleValue(BCO->getFalseExpr());
11254         return;
11255       }
11256 
11257       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11258         HandleValue(OVE->getSourceExpr());
11259         return;
11260       }
11261 
11262       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11263         if (BO->getOpcode() == BO_Comma) {
11264           Visit(BO->getLHS());
11265           HandleValue(BO->getRHS());
11266           return;
11267         }
11268       }
11269 
11270       if (isa<MemberExpr>(E)) {
11271         if (isInitList) {
11272           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11273                                       false /*CheckReference*/))
11274             return;
11275         }
11276 
11277         Expr *Base = E->IgnoreParenImpCasts();
11278         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11279           // Check for static member variables and don't warn on them.
11280           if (!isa<FieldDecl>(ME->getMemberDecl()))
11281             return;
11282           Base = ME->getBase()->IgnoreParenImpCasts();
11283         }
11284         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11285           HandleDeclRefExpr(DRE);
11286         return;
11287       }
11288 
11289       Visit(E);
11290     }
11291 
11292     // Reference types not handled in HandleValue are handled here since all
11293     // uses of references are bad, not just r-value uses.
11294     void VisitDeclRefExpr(DeclRefExpr *E) {
11295       if (isReferenceType)
11296         HandleDeclRefExpr(E);
11297     }
11298 
11299     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11300       if (E->getCastKind() == CK_LValueToRValue) {
11301         HandleValue(E->getSubExpr());
11302         return;
11303       }
11304 
11305       Inherited::VisitImplicitCastExpr(E);
11306     }
11307 
11308     void VisitMemberExpr(MemberExpr *E) {
11309       if (isInitList) {
11310         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11311           return;
11312       }
11313 
11314       // Don't warn on arrays since they can be treated as pointers.
11315       if (E->getType()->canDecayToPointerType()) return;
11316 
11317       // Warn when a non-static method call is followed by non-static member
11318       // field accesses, which is followed by a DeclRefExpr.
11319       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11320       bool Warn = (MD && !MD->isStatic());
11321       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11322       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11323         if (!isa<FieldDecl>(ME->getMemberDecl()))
11324           Warn = false;
11325         Base = ME->getBase()->IgnoreParenImpCasts();
11326       }
11327 
11328       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11329         if (Warn)
11330           HandleDeclRefExpr(DRE);
11331         return;
11332       }
11333 
11334       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11335       // Visit that expression.
11336       Visit(Base);
11337     }
11338 
11339     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11340       Expr *Callee = E->getCallee();
11341 
11342       if (isa<UnresolvedLookupExpr>(Callee))
11343         return Inherited::VisitCXXOperatorCallExpr(E);
11344 
11345       Visit(Callee);
11346       for (auto Arg: E->arguments())
11347         HandleValue(Arg->IgnoreParenImpCasts());
11348     }
11349 
11350     void VisitUnaryOperator(UnaryOperator *E) {
11351       // For POD record types, addresses of its own members are well-defined.
11352       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11353           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11354         if (!isPODType)
11355           HandleValue(E->getSubExpr());
11356         return;
11357       }
11358 
11359       if (E->isIncrementDecrementOp()) {
11360         HandleValue(E->getSubExpr());
11361         return;
11362       }
11363 
11364       Inherited::VisitUnaryOperator(E);
11365     }
11366 
11367     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11368 
11369     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11370       if (E->getConstructor()->isCopyConstructor()) {
11371         Expr *ArgExpr = E->getArg(0);
11372         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11373           if (ILE->getNumInits() == 1)
11374             ArgExpr = ILE->getInit(0);
11375         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11376           if (ICE->getCastKind() == CK_NoOp)
11377             ArgExpr = ICE->getSubExpr();
11378         HandleValue(ArgExpr);
11379         return;
11380       }
11381       Inherited::VisitCXXConstructExpr(E);
11382     }
11383 
11384     void VisitCallExpr(CallExpr *E) {
11385       // Treat std::move as a use.
11386       if (E->isCallToStdMove()) {
11387         HandleValue(E->getArg(0));
11388         return;
11389       }
11390 
11391       Inherited::VisitCallExpr(E);
11392     }
11393 
11394     void VisitBinaryOperator(BinaryOperator *E) {
11395       if (E->isCompoundAssignmentOp()) {
11396         HandleValue(E->getLHS());
11397         Visit(E->getRHS());
11398         return;
11399       }
11400 
11401       Inherited::VisitBinaryOperator(E);
11402     }
11403 
11404     // A custom visitor for BinaryConditionalOperator is needed because the
11405     // regular visitor would check the condition and true expression separately
11406     // but both point to the same place giving duplicate diagnostics.
11407     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11408       Visit(E->getCond());
11409       Visit(E->getFalseExpr());
11410     }
11411 
11412     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11413       Decl* ReferenceDecl = DRE->getDecl();
11414       if (OrigDecl != ReferenceDecl) return;
11415       unsigned diag;
11416       if (isReferenceType) {
11417         diag = diag::warn_uninit_self_reference_in_reference_init;
11418       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11419         diag = diag::warn_static_self_reference_in_init;
11420       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11421                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11422                  DRE->getDecl()->getType()->isRecordType()) {
11423         diag = diag::warn_uninit_self_reference_in_init;
11424       } else {
11425         // Local variables will be handled by the CFG analysis.
11426         return;
11427       }
11428 
11429       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11430                             S.PDiag(diag)
11431                                 << DRE->getDecl() << OrigDecl->getLocation()
11432                                 << DRE->getSourceRange());
11433     }
11434   };
11435 
11436   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11437   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11438                                  bool DirectInit) {
11439     // Parameters arguments are occassionially constructed with itself,
11440     // for instance, in recursive functions.  Skip them.
11441     if (isa<ParmVarDecl>(OrigDecl))
11442       return;
11443 
11444     E = E->IgnoreParens();
11445 
11446     // Skip checking T a = a where T is not a record or reference type.
11447     // Doing so is a way to silence uninitialized warnings.
11448     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11449       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11450         if (ICE->getCastKind() == CK_LValueToRValue)
11451           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11452             if (DRE->getDecl() == OrigDecl)
11453               return;
11454 
11455     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11456   }
11457 } // end anonymous namespace
11458 
11459 namespace {
11460   // Simple wrapper to add the name of a variable or (if no variable is
11461   // available) a DeclarationName into a diagnostic.
11462   struct VarDeclOrName {
11463     VarDecl *VDecl;
11464     DeclarationName Name;
11465 
11466     friend const Sema::SemaDiagnosticBuilder &
11467     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11468       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11469     }
11470   };
11471 } // end anonymous namespace
11472 
11473 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11474                                             DeclarationName Name, QualType Type,
11475                                             TypeSourceInfo *TSI,
11476                                             SourceRange Range, bool DirectInit,
11477                                             Expr *Init) {
11478   bool IsInitCapture = !VDecl;
11479   assert((!VDecl || !VDecl->isInitCapture()) &&
11480          "init captures are expected to be deduced prior to initialization");
11481 
11482   VarDeclOrName VN{VDecl, Name};
11483 
11484   DeducedType *Deduced = Type->getContainedDeducedType();
11485   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11486 
11487   // C++11 [dcl.spec.auto]p3
11488   if (!Init) {
11489     assert(VDecl && "no init for init capture deduction?");
11490 
11491     // Except for class argument deduction, and then for an initializing
11492     // declaration only, i.e. no static at class scope or extern.
11493     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11494         VDecl->hasExternalStorage() ||
11495         VDecl->isStaticDataMember()) {
11496       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11497         << VDecl->getDeclName() << Type;
11498       return QualType();
11499     }
11500   }
11501 
11502   ArrayRef<Expr*> DeduceInits;
11503   if (Init)
11504     DeduceInits = Init;
11505 
11506   if (DirectInit) {
11507     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11508       DeduceInits = PL->exprs();
11509   }
11510 
11511   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11512     assert(VDecl && "non-auto type for init capture deduction?");
11513     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11514     InitializationKind Kind = InitializationKind::CreateForInit(
11515         VDecl->getLocation(), DirectInit, Init);
11516     // FIXME: Initialization should not be taking a mutable list of inits.
11517     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11518     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11519                                                        InitsCopy);
11520   }
11521 
11522   if (DirectInit) {
11523     if (auto *IL = dyn_cast<InitListExpr>(Init))
11524       DeduceInits = IL->inits();
11525   }
11526 
11527   // Deduction only works if we have exactly one source expression.
11528   if (DeduceInits.empty()) {
11529     // It isn't possible to write this directly, but it is possible to
11530     // end up in this situation with "auto x(some_pack...);"
11531     Diag(Init->getBeginLoc(), IsInitCapture
11532                                   ? diag::err_init_capture_no_expression
11533                                   : diag::err_auto_var_init_no_expression)
11534         << VN << Type << Range;
11535     return QualType();
11536   }
11537 
11538   if (DeduceInits.size() > 1) {
11539     Diag(DeduceInits[1]->getBeginLoc(),
11540          IsInitCapture ? diag::err_init_capture_multiple_expressions
11541                        : diag::err_auto_var_init_multiple_expressions)
11542         << VN << Type << Range;
11543     return QualType();
11544   }
11545 
11546   Expr *DeduceInit = DeduceInits[0];
11547   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11548     Diag(Init->getBeginLoc(), IsInitCapture
11549                                   ? diag::err_init_capture_paren_braces
11550                                   : diag::err_auto_var_init_paren_braces)
11551         << isa<InitListExpr>(Init) << VN << Type << Range;
11552     return QualType();
11553   }
11554 
11555   // Expressions default to 'id' when we're in a debugger.
11556   bool DefaultedAnyToId = false;
11557   if (getLangOpts().DebuggerCastResultToId &&
11558       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11559     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11560     if (Result.isInvalid()) {
11561       return QualType();
11562     }
11563     Init = Result.get();
11564     DefaultedAnyToId = true;
11565   }
11566 
11567   // C++ [dcl.decomp]p1:
11568   //   If the assignment-expression [...] has array type A and no ref-qualifier
11569   //   is present, e has type cv A
11570   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11571       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11572       DeduceInit->getType()->isConstantArrayType())
11573     return Context.getQualifiedType(DeduceInit->getType(),
11574                                     Type.getQualifiers());
11575 
11576   QualType DeducedType;
11577   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11578     if (!IsInitCapture)
11579       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11580     else if (isa<InitListExpr>(Init))
11581       Diag(Range.getBegin(),
11582            diag::err_init_capture_deduction_failure_from_init_list)
11583           << VN
11584           << (DeduceInit->getType().isNull() ? TSI->getType()
11585                                              : DeduceInit->getType())
11586           << DeduceInit->getSourceRange();
11587     else
11588       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11589           << VN << TSI->getType()
11590           << (DeduceInit->getType().isNull() ? TSI->getType()
11591                                              : DeduceInit->getType())
11592           << DeduceInit->getSourceRange();
11593   }
11594 
11595   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11596   // 'id' instead of a specific object type prevents most of our usual
11597   // checks.
11598   // We only want to warn outside of template instantiations, though:
11599   // inside a template, the 'id' could have come from a parameter.
11600   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11601       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11602     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11603     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11604   }
11605 
11606   return DeducedType;
11607 }
11608 
11609 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11610                                          Expr *Init) {
11611   assert(!Init || !Init->containsErrors());
11612   QualType DeducedType = deduceVarTypeFromInitializer(
11613       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11614       VDecl->getSourceRange(), DirectInit, Init);
11615   if (DeducedType.isNull()) {
11616     VDecl->setInvalidDecl();
11617     return true;
11618   }
11619 
11620   VDecl->setType(DeducedType);
11621   assert(VDecl->isLinkageValid());
11622 
11623   // In ARC, infer lifetime.
11624   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11625     VDecl->setInvalidDecl();
11626 
11627   if (getLangOpts().OpenCL)
11628     deduceOpenCLAddressSpace(VDecl);
11629 
11630   // If this is a redeclaration, check that the type we just deduced matches
11631   // the previously declared type.
11632   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11633     // We never need to merge the type, because we cannot form an incomplete
11634     // array of auto, nor deduce such a type.
11635     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11636   }
11637 
11638   // Check the deduced type is valid for a variable declaration.
11639   CheckVariableDeclarationType(VDecl);
11640   return VDecl->isInvalidDecl();
11641 }
11642 
11643 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11644                                               SourceLocation Loc) {
11645   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11646     Init = EWC->getSubExpr();
11647 
11648   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11649     Init = CE->getSubExpr();
11650 
11651   QualType InitType = Init->getType();
11652   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11653           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11654          "shouldn't be called if type doesn't have a non-trivial C struct");
11655   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11656     for (auto I : ILE->inits()) {
11657       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11658           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11659         continue;
11660       SourceLocation SL = I->getExprLoc();
11661       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11662     }
11663     return;
11664   }
11665 
11666   if (isa<ImplicitValueInitExpr>(Init)) {
11667     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11668       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11669                             NTCUK_Init);
11670   } else {
11671     // Assume all other explicit initializers involving copying some existing
11672     // object.
11673     // TODO: ignore any explicit initializers where we can guarantee
11674     // copy-elision.
11675     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11676       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11677   }
11678 }
11679 
11680 namespace {
11681 
11682 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11683   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11684   // in the source code or implicitly by the compiler if it is in a union
11685   // defined in a system header and has non-trivial ObjC ownership
11686   // qualifications. We don't want those fields to participate in determining
11687   // whether the containing union is non-trivial.
11688   return FD->hasAttr<UnavailableAttr>();
11689 }
11690 
11691 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11692     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11693                                     void> {
11694   using Super =
11695       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11696                                     void>;
11697 
11698   DiagNonTrivalCUnionDefaultInitializeVisitor(
11699       QualType OrigTy, SourceLocation OrigLoc,
11700       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11701       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11702 
11703   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11704                      const FieldDecl *FD, bool InNonTrivialUnion) {
11705     if (const auto *AT = S.Context.getAsArrayType(QT))
11706       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11707                                      InNonTrivialUnion);
11708     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11709   }
11710 
11711   void visitARCStrong(QualType QT, const FieldDecl *FD,
11712                       bool InNonTrivialUnion) {
11713     if (InNonTrivialUnion)
11714       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11715           << 1 << 0 << QT << FD->getName();
11716   }
11717 
11718   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11719     if (InNonTrivialUnion)
11720       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11721           << 1 << 0 << QT << FD->getName();
11722   }
11723 
11724   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11725     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11726     if (RD->isUnion()) {
11727       if (OrigLoc.isValid()) {
11728         bool IsUnion = false;
11729         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11730           IsUnion = OrigRD->isUnion();
11731         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11732             << 0 << OrigTy << IsUnion << UseContext;
11733         // Reset OrigLoc so that this diagnostic is emitted only once.
11734         OrigLoc = SourceLocation();
11735       }
11736       InNonTrivialUnion = true;
11737     }
11738 
11739     if (InNonTrivialUnion)
11740       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11741           << 0 << 0 << QT.getUnqualifiedType() << "";
11742 
11743     for (const FieldDecl *FD : RD->fields())
11744       if (!shouldIgnoreForRecordTriviality(FD))
11745         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11746   }
11747 
11748   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11749 
11750   // The non-trivial C union type or the struct/union type that contains a
11751   // non-trivial C union.
11752   QualType OrigTy;
11753   SourceLocation OrigLoc;
11754   Sema::NonTrivialCUnionContext UseContext;
11755   Sema &S;
11756 };
11757 
11758 struct DiagNonTrivalCUnionDestructedTypeVisitor
11759     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11760   using Super =
11761       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11762 
11763   DiagNonTrivalCUnionDestructedTypeVisitor(
11764       QualType OrigTy, SourceLocation OrigLoc,
11765       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11766       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11767 
11768   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11769                      const FieldDecl *FD, bool InNonTrivialUnion) {
11770     if (const auto *AT = S.Context.getAsArrayType(QT))
11771       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11772                                      InNonTrivialUnion);
11773     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11774   }
11775 
11776   void visitARCStrong(QualType QT, const FieldDecl *FD,
11777                       bool InNonTrivialUnion) {
11778     if (InNonTrivialUnion)
11779       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11780           << 1 << 1 << QT << FD->getName();
11781   }
11782 
11783   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11784     if (InNonTrivialUnion)
11785       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11786           << 1 << 1 << QT << FD->getName();
11787   }
11788 
11789   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11790     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11791     if (RD->isUnion()) {
11792       if (OrigLoc.isValid()) {
11793         bool IsUnion = false;
11794         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11795           IsUnion = OrigRD->isUnion();
11796         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11797             << 1 << OrigTy << IsUnion << UseContext;
11798         // Reset OrigLoc so that this diagnostic is emitted only once.
11799         OrigLoc = SourceLocation();
11800       }
11801       InNonTrivialUnion = true;
11802     }
11803 
11804     if (InNonTrivialUnion)
11805       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11806           << 0 << 1 << QT.getUnqualifiedType() << "";
11807 
11808     for (const FieldDecl *FD : RD->fields())
11809       if (!shouldIgnoreForRecordTriviality(FD))
11810         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11811   }
11812 
11813   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11814   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11815                           bool InNonTrivialUnion) {}
11816 
11817   // The non-trivial C union type or the struct/union type that contains a
11818   // non-trivial C union.
11819   QualType OrigTy;
11820   SourceLocation OrigLoc;
11821   Sema::NonTrivialCUnionContext UseContext;
11822   Sema &S;
11823 };
11824 
11825 struct DiagNonTrivalCUnionCopyVisitor
11826     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11827   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11828 
11829   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11830                                  Sema::NonTrivialCUnionContext UseContext,
11831                                  Sema &S)
11832       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11833 
11834   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11835                      const FieldDecl *FD, bool InNonTrivialUnion) {
11836     if (const auto *AT = S.Context.getAsArrayType(QT))
11837       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11838                                      InNonTrivialUnion);
11839     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11840   }
11841 
11842   void visitARCStrong(QualType QT, const FieldDecl *FD,
11843                       bool InNonTrivialUnion) {
11844     if (InNonTrivialUnion)
11845       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11846           << 1 << 2 << QT << FD->getName();
11847   }
11848 
11849   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11850     if (InNonTrivialUnion)
11851       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11852           << 1 << 2 << QT << FD->getName();
11853   }
11854 
11855   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11856     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11857     if (RD->isUnion()) {
11858       if (OrigLoc.isValid()) {
11859         bool IsUnion = false;
11860         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11861           IsUnion = OrigRD->isUnion();
11862         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11863             << 2 << OrigTy << IsUnion << UseContext;
11864         // Reset OrigLoc so that this diagnostic is emitted only once.
11865         OrigLoc = SourceLocation();
11866       }
11867       InNonTrivialUnion = true;
11868     }
11869 
11870     if (InNonTrivialUnion)
11871       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11872           << 0 << 2 << QT.getUnqualifiedType() << "";
11873 
11874     for (const FieldDecl *FD : RD->fields())
11875       if (!shouldIgnoreForRecordTriviality(FD))
11876         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11877   }
11878 
11879   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11880                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11881   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11882   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11883                             bool InNonTrivialUnion) {}
11884 
11885   // The non-trivial C union type or the struct/union type that contains a
11886   // non-trivial C union.
11887   QualType OrigTy;
11888   SourceLocation OrigLoc;
11889   Sema::NonTrivialCUnionContext UseContext;
11890   Sema &S;
11891 };
11892 
11893 } // namespace
11894 
11895 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11896                                  NonTrivialCUnionContext UseContext,
11897                                  unsigned NonTrivialKind) {
11898   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11899           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11900           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11901          "shouldn't be called if type doesn't have a non-trivial C union");
11902 
11903   if ((NonTrivialKind & NTCUK_Init) &&
11904       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11905     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11906         .visit(QT, nullptr, false);
11907   if ((NonTrivialKind & NTCUK_Destruct) &&
11908       QT.hasNonTrivialToPrimitiveDestructCUnion())
11909     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11910         .visit(QT, nullptr, false);
11911   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11912     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11913         .visit(QT, nullptr, false);
11914 }
11915 
11916 /// AddInitializerToDecl - Adds the initializer Init to the
11917 /// declaration dcl. If DirectInit is true, this is C++ direct
11918 /// initialization rather than copy initialization.
11919 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11920   // If there is no declaration, there was an error parsing it.  Just ignore
11921   // the initializer.
11922   if (!RealDecl || RealDecl->isInvalidDecl()) {
11923     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11924     return;
11925   }
11926 
11927   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11928     // Pure-specifiers are handled in ActOnPureSpecifier.
11929     Diag(Method->getLocation(), diag::err_member_function_initialization)
11930       << Method->getDeclName() << Init->getSourceRange();
11931     Method->setInvalidDecl();
11932     return;
11933   }
11934 
11935   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11936   if (!VDecl) {
11937     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11938     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11939     RealDecl->setInvalidDecl();
11940     return;
11941   }
11942 
11943   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11944   if (VDecl->getType()->isUndeducedType()) {
11945     // Attempt typo correction early so that the type of the init expression can
11946     // be deduced based on the chosen correction if the original init contains a
11947     // TypoExpr.
11948     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11949     if (!Res.isUsable()) {
11950       // There are unresolved typos in Init, just drop them.
11951       // FIXME: improve the recovery strategy to preserve the Init.
11952       RealDecl->setInvalidDecl();
11953       return;
11954     }
11955     if (Res.get()->containsErrors()) {
11956       // Invalidate the decl as we don't know the type for recovery-expr yet.
11957       RealDecl->setInvalidDecl();
11958       VDecl->setInit(Res.get());
11959       return;
11960     }
11961     Init = Res.get();
11962 
11963     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11964       return;
11965   }
11966 
11967   // dllimport cannot be used on variable definitions.
11968   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11969     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11970     VDecl->setInvalidDecl();
11971     return;
11972   }
11973 
11974   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11975     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11976     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11977     VDecl->setInvalidDecl();
11978     return;
11979   }
11980 
11981   if (!VDecl->getType()->isDependentType()) {
11982     // A definition must end up with a complete type, which means it must be
11983     // complete with the restriction that an array type might be completed by
11984     // the initializer; note that later code assumes this restriction.
11985     QualType BaseDeclType = VDecl->getType();
11986     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11987       BaseDeclType = Array->getElementType();
11988     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11989                             diag::err_typecheck_decl_incomplete_type)) {
11990       RealDecl->setInvalidDecl();
11991       return;
11992     }
11993 
11994     // The variable can not have an abstract class type.
11995     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11996                                diag::err_abstract_type_in_decl,
11997                                AbstractVariableType))
11998       VDecl->setInvalidDecl();
11999   }
12000 
12001   // If adding the initializer will turn this declaration into a definition,
12002   // and we already have a definition for this variable, diagnose or otherwise
12003   // handle the situation.
12004   VarDecl *Def;
12005   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12006       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12007       !VDecl->isThisDeclarationADemotedDefinition() &&
12008       checkVarDeclRedefinition(Def, VDecl))
12009     return;
12010 
12011   if (getLangOpts().CPlusPlus) {
12012     // C++ [class.static.data]p4
12013     //   If a static data member is of const integral or const
12014     //   enumeration type, its declaration in the class definition can
12015     //   specify a constant-initializer which shall be an integral
12016     //   constant expression (5.19). In that case, the member can appear
12017     //   in integral constant expressions. The member shall still be
12018     //   defined in a namespace scope if it is used in the program and the
12019     //   namespace scope definition shall not contain an initializer.
12020     //
12021     // We already performed a redefinition check above, but for static
12022     // data members we also need to check whether there was an in-class
12023     // declaration with an initializer.
12024     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12025       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12026           << VDecl->getDeclName();
12027       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12028            diag::note_previous_initializer)
12029           << 0;
12030       return;
12031     }
12032 
12033     if (VDecl->hasLocalStorage())
12034       setFunctionHasBranchProtectedScope();
12035 
12036     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12037       VDecl->setInvalidDecl();
12038       return;
12039     }
12040   }
12041 
12042   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12043   // a kernel function cannot be initialized."
12044   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12045     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12046     VDecl->setInvalidDecl();
12047     return;
12048   }
12049 
12050   // The LoaderUninitialized attribute acts as a definition (of undef).
12051   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12052     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12053     VDecl->setInvalidDecl();
12054     return;
12055   }
12056 
12057   // Get the decls type and save a reference for later, since
12058   // CheckInitializerTypes may change it.
12059   QualType DclT = VDecl->getType(), SavT = DclT;
12060 
12061   // Expressions default to 'id' when we're in a debugger
12062   // and we are assigning it to a variable of Objective-C pointer type.
12063   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12064       Init->getType() == Context.UnknownAnyTy) {
12065     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12066     if (Result.isInvalid()) {
12067       VDecl->setInvalidDecl();
12068       return;
12069     }
12070     Init = Result.get();
12071   }
12072 
12073   // Perform the initialization.
12074   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12075   if (!VDecl->isInvalidDecl()) {
12076     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12077     InitializationKind Kind = InitializationKind::CreateForInit(
12078         VDecl->getLocation(), DirectInit, Init);
12079 
12080     MultiExprArg Args = Init;
12081     if (CXXDirectInit)
12082       Args = MultiExprArg(CXXDirectInit->getExprs(),
12083                           CXXDirectInit->getNumExprs());
12084 
12085     // Try to correct any TypoExprs in the initialization arguments.
12086     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12087       ExprResult Res = CorrectDelayedTyposInExpr(
12088           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12089           [this, Entity, Kind](Expr *E) {
12090             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12091             return Init.Failed() ? ExprError() : E;
12092           });
12093       if (Res.isInvalid()) {
12094         VDecl->setInvalidDecl();
12095       } else if (Res.get() != Args[Idx]) {
12096         Args[Idx] = Res.get();
12097       }
12098     }
12099     if (VDecl->isInvalidDecl())
12100       return;
12101 
12102     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12103                                    /*TopLevelOfInitList=*/false,
12104                                    /*TreatUnavailableAsInvalid=*/false);
12105     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12106     if (Result.isInvalid()) {
12107       // If the provied initializer fails to initialize the var decl,
12108       // we attach a recovery expr for better recovery.
12109       auto RecoveryExpr =
12110           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12111       if (RecoveryExpr.get())
12112         VDecl->setInit(RecoveryExpr.get());
12113       return;
12114     }
12115 
12116     Init = Result.getAs<Expr>();
12117   }
12118 
12119   // Check for self-references within variable initializers.
12120   // Variables declared within a function/method body (except for references)
12121   // are handled by a dataflow analysis.
12122   // This is undefined behavior in C++, but valid in C.
12123   if (getLangOpts().CPlusPlus) {
12124     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12125         VDecl->getType()->isReferenceType()) {
12126       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12127     }
12128   }
12129 
12130   // If the type changed, it means we had an incomplete type that was
12131   // completed by the initializer. For example:
12132   //   int ary[] = { 1, 3, 5 };
12133   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12134   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12135     VDecl->setType(DclT);
12136 
12137   if (!VDecl->isInvalidDecl()) {
12138     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12139 
12140     if (VDecl->hasAttr<BlocksAttr>())
12141       checkRetainCycles(VDecl, Init);
12142 
12143     // It is safe to assign a weak reference into a strong variable.
12144     // Although this code can still have problems:
12145     //   id x = self.weakProp;
12146     //   id y = self.weakProp;
12147     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12148     // paths through the function. This should be revisited if
12149     // -Wrepeated-use-of-weak is made flow-sensitive.
12150     if (FunctionScopeInfo *FSI = getCurFunction())
12151       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12152            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12153           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12154                            Init->getBeginLoc()))
12155         FSI->markSafeWeakUse(Init);
12156   }
12157 
12158   // The initialization is usually a full-expression.
12159   //
12160   // FIXME: If this is a braced initialization of an aggregate, it is not
12161   // an expression, and each individual field initializer is a separate
12162   // full-expression. For instance, in:
12163   //
12164   //   struct Temp { ~Temp(); };
12165   //   struct S { S(Temp); };
12166   //   struct T { S a, b; } t = { Temp(), Temp() }
12167   //
12168   // we should destroy the first Temp before constructing the second.
12169   ExprResult Result =
12170       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12171                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12172   if (Result.isInvalid()) {
12173     VDecl->setInvalidDecl();
12174     return;
12175   }
12176   Init = Result.get();
12177 
12178   // Attach the initializer to the decl.
12179   VDecl->setInit(Init);
12180 
12181   if (VDecl->isLocalVarDecl()) {
12182     // Don't check the initializer if the declaration is malformed.
12183     if (VDecl->isInvalidDecl()) {
12184       // do nothing
12185 
12186     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12187     // This is true even in C++ for OpenCL.
12188     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12189       CheckForConstantInitializer(Init, DclT);
12190 
12191     // Otherwise, C++ does not restrict the initializer.
12192     } else if (getLangOpts().CPlusPlus) {
12193       // do nothing
12194 
12195     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12196     // static storage duration shall be constant expressions or string literals.
12197     } else if (VDecl->getStorageClass() == SC_Static) {
12198       CheckForConstantInitializer(Init, DclT);
12199 
12200     // C89 is stricter than C99 for aggregate initializers.
12201     // C89 6.5.7p3: All the expressions [...] in an initializer list
12202     // for an object that has aggregate or union type shall be
12203     // constant expressions.
12204     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12205                isa<InitListExpr>(Init)) {
12206       const Expr *Culprit;
12207       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12208         Diag(Culprit->getExprLoc(),
12209              diag::ext_aggregate_init_not_constant)
12210           << Culprit->getSourceRange();
12211       }
12212     }
12213 
12214     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12215       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12216         if (VDecl->hasLocalStorage())
12217           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12218   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12219              VDecl->getLexicalDeclContext()->isRecord()) {
12220     // This is an in-class initialization for a static data member, e.g.,
12221     //
12222     // struct S {
12223     //   static const int value = 17;
12224     // };
12225 
12226     // C++ [class.mem]p4:
12227     //   A member-declarator can contain a constant-initializer only
12228     //   if it declares a static member (9.4) of const integral or
12229     //   const enumeration type, see 9.4.2.
12230     //
12231     // C++11 [class.static.data]p3:
12232     //   If a non-volatile non-inline const static data member is of integral
12233     //   or enumeration type, its declaration in the class definition can
12234     //   specify a brace-or-equal-initializer in which every initializer-clause
12235     //   that is an assignment-expression is a constant expression. A static
12236     //   data member of literal type can be declared in the class definition
12237     //   with the constexpr specifier; if so, its declaration shall specify a
12238     //   brace-or-equal-initializer in which every initializer-clause that is
12239     //   an assignment-expression is a constant expression.
12240 
12241     // Do nothing on dependent types.
12242     if (DclT->isDependentType()) {
12243 
12244     // Allow any 'static constexpr' members, whether or not they are of literal
12245     // type. We separately check that every constexpr variable is of literal
12246     // type.
12247     } else if (VDecl->isConstexpr()) {
12248 
12249     // Require constness.
12250     } else if (!DclT.isConstQualified()) {
12251       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12252         << Init->getSourceRange();
12253       VDecl->setInvalidDecl();
12254 
12255     // We allow integer constant expressions in all cases.
12256     } else if (DclT->isIntegralOrEnumerationType()) {
12257       // Check whether the expression is a constant expression.
12258       SourceLocation Loc;
12259       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12260         // In C++11, a non-constexpr const static data member with an
12261         // in-class initializer cannot be volatile.
12262         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12263       else if (Init->isValueDependent())
12264         ; // Nothing to check.
12265       else if (Init->isIntegerConstantExpr(Context, &Loc))
12266         ; // Ok, it's an ICE!
12267       else if (Init->getType()->isScopedEnumeralType() &&
12268                Init->isCXX11ConstantExpr(Context))
12269         ; // Ok, it is a scoped-enum constant expression.
12270       else if (Init->isEvaluatable(Context)) {
12271         // If we can constant fold the initializer through heroics, accept it,
12272         // but report this as a use of an extension for -pedantic.
12273         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12274           << Init->getSourceRange();
12275       } else {
12276         // Otherwise, this is some crazy unknown case.  Report the issue at the
12277         // location provided by the isIntegerConstantExpr failed check.
12278         Diag(Loc, diag::err_in_class_initializer_non_constant)
12279           << Init->getSourceRange();
12280         VDecl->setInvalidDecl();
12281       }
12282 
12283     // We allow foldable floating-point constants as an extension.
12284     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12285       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12286       // it anyway and provide a fixit to add the 'constexpr'.
12287       if (getLangOpts().CPlusPlus11) {
12288         Diag(VDecl->getLocation(),
12289              diag::ext_in_class_initializer_float_type_cxx11)
12290             << DclT << Init->getSourceRange();
12291         Diag(VDecl->getBeginLoc(),
12292              diag::note_in_class_initializer_float_type_cxx11)
12293             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12294       } else {
12295         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12296           << DclT << Init->getSourceRange();
12297 
12298         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12299           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12300             << Init->getSourceRange();
12301           VDecl->setInvalidDecl();
12302         }
12303       }
12304 
12305     // Suggest adding 'constexpr' in C++11 for literal types.
12306     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12307       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12308           << DclT << Init->getSourceRange()
12309           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12310       VDecl->setConstexpr(true);
12311 
12312     } else {
12313       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12314         << DclT << Init->getSourceRange();
12315       VDecl->setInvalidDecl();
12316     }
12317   } else if (VDecl->isFileVarDecl()) {
12318     // In C, extern is typically used to avoid tentative definitions when
12319     // declaring variables in headers, but adding an intializer makes it a
12320     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12321     // In C++, extern is often used to give implictly static const variables
12322     // external linkage, so don't warn in that case. If selectany is present,
12323     // this might be header code intended for C and C++ inclusion, so apply the
12324     // C++ rules.
12325     if (VDecl->getStorageClass() == SC_Extern &&
12326         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12327          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12328         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12329         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12330       Diag(VDecl->getLocation(), diag::warn_extern_init);
12331 
12332     // In Microsoft C++ mode, a const variable defined in namespace scope has
12333     // external linkage by default if the variable is declared with
12334     // __declspec(dllexport).
12335     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12336         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12337         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12338       VDecl->setStorageClass(SC_Extern);
12339 
12340     // C99 6.7.8p4. All file scoped initializers need to be constant.
12341     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12342       CheckForConstantInitializer(Init, DclT);
12343   }
12344 
12345   QualType InitType = Init->getType();
12346   if (!InitType.isNull() &&
12347       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12348        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12349     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12350 
12351   // We will represent direct-initialization similarly to copy-initialization:
12352   //    int x(1);  -as-> int x = 1;
12353   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12354   //
12355   // Clients that want to distinguish between the two forms, can check for
12356   // direct initializer using VarDecl::getInitStyle().
12357   // A major benefit is that clients that don't particularly care about which
12358   // exactly form was it (like the CodeGen) can handle both cases without
12359   // special case code.
12360 
12361   // C++ 8.5p11:
12362   // The form of initialization (using parentheses or '=') is generally
12363   // insignificant, but does matter when the entity being initialized has a
12364   // class type.
12365   if (CXXDirectInit) {
12366     assert(DirectInit && "Call-style initializer must be direct init.");
12367     VDecl->setInitStyle(VarDecl::CallInit);
12368   } else if (DirectInit) {
12369     // This must be list-initialization. No other way is direct-initialization.
12370     VDecl->setInitStyle(VarDecl::ListInit);
12371   }
12372 
12373   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12374     DeclsToCheckForDeferredDiags.push_back(VDecl);
12375   CheckCompleteVariableDeclaration(VDecl);
12376 }
12377 
12378 /// ActOnInitializerError - Given that there was an error parsing an
12379 /// initializer for the given declaration, try to return to some form
12380 /// of sanity.
12381 void Sema::ActOnInitializerError(Decl *D) {
12382   // Our main concern here is re-establishing invariants like "a
12383   // variable's type is either dependent or complete".
12384   if (!D || D->isInvalidDecl()) return;
12385 
12386   VarDecl *VD = dyn_cast<VarDecl>(D);
12387   if (!VD) return;
12388 
12389   // Bindings are not usable if we can't make sense of the initializer.
12390   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12391     for (auto *BD : DD->bindings())
12392       BD->setInvalidDecl();
12393 
12394   // Auto types are meaningless if we can't make sense of the initializer.
12395   if (VD->getType()->isUndeducedType()) {
12396     D->setInvalidDecl();
12397     return;
12398   }
12399 
12400   QualType Ty = VD->getType();
12401   if (Ty->isDependentType()) return;
12402 
12403   // Require a complete type.
12404   if (RequireCompleteType(VD->getLocation(),
12405                           Context.getBaseElementType(Ty),
12406                           diag::err_typecheck_decl_incomplete_type)) {
12407     VD->setInvalidDecl();
12408     return;
12409   }
12410 
12411   // Require a non-abstract type.
12412   if (RequireNonAbstractType(VD->getLocation(), Ty,
12413                              diag::err_abstract_type_in_decl,
12414                              AbstractVariableType)) {
12415     VD->setInvalidDecl();
12416     return;
12417   }
12418 
12419   // Don't bother complaining about constructors or destructors,
12420   // though.
12421 }
12422 
12423 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12424   // If there is no declaration, there was an error parsing it. Just ignore it.
12425   if (!RealDecl)
12426     return;
12427 
12428   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12429     QualType Type = Var->getType();
12430 
12431     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12432     if (isa<DecompositionDecl>(RealDecl)) {
12433       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12434       Var->setInvalidDecl();
12435       return;
12436     }
12437 
12438     if (Type->isUndeducedType() &&
12439         DeduceVariableDeclarationType(Var, false, nullptr))
12440       return;
12441 
12442     // C++11 [class.static.data]p3: A static data member can be declared with
12443     // the constexpr specifier; if so, its declaration shall specify
12444     // a brace-or-equal-initializer.
12445     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12446     // the definition of a variable [...] or the declaration of a static data
12447     // member.
12448     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12449         !Var->isThisDeclarationADemotedDefinition()) {
12450       if (Var->isStaticDataMember()) {
12451         // C++1z removes the relevant rule; the in-class declaration is always
12452         // a definition there.
12453         if (!getLangOpts().CPlusPlus17 &&
12454             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12455           Diag(Var->getLocation(),
12456                diag::err_constexpr_static_mem_var_requires_init)
12457               << Var;
12458           Var->setInvalidDecl();
12459           return;
12460         }
12461       } else {
12462         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12463         Var->setInvalidDecl();
12464         return;
12465       }
12466     }
12467 
12468     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12469     // be initialized.
12470     if (!Var->isInvalidDecl() &&
12471         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12472         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12473       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12474       Var->setInvalidDecl();
12475       return;
12476     }
12477 
12478     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12479       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12480         if (!RD->hasTrivialDefaultConstructor()) {
12481           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12482           Var->setInvalidDecl();
12483           return;
12484         }
12485       }
12486       if (Var->getStorageClass() == SC_Extern) {
12487         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12488             << Var;
12489         Var->setInvalidDecl();
12490         return;
12491       }
12492     }
12493 
12494     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12495     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12496         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12497       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12498                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12499 
12500 
12501     switch (DefKind) {
12502     case VarDecl::Definition:
12503       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12504         break;
12505 
12506       // We have an out-of-line definition of a static data member
12507       // that has an in-class initializer, so we type-check this like
12508       // a declaration.
12509       //
12510       LLVM_FALLTHROUGH;
12511 
12512     case VarDecl::DeclarationOnly:
12513       // It's only a declaration.
12514 
12515       // Block scope. C99 6.7p7: If an identifier for an object is
12516       // declared with no linkage (C99 6.2.2p6), the type for the
12517       // object shall be complete.
12518       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12519           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12520           RequireCompleteType(Var->getLocation(), Type,
12521                               diag::err_typecheck_decl_incomplete_type))
12522         Var->setInvalidDecl();
12523 
12524       // Make sure that the type is not abstract.
12525       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12526           RequireNonAbstractType(Var->getLocation(), Type,
12527                                  diag::err_abstract_type_in_decl,
12528                                  AbstractVariableType))
12529         Var->setInvalidDecl();
12530       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12531           Var->getStorageClass() == SC_PrivateExtern) {
12532         Diag(Var->getLocation(), diag::warn_private_extern);
12533         Diag(Var->getLocation(), diag::note_private_extern);
12534       }
12535 
12536       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12537           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12538         ExternalDeclarations.push_back(Var);
12539 
12540       return;
12541 
12542     case VarDecl::TentativeDefinition:
12543       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12544       // object that has file scope without an initializer, and without a
12545       // storage-class specifier or with the storage-class specifier "static",
12546       // constitutes a tentative definition. Note: A tentative definition with
12547       // external linkage is valid (C99 6.2.2p5).
12548       if (!Var->isInvalidDecl()) {
12549         if (const IncompleteArrayType *ArrayT
12550                                     = Context.getAsIncompleteArrayType(Type)) {
12551           if (RequireCompleteSizedType(
12552                   Var->getLocation(), ArrayT->getElementType(),
12553                   diag::err_array_incomplete_or_sizeless_type))
12554             Var->setInvalidDecl();
12555         } else if (Var->getStorageClass() == SC_Static) {
12556           // C99 6.9.2p3: If the declaration of an identifier for an object is
12557           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12558           // declared type shall not be an incomplete type.
12559           // NOTE: code such as the following
12560           //     static struct s;
12561           //     struct s { int a; };
12562           // is accepted by gcc. Hence here we issue a warning instead of
12563           // an error and we do not invalidate the static declaration.
12564           // NOTE: to avoid multiple warnings, only check the first declaration.
12565           if (Var->isFirstDecl())
12566             RequireCompleteType(Var->getLocation(), Type,
12567                                 diag::ext_typecheck_decl_incomplete_type);
12568         }
12569       }
12570 
12571       // Record the tentative definition; we're done.
12572       if (!Var->isInvalidDecl())
12573         TentativeDefinitions.push_back(Var);
12574       return;
12575     }
12576 
12577     // Provide a specific diagnostic for uninitialized variable
12578     // definitions with incomplete array type.
12579     if (Type->isIncompleteArrayType()) {
12580       Diag(Var->getLocation(),
12581            diag::err_typecheck_incomplete_array_needs_initializer);
12582       Var->setInvalidDecl();
12583       return;
12584     }
12585 
12586     // Provide a specific diagnostic for uninitialized variable
12587     // definitions with reference type.
12588     if (Type->isReferenceType()) {
12589       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12590           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12591       Var->setInvalidDecl();
12592       return;
12593     }
12594 
12595     // Do not attempt to type-check the default initializer for a
12596     // variable with dependent type.
12597     if (Type->isDependentType())
12598       return;
12599 
12600     if (Var->isInvalidDecl())
12601       return;
12602 
12603     if (!Var->hasAttr<AliasAttr>()) {
12604       if (RequireCompleteType(Var->getLocation(),
12605                               Context.getBaseElementType(Type),
12606                               diag::err_typecheck_decl_incomplete_type)) {
12607         Var->setInvalidDecl();
12608         return;
12609       }
12610     } else {
12611       return;
12612     }
12613 
12614     // The variable can not have an abstract class type.
12615     if (RequireNonAbstractType(Var->getLocation(), Type,
12616                                diag::err_abstract_type_in_decl,
12617                                AbstractVariableType)) {
12618       Var->setInvalidDecl();
12619       return;
12620     }
12621 
12622     // Check for jumps past the implicit initializer.  C++0x
12623     // clarifies that this applies to a "variable with automatic
12624     // storage duration", not a "local variable".
12625     // C++11 [stmt.dcl]p3
12626     //   A program that jumps from a point where a variable with automatic
12627     //   storage duration is not in scope to a point where it is in scope is
12628     //   ill-formed unless the variable has scalar type, class type with a
12629     //   trivial default constructor and a trivial destructor, a cv-qualified
12630     //   version of one of these types, or an array of one of the preceding
12631     //   types and is declared without an initializer.
12632     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12633       if (const RecordType *Record
12634             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12635         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12636         // Mark the function (if we're in one) for further checking even if the
12637         // looser rules of C++11 do not require such checks, so that we can
12638         // diagnose incompatibilities with C++98.
12639         if (!CXXRecord->isPOD())
12640           setFunctionHasBranchProtectedScope();
12641       }
12642     }
12643     // In OpenCL, we can't initialize objects in the __local address space,
12644     // even implicitly, so don't synthesize an implicit initializer.
12645     if (getLangOpts().OpenCL &&
12646         Var->getType().getAddressSpace() == LangAS::opencl_local)
12647       return;
12648     // C++03 [dcl.init]p9:
12649     //   If no initializer is specified for an object, and the
12650     //   object is of (possibly cv-qualified) non-POD class type (or
12651     //   array thereof), the object shall be default-initialized; if
12652     //   the object is of const-qualified type, the underlying class
12653     //   type shall have a user-declared default
12654     //   constructor. Otherwise, if no initializer is specified for
12655     //   a non- static object, the object and its subobjects, if
12656     //   any, have an indeterminate initial value); if the object
12657     //   or any of its subobjects are of const-qualified type, the
12658     //   program is ill-formed.
12659     // C++0x [dcl.init]p11:
12660     //   If no initializer is specified for an object, the object is
12661     //   default-initialized; [...].
12662     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12663     InitializationKind Kind
12664       = InitializationKind::CreateDefault(Var->getLocation());
12665 
12666     InitializationSequence InitSeq(*this, Entity, Kind, None);
12667     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12668 
12669     if (Init.get()) {
12670       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12671       // This is important for template substitution.
12672       Var->setInitStyle(VarDecl::CallInit);
12673     } else if (Init.isInvalid()) {
12674       // If default-init fails, attach a recovery-expr initializer to track
12675       // that initialization was attempted and failed.
12676       auto RecoveryExpr =
12677           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12678       if (RecoveryExpr.get())
12679         Var->setInit(RecoveryExpr.get());
12680     }
12681 
12682     CheckCompleteVariableDeclaration(Var);
12683   }
12684 }
12685 
12686 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12687   // If there is no declaration, there was an error parsing it. Ignore it.
12688   if (!D)
12689     return;
12690 
12691   VarDecl *VD = dyn_cast<VarDecl>(D);
12692   if (!VD) {
12693     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12694     D->setInvalidDecl();
12695     return;
12696   }
12697 
12698   VD->setCXXForRangeDecl(true);
12699 
12700   // for-range-declaration cannot be given a storage class specifier.
12701   int Error = -1;
12702   switch (VD->getStorageClass()) {
12703   case SC_None:
12704     break;
12705   case SC_Extern:
12706     Error = 0;
12707     break;
12708   case SC_Static:
12709     Error = 1;
12710     break;
12711   case SC_PrivateExtern:
12712     Error = 2;
12713     break;
12714   case SC_Auto:
12715     Error = 3;
12716     break;
12717   case SC_Register:
12718     Error = 4;
12719     break;
12720   }
12721   if (Error != -1) {
12722     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12723         << VD << Error;
12724     D->setInvalidDecl();
12725   }
12726 }
12727 
12728 StmtResult
12729 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12730                                  IdentifierInfo *Ident,
12731                                  ParsedAttributes &Attrs,
12732                                  SourceLocation AttrEnd) {
12733   // C++1y [stmt.iter]p1:
12734   //   A range-based for statement of the form
12735   //      for ( for-range-identifier : for-range-initializer ) statement
12736   //   is equivalent to
12737   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12738   DeclSpec DS(Attrs.getPool().getFactory());
12739 
12740   const char *PrevSpec;
12741   unsigned DiagID;
12742   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12743                      getPrintingPolicy());
12744 
12745   Declarator D(DS, DeclaratorContext::ForContext);
12746   D.SetIdentifier(Ident, IdentLoc);
12747   D.takeAttributes(Attrs, AttrEnd);
12748 
12749   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12750                 IdentLoc);
12751   Decl *Var = ActOnDeclarator(S, D);
12752   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12753   FinalizeDeclaration(Var);
12754   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12755                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12756 }
12757 
12758 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12759   if (var->isInvalidDecl()) return;
12760 
12761   if (getLangOpts().OpenCL) {
12762     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12763     // initialiser
12764     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12765         !var->hasInit()) {
12766       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12767           << 1 /*Init*/;
12768       var->setInvalidDecl();
12769       return;
12770     }
12771   }
12772 
12773   // In Objective-C, don't allow jumps past the implicit initialization of a
12774   // local retaining variable.
12775   if (getLangOpts().ObjC &&
12776       var->hasLocalStorage()) {
12777     switch (var->getType().getObjCLifetime()) {
12778     case Qualifiers::OCL_None:
12779     case Qualifiers::OCL_ExplicitNone:
12780     case Qualifiers::OCL_Autoreleasing:
12781       break;
12782 
12783     case Qualifiers::OCL_Weak:
12784     case Qualifiers::OCL_Strong:
12785       setFunctionHasBranchProtectedScope();
12786       break;
12787     }
12788   }
12789 
12790   if (var->hasLocalStorage() &&
12791       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12792     setFunctionHasBranchProtectedScope();
12793 
12794   // Warn about externally-visible variables being defined without a
12795   // prior declaration.  We only want to do this for global
12796   // declarations, but we also specifically need to avoid doing it for
12797   // class members because the linkage of an anonymous class can
12798   // change if it's later given a typedef name.
12799   if (var->isThisDeclarationADefinition() &&
12800       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12801       var->isExternallyVisible() && var->hasLinkage() &&
12802       !var->isInline() && !var->getDescribedVarTemplate() &&
12803       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12804       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12805       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12806                                   var->getLocation())) {
12807     // Find a previous declaration that's not a definition.
12808     VarDecl *prev = var->getPreviousDecl();
12809     while (prev && prev->isThisDeclarationADefinition())
12810       prev = prev->getPreviousDecl();
12811 
12812     if (!prev) {
12813       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12814       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12815           << /* variable */ 0;
12816     }
12817   }
12818 
12819   // Cache the result of checking for constant initialization.
12820   Optional<bool> CacheHasConstInit;
12821   const Expr *CacheCulprit = nullptr;
12822   auto checkConstInit = [&]() mutable {
12823     if (!CacheHasConstInit)
12824       CacheHasConstInit = var->getInit()->isConstantInitializer(
12825             Context, var->getType()->isReferenceType(), &CacheCulprit);
12826     return *CacheHasConstInit;
12827   };
12828 
12829   if (var->getTLSKind() == VarDecl::TLS_Static) {
12830     if (var->getType().isDestructedType()) {
12831       // GNU C++98 edits for __thread, [basic.start.term]p3:
12832       //   The type of an object with thread storage duration shall not
12833       //   have a non-trivial destructor.
12834       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12835       if (getLangOpts().CPlusPlus11)
12836         Diag(var->getLocation(), diag::note_use_thread_local);
12837     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12838       if (!checkConstInit()) {
12839         // GNU C++98 edits for __thread, [basic.start.init]p4:
12840         //   An object of thread storage duration shall not require dynamic
12841         //   initialization.
12842         // FIXME: Need strict checking here.
12843         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12844           << CacheCulprit->getSourceRange();
12845         if (getLangOpts().CPlusPlus11)
12846           Diag(var->getLocation(), diag::note_use_thread_local);
12847       }
12848     }
12849   }
12850 
12851   // Apply section attributes and pragmas to global variables.
12852   bool GlobalStorage = var->hasGlobalStorage();
12853   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12854       !inTemplateInstantiation()) {
12855     PragmaStack<StringLiteral *> *Stack = nullptr;
12856     int SectionFlags = ASTContext::PSF_Read;
12857     if (var->getType().isConstQualified())
12858       Stack = &ConstSegStack;
12859     else if (!var->getInit()) {
12860       Stack = &BSSSegStack;
12861       SectionFlags |= ASTContext::PSF_Write;
12862     } else {
12863       Stack = &DataSegStack;
12864       SectionFlags |= ASTContext::PSF_Write;
12865     }
12866     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12867       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12868         SectionFlags |= ASTContext::PSF_Implicit;
12869       UnifySection(SA->getName(), SectionFlags, var);
12870     } else if (Stack->CurrentValue) {
12871       SectionFlags |= ASTContext::PSF_Implicit;
12872       auto SectionName = Stack->CurrentValue->getString();
12873       var->addAttr(SectionAttr::CreateImplicit(
12874           Context, SectionName, Stack->CurrentPragmaLocation,
12875           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12876       if (UnifySection(SectionName, SectionFlags, var))
12877         var->dropAttr<SectionAttr>();
12878     }
12879 
12880     // Apply the init_seg attribute if this has an initializer.  If the
12881     // initializer turns out to not be dynamic, we'll end up ignoring this
12882     // attribute.
12883     if (CurInitSeg && var->getInit())
12884       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12885                                                CurInitSegLoc,
12886                                                AttributeCommonInfo::AS_Pragma));
12887   }
12888 
12889   // All the following checks are C++ only.
12890   if (!getLangOpts().CPlusPlus) {
12891       // If this variable must be emitted, add it as an initializer for the
12892       // current module.
12893      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12894        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12895      return;
12896   }
12897 
12898   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12899     CheckCompleteDecompositionDeclaration(DD);
12900 
12901   QualType type = var->getType();
12902   if (type->isDependentType()) return;
12903 
12904   if (var->hasAttr<BlocksAttr>())
12905     getCurFunction()->addByrefBlockVar(var);
12906 
12907   Expr *Init = var->getInit();
12908   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12909   QualType baseType = Context.getBaseElementType(type);
12910 
12911   if (Init && !Init->isValueDependent()) {
12912     if (var->isConstexpr()) {
12913       SmallVector<PartialDiagnosticAt, 8> Notes;
12914       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12915         SourceLocation DiagLoc = var->getLocation();
12916         // If the note doesn't add any useful information other than a source
12917         // location, fold it into the primary diagnostic.
12918         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12919               diag::note_invalid_subexpr_in_const_expr) {
12920           DiagLoc = Notes[0].first;
12921           Notes.clear();
12922         }
12923         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12924           << var << Init->getSourceRange();
12925         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12926           Diag(Notes[I].first, Notes[I].second);
12927       }
12928     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12929       // Check whether the initializer of a const variable of integral or
12930       // enumeration type is an ICE now, since we can't tell whether it was
12931       // initialized by a constant expression if we check later.
12932       var->checkInitIsICE();
12933     }
12934 
12935     // Don't emit further diagnostics about constexpr globals since they
12936     // were just diagnosed.
12937     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12938       // FIXME: Need strict checking in C++03 here.
12939       bool DiagErr = getLangOpts().CPlusPlus11
12940           ? !var->checkInitIsICE() : !checkConstInit();
12941       if (DiagErr) {
12942         auto *Attr = var->getAttr<ConstInitAttr>();
12943         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12944           << Init->getSourceRange();
12945         Diag(Attr->getLocation(),
12946              diag::note_declared_required_constant_init_here)
12947             << Attr->getRange() << Attr->isConstinit();
12948         if (getLangOpts().CPlusPlus11) {
12949           APValue Value;
12950           SmallVector<PartialDiagnosticAt, 8> Notes;
12951           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12952           for (auto &it : Notes)
12953             Diag(it.first, it.second);
12954         } else {
12955           Diag(CacheCulprit->getExprLoc(),
12956                diag::note_invalid_subexpr_in_const_expr)
12957               << CacheCulprit->getSourceRange();
12958         }
12959       }
12960     }
12961     else if (!var->isConstexpr() && IsGlobal &&
12962              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12963                                     var->getLocation())) {
12964       // Warn about globals which don't have a constant initializer.  Don't
12965       // warn about globals with a non-trivial destructor because we already
12966       // warned about them.
12967       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12968       if (!(RD && !RD->hasTrivialDestructor())) {
12969         if (!checkConstInit())
12970           Diag(var->getLocation(), diag::warn_global_constructor)
12971             << Init->getSourceRange();
12972       }
12973     }
12974   }
12975 
12976   // Require the destructor.
12977   if (const RecordType *recordType = baseType->getAs<RecordType>())
12978     FinalizeVarWithDestructor(var, recordType);
12979 
12980   // If this variable must be emitted, add it as an initializer for the current
12981   // module.
12982   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12983     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12984 }
12985 
12986 /// Determines if a variable's alignment is dependent.
12987 static bool hasDependentAlignment(VarDecl *VD) {
12988   if (VD->getType()->isDependentType())
12989     return true;
12990   for (auto *I : VD->specific_attrs<AlignedAttr>())
12991     if (I->isAlignmentDependent())
12992       return true;
12993   return false;
12994 }
12995 
12996 /// Check if VD needs to be dllexport/dllimport due to being in a
12997 /// dllexport/import function.
12998 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12999   assert(VD->isStaticLocal());
13000 
13001   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13002 
13003   // Find outermost function when VD is in lambda function.
13004   while (FD && !getDLLAttr(FD) &&
13005          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13006          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13007     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13008   }
13009 
13010   if (!FD)
13011     return;
13012 
13013   // Static locals inherit dll attributes from their function.
13014   if (Attr *A = getDLLAttr(FD)) {
13015     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13016     NewAttr->setInherited(true);
13017     VD->addAttr(NewAttr);
13018   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13019     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13020     NewAttr->setInherited(true);
13021     VD->addAttr(NewAttr);
13022 
13023     // Export this function to enforce exporting this static variable even
13024     // if it is not used in this compilation unit.
13025     if (!FD->hasAttr<DLLExportAttr>())
13026       FD->addAttr(NewAttr);
13027 
13028   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13029     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13030     NewAttr->setInherited(true);
13031     VD->addAttr(NewAttr);
13032   }
13033 }
13034 
13035 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13036 /// any semantic actions necessary after any initializer has been attached.
13037 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13038   // Note that we are no longer parsing the initializer for this declaration.
13039   ParsingInitForAutoVars.erase(ThisDecl);
13040 
13041   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13042   if (!VD)
13043     return;
13044 
13045   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13046   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13047       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13048     if (PragmaClangBSSSection.Valid)
13049       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13050           Context, PragmaClangBSSSection.SectionName,
13051           PragmaClangBSSSection.PragmaLocation,
13052           AttributeCommonInfo::AS_Pragma));
13053     if (PragmaClangDataSection.Valid)
13054       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13055           Context, PragmaClangDataSection.SectionName,
13056           PragmaClangDataSection.PragmaLocation,
13057           AttributeCommonInfo::AS_Pragma));
13058     if (PragmaClangRodataSection.Valid)
13059       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13060           Context, PragmaClangRodataSection.SectionName,
13061           PragmaClangRodataSection.PragmaLocation,
13062           AttributeCommonInfo::AS_Pragma));
13063     if (PragmaClangRelroSection.Valid)
13064       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13065           Context, PragmaClangRelroSection.SectionName,
13066           PragmaClangRelroSection.PragmaLocation,
13067           AttributeCommonInfo::AS_Pragma));
13068   }
13069 
13070   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13071     for (auto *BD : DD->bindings()) {
13072       FinalizeDeclaration(BD);
13073     }
13074   }
13075 
13076   checkAttributesAfterMerging(*this, *VD);
13077 
13078   // Perform TLS alignment check here after attributes attached to the variable
13079   // which may affect the alignment have been processed. Only perform the check
13080   // if the target has a maximum TLS alignment (zero means no constraints).
13081   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13082     // Protect the check so that it's not performed on dependent types and
13083     // dependent alignments (we can't determine the alignment in that case).
13084     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13085         !VD->isInvalidDecl()) {
13086       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13087       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13088         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13089           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13090           << (unsigned)MaxAlignChars.getQuantity();
13091       }
13092     }
13093   }
13094 
13095   if (VD->isStaticLocal()) {
13096     CheckStaticLocalForDllExport(VD);
13097 
13098     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13099       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13100       // function, only __shared__ variables or variables without any device
13101       // memory qualifiers may be declared with static storage class.
13102       // Note: It is unclear how a function-scope non-const static variable
13103       // without device memory qualifier is implemented, therefore only static
13104       // const variable without device memory qualifier is allowed.
13105       [&]() {
13106         if (!getLangOpts().CUDA)
13107           return;
13108         if (VD->hasAttr<CUDASharedAttr>())
13109           return;
13110         if (VD->getType().isConstQualified() &&
13111             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13112           return;
13113         if (CUDADiagIfDeviceCode(VD->getLocation(),
13114                                  diag::err_device_static_local_var)
13115             << CurrentCUDATarget())
13116           VD->setInvalidDecl();
13117       }();
13118     }
13119   }
13120 
13121   // Perform check for initializers of device-side global variables.
13122   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13123   // 7.5). We must also apply the same checks to all __shared__
13124   // variables whether they are local or not. CUDA also allows
13125   // constant initializers for __constant__ and __device__ variables.
13126   if (getLangOpts().CUDA)
13127     checkAllowedCUDAInitializer(VD);
13128 
13129   // Grab the dllimport or dllexport attribute off of the VarDecl.
13130   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13131 
13132   // Imported static data members cannot be defined out-of-line.
13133   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13134     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13135         VD->isThisDeclarationADefinition()) {
13136       // We allow definitions of dllimport class template static data members
13137       // with a warning.
13138       CXXRecordDecl *Context =
13139         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13140       bool IsClassTemplateMember =
13141           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13142           Context->getDescribedClassTemplate();
13143 
13144       Diag(VD->getLocation(),
13145            IsClassTemplateMember
13146                ? diag::warn_attribute_dllimport_static_field_definition
13147                : diag::err_attribute_dllimport_static_field_definition);
13148       Diag(IA->getLocation(), diag::note_attribute);
13149       if (!IsClassTemplateMember)
13150         VD->setInvalidDecl();
13151     }
13152   }
13153 
13154   // dllimport/dllexport variables cannot be thread local, their TLS index
13155   // isn't exported with the variable.
13156   if (DLLAttr && VD->getTLSKind()) {
13157     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13158     if (F && getDLLAttr(F)) {
13159       assert(VD->isStaticLocal());
13160       // But if this is a static local in a dlimport/dllexport function, the
13161       // function will never be inlined, which means the var would never be
13162       // imported, so having it marked import/export is safe.
13163     } else {
13164       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13165                                                                     << DLLAttr;
13166       VD->setInvalidDecl();
13167     }
13168   }
13169 
13170   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13171     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13172       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13173       VD->dropAttr<UsedAttr>();
13174     }
13175   }
13176 
13177   const DeclContext *DC = VD->getDeclContext();
13178   // If there's a #pragma GCC visibility in scope, and this isn't a class
13179   // member, set the visibility of this variable.
13180   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13181     AddPushedVisibilityAttribute(VD);
13182 
13183   // FIXME: Warn on unused var template partial specializations.
13184   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13185     MarkUnusedFileScopedDecl(VD);
13186 
13187   // Now we have parsed the initializer and can update the table of magic
13188   // tag values.
13189   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13190       !VD->getType()->isIntegralOrEnumerationType())
13191     return;
13192 
13193   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13194     const Expr *MagicValueExpr = VD->getInit();
13195     if (!MagicValueExpr) {
13196       continue;
13197     }
13198     Optional<llvm::APSInt> MagicValueInt;
13199     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13200       Diag(I->getRange().getBegin(),
13201            diag::err_type_tag_for_datatype_not_ice)
13202         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13203       continue;
13204     }
13205     if (MagicValueInt->getActiveBits() > 64) {
13206       Diag(I->getRange().getBegin(),
13207            diag::err_type_tag_for_datatype_too_large)
13208         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13209       continue;
13210     }
13211     uint64_t MagicValue = MagicValueInt->getZExtValue();
13212     RegisterTypeTagForDatatype(I->getArgumentKind(),
13213                                MagicValue,
13214                                I->getMatchingCType(),
13215                                I->getLayoutCompatible(),
13216                                I->getMustBeNull());
13217   }
13218 }
13219 
13220 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13221   auto *VD = dyn_cast<VarDecl>(DD);
13222   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13223 }
13224 
13225 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13226                                                    ArrayRef<Decl *> Group) {
13227   SmallVector<Decl*, 8> Decls;
13228 
13229   if (DS.isTypeSpecOwned())
13230     Decls.push_back(DS.getRepAsDecl());
13231 
13232   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13233   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13234   bool DiagnosedMultipleDecomps = false;
13235   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13236   bool DiagnosedNonDeducedAuto = false;
13237 
13238   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13239     if (Decl *D = Group[i]) {
13240       // For declarators, there are some additional syntactic-ish checks we need
13241       // to perform.
13242       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13243         if (!FirstDeclaratorInGroup)
13244           FirstDeclaratorInGroup = DD;
13245         if (!FirstDecompDeclaratorInGroup)
13246           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13247         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13248             !hasDeducedAuto(DD))
13249           FirstNonDeducedAutoInGroup = DD;
13250 
13251         if (FirstDeclaratorInGroup != DD) {
13252           // A decomposition declaration cannot be combined with any other
13253           // declaration in the same group.
13254           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13255             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13256                  diag::err_decomp_decl_not_alone)
13257                 << FirstDeclaratorInGroup->getSourceRange()
13258                 << DD->getSourceRange();
13259             DiagnosedMultipleDecomps = true;
13260           }
13261 
13262           // A declarator that uses 'auto' in any way other than to declare a
13263           // variable with a deduced type cannot be combined with any other
13264           // declarator in the same group.
13265           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13266             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13267                  diag::err_auto_non_deduced_not_alone)
13268                 << FirstNonDeducedAutoInGroup->getType()
13269                        ->hasAutoForTrailingReturnType()
13270                 << FirstDeclaratorInGroup->getSourceRange()
13271                 << DD->getSourceRange();
13272             DiagnosedNonDeducedAuto = true;
13273           }
13274         }
13275       }
13276 
13277       Decls.push_back(D);
13278     }
13279   }
13280 
13281   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13282     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13283       handleTagNumbering(Tag, S);
13284       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13285           getLangOpts().CPlusPlus)
13286         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13287     }
13288   }
13289 
13290   return BuildDeclaratorGroup(Decls);
13291 }
13292 
13293 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13294 /// group, performing any necessary semantic checking.
13295 Sema::DeclGroupPtrTy
13296 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13297   // C++14 [dcl.spec.auto]p7: (DR1347)
13298   //   If the type that replaces the placeholder type is not the same in each
13299   //   deduction, the program is ill-formed.
13300   if (Group.size() > 1) {
13301     QualType Deduced;
13302     VarDecl *DeducedDecl = nullptr;
13303     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13304       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13305       if (!D || D->isInvalidDecl())
13306         break;
13307       DeducedType *DT = D->getType()->getContainedDeducedType();
13308       if (!DT || DT->getDeducedType().isNull())
13309         continue;
13310       if (Deduced.isNull()) {
13311         Deduced = DT->getDeducedType();
13312         DeducedDecl = D;
13313       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13314         auto *AT = dyn_cast<AutoType>(DT);
13315         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13316                         diag::err_auto_different_deductions)
13317                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13318                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13319                    << D->getDeclName();
13320         if (DeducedDecl->hasInit())
13321           Dia << DeducedDecl->getInit()->getSourceRange();
13322         if (D->getInit())
13323           Dia << D->getInit()->getSourceRange();
13324         D->setInvalidDecl();
13325         break;
13326       }
13327     }
13328   }
13329 
13330   ActOnDocumentableDecls(Group);
13331 
13332   return DeclGroupPtrTy::make(
13333       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13334 }
13335 
13336 void Sema::ActOnDocumentableDecl(Decl *D) {
13337   ActOnDocumentableDecls(D);
13338 }
13339 
13340 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13341   // Don't parse the comment if Doxygen diagnostics are ignored.
13342   if (Group.empty() || !Group[0])
13343     return;
13344 
13345   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13346                       Group[0]->getLocation()) &&
13347       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13348                       Group[0]->getLocation()))
13349     return;
13350 
13351   if (Group.size() >= 2) {
13352     // This is a decl group.  Normally it will contain only declarations
13353     // produced from declarator list.  But in case we have any definitions or
13354     // additional declaration references:
13355     //   'typedef struct S {} S;'
13356     //   'typedef struct S *S;'
13357     //   'struct S *pS;'
13358     // FinalizeDeclaratorGroup adds these as separate declarations.
13359     Decl *MaybeTagDecl = Group[0];
13360     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13361       Group = Group.slice(1);
13362     }
13363   }
13364 
13365   // FIMXE: We assume every Decl in the group is in the same file.
13366   // This is false when preprocessor constructs the group from decls in
13367   // different files (e. g. macros or #include).
13368   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13369 }
13370 
13371 /// Common checks for a parameter-declaration that should apply to both function
13372 /// parameters and non-type template parameters.
13373 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13374   // Check that there are no default arguments inside the type of this
13375   // parameter.
13376   if (getLangOpts().CPlusPlus)
13377     CheckExtraCXXDefaultArguments(D);
13378 
13379   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13380   if (D.getCXXScopeSpec().isSet()) {
13381     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13382       << D.getCXXScopeSpec().getRange();
13383   }
13384 
13385   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13386   // simple identifier except [...irrelevant cases...].
13387   switch (D.getName().getKind()) {
13388   case UnqualifiedIdKind::IK_Identifier:
13389     break;
13390 
13391   case UnqualifiedIdKind::IK_OperatorFunctionId:
13392   case UnqualifiedIdKind::IK_ConversionFunctionId:
13393   case UnqualifiedIdKind::IK_LiteralOperatorId:
13394   case UnqualifiedIdKind::IK_ConstructorName:
13395   case UnqualifiedIdKind::IK_DestructorName:
13396   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13397   case UnqualifiedIdKind::IK_DeductionGuideName:
13398     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13399       << GetNameForDeclarator(D).getName();
13400     break;
13401 
13402   case UnqualifiedIdKind::IK_TemplateId:
13403   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13404     // GetNameForDeclarator would not produce a useful name in this case.
13405     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13406     break;
13407   }
13408 }
13409 
13410 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13411 /// to introduce parameters into function prototype scope.
13412 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13413   const DeclSpec &DS = D.getDeclSpec();
13414 
13415   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13416 
13417   // C++03 [dcl.stc]p2 also permits 'auto'.
13418   StorageClass SC = SC_None;
13419   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13420     SC = SC_Register;
13421     // In C++11, the 'register' storage class specifier is deprecated.
13422     // In C++17, it is not allowed, but we tolerate it as an extension.
13423     if (getLangOpts().CPlusPlus11) {
13424       Diag(DS.getStorageClassSpecLoc(),
13425            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13426                                      : diag::warn_deprecated_register)
13427         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13428     }
13429   } else if (getLangOpts().CPlusPlus &&
13430              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13431     SC = SC_Auto;
13432   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13433     Diag(DS.getStorageClassSpecLoc(),
13434          diag::err_invalid_storage_class_in_func_decl);
13435     D.getMutableDeclSpec().ClearStorageClassSpecs();
13436   }
13437 
13438   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13439     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13440       << DeclSpec::getSpecifierName(TSCS);
13441   if (DS.isInlineSpecified())
13442     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13443         << getLangOpts().CPlusPlus17;
13444   if (DS.hasConstexprSpecifier())
13445     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13446         << 0 << D.getDeclSpec().getConstexprSpecifier();
13447 
13448   DiagnoseFunctionSpecifiers(DS);
13449 
13450   CheckFunctionOrTemplateParamDeclarator(S, D);
13451 
13452   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13453   QualType parmDeclType = TInfo->getType();
13454 
13455   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13456   IdentifierInfo *II = D.getIdentifier();
13457   if (II) {
13458     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13459                    ForVisibleRedeclaration);
13460     LookupName(R, S);
13461     if (R.isSingleResult()) {
13462       NamedDecl *PrevDecl = R.getFoundDecl();
13463       if (PrevDecl->isTemplateParameter()) {
13464         // Maybe we will complain about the shadowed template parameter.
13465         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13466         // Just pretend that we didn't see the previous declaration.
13467         PrevDecl = nullptr;
13468       } else if (S->isDeclScope(PrevDecl)) {
13469         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13470         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13471 
13472         // Recover by removing the name
13473         II = nullptr;
13474         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13475         D.setInvalidType(true);
13476       }
13477     }
13478   }
13479 
13480   // Temporarily put parameter variables in the translation unit, not
13481   // the enclosing context.  This prevents them from accidentally
13482   // looking like class members in C++.
13483   ParmVarDecl *New =
13484       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13485                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13486 
13487   if (D.isInvalidType())
13488     New->setInvalidDecl();
13489 
13490   assert(S->isFunctionPrototypeScope());
13491   assert(S->getFunctionPrototypeDepth() >= 1);
13492   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13493                     S->getNextFunctionPrototypeIndex());
13494 
13495   // Add the parameter declaration into this scope.
13496   S->AddDecl(New);
13497   if (II)
13498     IdResolver.AddDecl(New);
13499 
13500   ProcessDeclAttributes(S, New, D);
13501 
13502   if (D.getDeclSpec().isModulePrivateSpecified())
13503     Diag(New->getLocation(), diag::err_module_private_local)
13504         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13505         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13506 
13507   if (New->hasAttr<BlocksAttr>()) {
13508     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13509   }
13510 
13511   if (getLangOpts().OpenCL)
13512     deduceOpenCLAddressSpace(New);
13513 
13514   return New;
13515 }
13516 
13517 /// Synthesizes a variable for a parameter arising from a
13518 /// typedef.
13519 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13520                                               SourceLocation Loc,
13521                                               QualType T) {
13522   /* FIXME: setting StartLoc == Loc.
13523      Would it be worth to modify callers so as to provide proper source
13524      location for the unnamed parameters, embedding the parameter's type? */
13525   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13526                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13527                                            SC_None, nullptr);
13528   Param->setImplicit();
13529   return Param;
13530 }
13531 
13532 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13533   // Don't diagnose unused-parameter errors in template instantiations; we
13534   // will already have done so in the template itself.
13535   if (inTemplateInstantiation())
13536     return;
13537 
13538   for (const ParmVarDecl *Parameter : Parameters) {
13539     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13540         !Parameter->hasAttr<UnusedAttr>()) {
13541       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13542         << Parameter->getDeclName();
13543     }
13544   }
13545 }
13546 
13547 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13548     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13549   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13550     return;
13551 
13552   // Warn if the return value is pass-by-value and larger than the specified
13553   // threshold.
13554   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13555     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13556     if (Size > LangOpts.NumLargeByValueCopy)
13557       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13558   }
13559 
13560   // Warn if any parameter is pass-by-value and larger than the specified
13561   // threshold.
13562   for (const ParmVarDecl *Parameter : Parameters) {
13563     QualType T = Parameter->getType();
13564     if (T->isDependentType() || !T.isPODType(Context))
13565       continue;
13566     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13567     if (Size > LangOpts.NumLargeByValueCopy)
13568       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13569           << Parameter << Size;
13570   }
13571 }
13572 
13573 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13574                                   SourceLocation NameLoc, IdentifierInfo *Name,
13575                                   QualType T, TypeSourceInfo *TSInfo,
13576                                   StorageClass SC) {
13577   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13578   if (getLangOpts().ObjCAutoRefCount &&
13579       T.getObjCLifetime() == Qualifiers::OCL_None &&
13580       T->isObjCLifetimeType()) {
13581 
13582     Qualifiers::ObjCLifetime lifetime;
13583 
13584     // Special cases for arrays:
13585     //   - if it's const, use __unsafe_unretained
13586     //   - otherwise, it's an error
13587     if (T->isArrayType()) {
13588       if (!T.isConstQualified()) {
13589         if (DelayedDiagnostics.shouldDelayDiagnostics())
13590           DelayedDiagnostics.add(
13591               sema::DelayedDiagnostic::makeForbiddenType(
13592               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13593         else
13594           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13595               << TSInfo->getTypeLoc().getSourceRange();
13596       }
13597       lifetime = Qualifiers::OCL_ExplicitNone;
13598     } else {
13599       lifetime = T->getObjCARCImplicitLifetime();
13600     }
13601     T = Context.getLifetimeQualifiedType(T, lifetime);
13602   }
13603 
13604   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13605                                          Context.getAdjustedParameterType(T),
13606                                          TSInfo, SC, nullptr);
13607 
13608   // Make a note if we created a new pack in the scope of a lambda, so that
13609   // we know that references to that pack must also be expanded within the
13610   // lambda scope.
13611   if (New->isParameterPack())
13612     if (auto *LSI = getEnclosingLambda())
13613       LSI->LocalPacks.push_back(New);
13614 
13615   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13616       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13617     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13618                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13619 
13620   // Parameters can not be abstract class types.
13621   // For record types, this is done by the AbstractClassUsageDiagnoser once
13622   // the class has been completely parsed.
13623   if (!CurContext->isRecord() &&
13624       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13625                              AbstractParamType))
13626     New->setInvalidDecl();
13627 
13628   // Parameter declarators cannot be interface types. All ObjC objects are
13629   // passed by reference.
13630   if (T->isObjCObjectType()) {
13631     SourceLocation TypeEndLoc =
13632         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13633     Diag(NameLoc,
13634          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13635       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13636     T = Context.getObjCObjectPointerType(T);
13637     New->setType(T);
13638   }
13639 
13640   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13641   // duration shall not be qualified by an address-space qualifier."
13642   // Since all parameters have automatic store duration, they can not have
13643   // an address space.
13644   if (T.getAddressSpace() != LangAS::Default &&
13645       // OpenCL allows function arguments declared to be an array of a type
13646       // to be qualified with an address space.
13647       !(getLangOpts().OpenCL &&
13648         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13649     Diag(NameLoc, diag::err_arg_with_address_space);
13650     New->setInvalidDecl();
13651   }
13652 
13653   return New;
13654 }
13655 
13656 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13657                                            SourceLocation LocAfterDecls) {
13658   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13659 
13660   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13661   // for a K&R function.
13662   if (!FTI.hasPrototype) {
13663     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13664       --i;
13665       if (FTI.Params[i].Param == nullptr) {
13666         SmallString<256> Code;
13667         llvm::raw_svector_ostream(Code)
13668             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13669         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13670             << FTI.Params[i].Ident
13671             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13672 
13673         // Implicitly declare the argument as type 'int' for lack of a better
13674         // type.
13675         AttributeFactory attrs;
13676         DeclSpec DS(attrs);
13677         const char* PrevSpec; // unused
13678         unsigned DiagID; // unused
13679         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13680                            DiagID, Context.getPrintingPolicy());
13681         // Use the identifier location for the type source range.
13682         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13683         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13684         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13685         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13686         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13687       }
13688     }
13689   }
13690 }
13691 
13692 Decl *
13693 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13694                               MultiTemplateParamsArg TemplateParameterLists,
13695                               SkipBodyInfo *SkipBody) {
13696   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13697   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13698   Scope *ParentScope = FnBodyScope->getParent();
13699 
13700   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13701   // we define a non-templated function definition, we will create a declaration
13702   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13703   // The base function declaration will have the equivalent of an `omp declare
13704   // variant` annotation which specifies the mangled definition as a
13705   // specialization function under the OpenMP context defined as part of the
13706   // `omp begin declare variant`.
13707   FunctionDecl *BaseFD = nullptr;
13708   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13709       TemplateParameterLists.empty())
13710     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13711         ParentScope, D);
13712 
13713   D.setFunctionDefinitionKind(FDK_Definition);
13714   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13715   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13716 
13717   if (BaseFD)
13718     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13719         cast<FunctionDecl>(Dcl), BaseFD);
13720 
13721   return Dcl;
13722 }
13723 
13724 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13725   Consumer.HandleInlineFunctionDefinition(D);
13726 }
13727 
13728 static bool
13729 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13730                                 const FunctionDecl *&PossiblePrototype) {
13731   // Don't warn about invalid declarations.
13732   if (FD->isInvalidDecl())
13733     return false;
13734 
13735   // Or declarations that aren't global.
13736   if (!FD->isGlobal())
13737     return false;
13738 
13739   // Don't warn about C++ member functions.
13740   if (isa<CXXMethodDecl>(FD))
13741     return false;
13742 
13743   // Don't warn about 'main'.
13744   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13745     if (IdentifierInfo *II = FD->getIdentifier())
13746       if (II->isStr("main"))
13747         return false;
13748 
13749   // Don't warn about inline functions.
13750   if (FD->isInlined())
13751     return false;
13752 
13753   // Don't warn about function templates.
13754   if (FD->getDescribedFunctionTemplate())
13755     return false;
13756 
13757   // Don't warn about function template specializations.
13758   if (FD->isFunctionTemplateSpecialization())
13759     return false;
13760 
13761   // Don't warn for OpenCL kernels.
13762   if (FD->hasAttr<OpenCLKernelAttr>())
13763     return false;
13764 
13765   // Don't warn on explicitly deleted functions.
13766   if (FD->isDeleted())
13767     return false;
13768 
13769   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13770        Prev; Prev = Prev->getPreviousDecl()) {
13771     // Ignore any declarations that occur in function or method
13772     // scope, because they aren't visible from the header.
13773     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13774       continue;
13775 
13776     PossiblePrototype = Prev;
13777     return Prev->getType()->isFunctionNoProtoType();
13778   }
13779 
13780   return true;
13781 }
13782 
13783 void
13784 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13785                                    const FunctionDecl *EffectiveDefinition,
13786                                    SkipBodyInfo *SkipBody) {
13787   const FunctionDecl *Definition = EffectiveDefinition;
13788   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13789     // If this is a friend function defined in a class template, it does not
13790     // have a body until it is used, nevertheless it is a definition, see
13791     // [temp.inst]p2:
13792     //
13793     // ... for the purpose of determining whether an instantiated redeclaration
13794     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13795     // corresponds to a definition in the template is considered to be a
13796     // definition.
13797     //
13798     // The following code must produce redefinition error:
13799     //
13800     //     template<typename T> struct C20 { friend void func_20() {} };
13801     //     C20<int> c20i;
13802     //     void func_20() {}
13803     //
13804     for (auto I : FD->redecls()) {
13805       if (I != FD && !I->isInvalidDecl() &&
13806           I->getFriendObjectKind() != Decl::FOK_None) {
13807         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13808           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13809             // A merged copy of the same function, instantiated as a member of
13810             // the same class, is OK.
13811             if (declaresSameEntity(OrigFD, Original) &&
13812                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13813                                    cast<Decl>(FD->getLexicalDeclContext())))
13814               continue;
13815           }
13816 
13817           if (Original->isThisDeclarationADefinition()) {
13818             Definition = I;
13819             break;
13820           }
13821         }
13822       }
13823     }
13824   }
13825 
13826   if (!Definition)
13827     // Similar to friend functions a friend function template may be a
13828     // definition and do not have a body if it is instantiated in a class
13829     // template.
13830     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13831       for (auto I : FTD->redecls()) {
13832         auto D = cast<FunctionTemplateDecl>(I);
13833         if (D != FTD) {
13834           assert(!D->isThisDeclarationADefinition() &&
13835                  "More than one definition in redeclaration chain");
13836           if (D->getFriendObjectKind() != Decl::FOK_None)
13837             if (FunctionTemplateDecl *FT =
13838                                        D->getInstantiatedFromMemberTemplate()) {
13839               if (FT->isThisDeclarationADefinition()) {
13840                 Definition = D->getTemplatedDecl();
13841                 break;
13842               }
13843             }
13844         }
13845       }
13846     }
13847 
13848   if (!Definition)
13849     return;
13850 
13851   if (canRedefineFunction(Definition, getLangOpts()))
13852     return;
13853 
13854   // Don't emit an error when this is redefinition of a typo-corrected
13855   // definition.
13856   if (TypoCorrectedFunctionDefinitions.count(Definition))
13857     return;
13858 
13859   // If we don't have a visible definition of the function, and it's inline or
13860   // a template, skip the new definition.
13861   if (SkipBody && !hasVisibleDefinition(Definition) &&
13862       (Definition->getFormalLinkage() == InternalLinkage ||
13863        Definition->isInlined() ||
13864        Definition->getDescribedFunctionTemplate() ||
13865        Definition->getNumTemplateParameterLists())) {
13866     SkipBody->ShouldSkip = true;
13867     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13868     if (auto *TD = Definition->getDescribedFunctionTemplate())
13869       makeMergedDefinitionVisible(TD);
13870     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13871     return;
13872   }
13873 
13874   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13875       Definition->getStorageClass() == SC_Extern)
13876     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13877         << FD << getLangOpts().CPlusPlus;
13878   else
13879     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13880 
13881   Diag(Definition->getLocation(), diag::note_previous_definition);
13882   FD->setInvalidDecl();
13883 }
13884 
13885 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13886                                    Sema &S) {
13887   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13888 
13889   LambdaScopeInfo *LSI = S.PushLambdaScope();
13890   LSI->CallOperator = CallOperator;
13891   LSI->Lambda = LambdaClass;
13892   LSI->ReturnType = CallOperator->getReturnType();
13893   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13894 
13895   if (LCD == LCD_None)
13896     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13897   else if (LCD == LCD_ByCopy)
13898     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13899   else if (LCD == LCD_ByRef)
13900     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13901   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13902 
13903   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13904   LSI->Mutable = !CallOperator->isConst();
13905 
13906   // Add the captures to the LSI so they can be noted as already
13907   // captured within tryCaptureVar.
13908   auto I = LambdaClass->field_begin();
13909   for (const auto &C : LambdaClass->captures()) {
13910     if (C.capturesVariable()) {
13911       VarDecl *VD = C.getCapturedVar();
13912       if (VD->isInitCapture())
13913         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13914       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13915       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13916           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13917           /*EllipsisLoc*/C.isPackExpansion()
13918                          ? C.getEllipsisLoc() : SourceLocation(),
13919           I->getType(), /*Invalid*/false);
13920 
13921     } else if (C.capturesThis()) {
13922       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13923                           C.getCaptureKind() == LCK_StarThis);
13924     } else {
13925       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13926                              I->getType());
13927     }
13928     ++I;
13929   }
13930 }
13931 
13932 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13933                                     SkipBodyInfo *SkipBody) {
13934   if (!D) {
13935     // Parsing the function declaration failed in some way. Push on a fake scope
13936     // anyway so we can try to parse the function body.
13937     PushFunctionScope();
13938     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13939     return D;
13940   }
13941 
13942   FunctionDecl *FD = nullptr;
13943 
13944   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13945     FD = FunTmpl->getTemplatedDecl();
13946   else
13947     FD = cast<FunctionDecl>(D);
13948 
13949   // Do not push if it is a lambda because one is already pushed when building
13950   // the lambda in ActOnStartOfLambdaDefinition().
13951   if (!isLambdaCallOperator(FD))
13952     PushExpressionEvaluationContext(
13953         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13954                           : ExprEvalContexts.back().Context);
13955 
13956   // Check for defining attributes before the check for redefinition.
13957   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13958     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13959     FD->dropAttr<AliasAttr>();
13960     FD->setInvalidDecl();
13961   }
13962   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13963     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13964     FD->dropAttr<IFuncAttr>();
13965     FD->setInvalidDecl();
13966   }
13967 
13968   // See if this is a redefinition. If 'will have body' is already set, then
13969   // these checks were already performed when it was set.
13970   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13971     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13972 
13973     // If we're skipping the body, we're done. Don't enter the scope.
13974     if (SkipBody && SkipBody->ShouldSkip)
13975       return D;
13976   }
13977 
13978   // Mark this function as "will have a body eventually".  This lets users to
13979   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13980   // this function.
13981   FD->setWillHaveBody();
13982 
13983   // If we are instantiating a generic lambda call operator, push
13984   // a LambdaScopeInfo onto the function stack.  But use the information
13985   // that's already been calculated (ActOnLambdaExpr) to prime the current
13986   // LambdaScopeInfo.
13987   // When the template operator is being specialized, the LambdaScopeInfo,
13988   // has to be properly restored so that tryCaptureVariable doesn't try
13989   // and capture any new variables. In addition when calculating potential
13990   // captures during transformation of nested lambdas, it is necessary to
13991   // have the LSI properly restored.
13992   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13993     assert(inTemplateInstantiation() &&
13994            "There should be an active template instantiation on the stack "
13995            "when instantiating a generic lambda!");
13996     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13997   } else {
13998     // Enter a new function scope
13999     PushFunctionScope();
14000   }
14001 
14002   // Builtin functions cannot be defined.
14003   if (unsigned BuiltinID = FD->getBuiltinID()) {
14004     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14005         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14006       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14007       FD->setInvalidDecl();
14008     }
14009   }
14010 
14011   // The return type of a function definition must be complete
14012   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14013   QualType ResultType = FD->getReturnType();
14014   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14015       !FD->isInvalidDecl() &&
14016       RequireCompleteType(FD->getLocation(), ResultType,
14017                           diag::err_func_def_incomplete_result))
14018     FD->setInvalidDecl();
14019 
14020   if (FnBodyScope)
14021     PushDeclContext(FnBodyScope, FD);
14022 
14023   // Check the validity of our function parameters
14024   CheckParmsForFunctionDef(FD->parameters(),
14025                            /*CheckParameterNames=*/true);
14026 
14027   // Add non-parameter declarations already in the function to the current
14028   // scope.
14029   if (FnBodyScope) {
14030     for (Decl *NPD : FD->decls()) {
14031       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14032       if (!NonParmDecl)
14033         continue;
14034       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14035              "parameters should not be in newly created FD yet");
14036 
14037       // If the decl has a name, make it accessible in the current scope.
14038       if (NonParmDecl->getDeclName())
14039         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14040 
14041       // Similarly, dive into enums and fish their constants out, making them
14042       // accessible in this scope.
14043       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14044         for (auto *EI : ED->enumerators())
14045           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14046       }
14047     }
14048   }
14049 
14050   // Introduce our parameters into the function scope
14051   for (auto Param : FD->parameters()) {
14052     Param->setOwningFunction(FD);
14053 
14054     // If this has an identifier, add it to the scope stack.
14055     if (Param->getIdentifier() && FnBodyScope) {
14056       CheckShadow(FnBodyScope, Param);
14057 
14058       PushOnScopeChains(Param, FnBodyScope);
14059     }
14060   }
14061 
14062   // Ensure that the function's exception specification is instantiated.
14063   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14064     ResolveExceptionSpec(D->getLocation(), FPT);
14065 
14066   // dllimport cannot be applied to non-inline function definitions.
14067   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14068       !FD->isTemplateInstantiation()) {
14069     assert(!FD->hasAttr<DLLExportAttr>());
14070     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14071     FD->setInvalidDecl();
14072     return D;
14073   }
14074   // We want to attach documentation to original Decl (which might be
14075   // a function template).
14076   ActOnDocumentableDecl(D);
14077   if (getCurLexicalContext()->isObjCContainer() &&
14078       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14079       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14080     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14081 
14082   return D;
14083 }
14084 
14085 /// Given the set of return statements within a function body,
14086 /// compute the variables that are subject to the named return value
14087 /// optimization.
14088 ///
14089 /// Each of the variables that is subject to the named return value
14090 /// optimization will be marked as NRVO variables in the AST, and any
14091 /// return statement that has a marked NRVO variable as its NRVO candidate can
14092 /// use the named return value optimization.
14093 ///
14094 /// This function applies a very simplistic algorithm for NRVO: if every return
14095 /// statement in the scope of a variable has the same NRVO candidate, that
14096 /// candidate is an NRVO variable.
14097 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14098   ReturnStmt **Returns = Scope->Returns.data();
14099 
14100   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14101     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14102       if (!NRVOCandidate->isNRVOVariable())
14103         Returns[I]->setNRVOCandidate(nullptr);
14104     }
14105   }
14106 }
14107 
14108 bool Sema::canDelayFunctionBody(const Declarator &D) {
14109   // We can't delay parsing the body of a constexpr function template (yet).
14110   if (D.getDeclSpec().hasConstexprSpecifier())
14111     return false;
14112 
14113   // We can't delay parsing the body of a function template with a deduced
14114   // return type (yet).
14115   if (D.getDeclSpec().hasAutoTypeSpec()) {
14116     // If the placeholder introduces a non-deduced trailing return type,
14117     // we can still delay parsing it.
14118     if (D.getNumTypeObjects()) {
14119       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14120       if (Outer.Kind == DeclaratorChunk::Function &&
14121           Outer.Fun.hasTrailingReturnType()) {
14122         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14123         return Ty.isNull() || !Ty->isUndeducedType();
14124       }
14125     }
14126     return false;
14127   }
14128 
14129   return true;
14130 }
14131 
14132 bool Sema::canSkipFunctionBody(Decl *D) {
14133   // We cannot skip the body of a function (or function template) which is
14134   // constexpr, since we may need to evaluate its body in order to parse the
14135   // rest of the file.
14136   // We cannot skip the body of a function with an undeduced return type,
14137   // because any callers of that function need to know the type.
14138   if (const FunctionDecl *FD = D->getAsFunction()) {
14139     if (FD->isConstexpr())
14140       return false;
14141     // We can't simply call Type::isUndeducedType here, because inside template
14142     // auto can be deduced to a dependent type, which is not considered
14143     // "undeduced".
14144     if (FD->getReturnType()->getContainedDeducedType())
14145       return false;
14146   }
14147   return Consumer.shouldSkipFunctionBody(D);
14148 }
14149 
14150 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14151   if (!Decl)
14152     return nullptr;
14153   if (FunctionDecl *FD = Decl->getAsFunction())
14154     FD->setHasSkippedBody();
14155   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14156     MD->setHasSkippedBody();
14157   return Decl;
14158 }
14159 
14160 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14161   return ActOnFinishFunctionBody(D, BodyArg, false);
14162 }
14163 
14164 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14165 /// body.
14166 class ExitFunctionBodyRAII {
14167 public:
14168   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14169   ~ExitFunctionBodyRAII() {
14170     if (!IsLambda)
14171       S.PopExpressionEvaluationContext();
14172   }
14173 
14174 private:
14175   Sema &S;
14176   bool IsLambda = false;
14177 };
14178 
14179 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14180   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14181 
14182   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14183     if (EscapeInfo.count(BD))
14184       return EscapeInfo[BD];
14185 
14186     bool R = false;
14187     const BlockDecl *CurBD = BD;
14188 
14189     do {
14190       R = !CurBD->doesNotEscape();
14191       if (R)
14192         break;
14193       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14194     } while (CurBD);
14195 
14196     return EscapeInfo[BD] = R;
14197   };
14198 
14199   // If the location where 'self' is implicitly retained is inside a escaping
14200   // block, emit a diagnostic.
14201   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14202        S.ImplicitlyRetainedSelfLocs)
14203     if (IsOrNestedInEscapingBlock(P.second))
14204       S.Diag(P.first, diag::warn_implicitly_retains_self)
14205           << FixItHint::CreateInsertion(P.first, "self->");
14206 }
14207 
14208 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14209                                     bool IsInstantiation) {
14210   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14211 
14212   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14213   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14214 
14215   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14216     CheckCompletedCoroutineBody(FD, Body);
14217 
14218   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14219   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14220   // meant to pop the context added in ActOnStartOfFunctionDef().
14221   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14222 
14223   if (FD) {
14224     FD->setBody(Body);
14225     FD->setWillHaveBody(false);
14226 
14227     if (getLangOpts().CPlusPlus14) {
14228       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14229           FD->getReturnType()->isUndeducedType()) {
14230         // If the function has a deduced result type but contains no 'return'
14231         // statements, the result type as written must be exactly 'auto', and
14232         // the deduced result type is 'void'.
14233         if (!FD->getReturnType()->getAs<AutoType>()) {
14234           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14235               << FD->getReturnType();
14236           FD->setInvalidDecl();
14237         } else {
14238           // Substitute 'void' for the 'auto' in the type.
14239           TypeLoc ResultType = getReturnTypeLoc(FD);
14240           Context.adjustDeducedFunctionResultType(
14241               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14242         }
14243       }
14244     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14245       // In C++11, we don't use 'auto' deduction rules for lambda call
14246       // operators because we don't support return type deduction.
14247       auto *LSI = getCurLambda();
14248       if (LSI->HasImplicitReturnType) {
14249         deduceClosureReturnType(*LSI);
14250 
14251         // C++11 [expr.prim.lambda]p4:
14252         //   [...] if there are no return statements in the compound-statement
14253         //   [the deduced type is] the type void
14254         QualType RetType =
14255             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14256 
14257         // Update the return type to the deduced type.
14258         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14259         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14260                                             Proto->getExtProtoInfo()));
14261       }
14262     }
14263 
14264     // If the function implicitly returns zero (like 'main') or is naked,
14265     // don't complain about missing return statements.
14266     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14267       WP.disableCheckFallThrough();
14268 
14269     // MSVC permits the use of pure specifier (=0) on function definition,
14270     // defined at class scope, warn about this non-standard construct.
14271     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14272       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14273 
14274     if (!FD->isInvalidDecl()) {
14275       // Don't diagnose unused parameters of defaulted or deleted functions.
14276       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14277         DiagnoseUnusedParameters(FD->parameters());
14278       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14279                                              FD->getReturnType(), FD);
14280 
14281       // If this is a structor, we need a vtable.
14282       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14283         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14284       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14285         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14286 
14287       // Try to apply the named return value optimization. We have to check
14288       // if we can do this here because lambdas keep return statements around
14289       // to deduce an implicit return type.
14290       if (FD->getReturnType()->isRecordType() &&
14291           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14292         computeNRVO(Body, getCurFunction());
14293     }
14294 
14295     // GNU warning -Wmissing-prototypes:
14296     //   Warn if a global function is defined without a previous
14297     //   prototype declaration. This warning is issued even if the
14298     //   definition itself provides a prototype. The aim is to detect
14299     //   global functions that fail to be declared in header files.
14300     const FunctionDecl *PossiblePrototype = nullptr;
14301     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14302       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14303 
14304       if (PossiblePrototype) {
14305         // We found a declaration that is not a prototype,
14306         // but that could be a zero-parameter prototype
14307         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14308           TypeLoc TL = TI->getTypeLoc();
14309           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14310             Diag(PossiblePrototype->getLocation(),
14311                  diag::note_declaration_not_a_prototype)
14312                 << (FD->getNumParams() != 0)
14313                 << (FD->getNumParams() == 0
14314                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14315                         : FixItHint{});
14316         }
14317       } else {
14318         // Returns true if the token beginning at this Loc is `const`.
14319         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14320                                 const LangOptions &LangOpts) {
14321           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14322           if (LocInfo.first.isInvalid())
14323             return false;
14324 
14325           bool Invalid = false;
14326           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14327           if (Invalid)
14328             return false;
14329 
14330           if (LocInfo.second > Buffer.size())
14331             return false;
14332 
14333           const char *LexStart = Buffer.data() + LocInfo.second;
14334           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14335 
14336           return StartTok.consume_front("const") &&
14337                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14338                   StartTok.startswith("/*") || StartTok.startswith("//"));
14339         };
14340 
14341         auto findBeginLoc = [&]() {
14342           // If the return type has `const` qualifier, we want to insert
14343           // `static` before `const` (and not before the typename).
14344           if ((FD->getReturnType()->isAnyPointerType() &&
14345                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14346               FD->getReturnType().isConstQualified()) {
14347             // But only do this if we can determine where the `const` is.
14348 
14349             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14350                              getLangOpts()))
14351 
14352               return FD->getBeginLoc();
14353           }
14354           return FD->getTypeSpecStartLoc();
14355         };
14356         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14357             << /* function */ 1
14358             << (FD->getStorageClass() == SC_None
14359                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14360                     : FixItHint{});
14361       }
14362 
14363       // GNU warning -Wstrict-prototypes
14364       //   Warn if K&R function is defined without a previous declaration.
14365       //   This warning is issued only if the definition itself does not provide
14366       //   a prototype. Only K&R definitions do not provide a prototype.
14367       if (!FD->hasWrittenPrototype()) {
14368         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14369         TypeLoc TL = TI->getTypeLoc();
14370         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14371         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14372       }
14373     }
14374 
14375     // Warn on CPUDispatch with an actual body.
14376     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14377       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14378         if (!CmpndBody->body_empty())
14379           Diag(CmpndBody->body_front()->getBeginLoc(),
14380                diag::warn_dispatch_body_ignored);
14381 
14382     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14383       const CXXMethodDecl *KeyFunction;
14384       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14385           MD->isVirtual() &&
14386           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14387           MD == KeyFunction->getCanonicalDecl()) {
14388         // Update the key-function state if necessary for this ABI.
14389         if (FD->isInlined() &&
14390             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14391           Context.setNonKeyFunction(MD);
14392 
14393           // If the newly-chosen key function is already defined, then we
14394           // need to mark the vtable as used retroactively.
14395           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14396           const FunctionDecl *Definition;
14397           if (KeyFunction && KeyFunction->isDefined(Definition))
14398             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14399         } else {
14400           // We just defined they key function; mark the vtable as used.
14401           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14402         }
14403       }
14404     }
14405 
14406     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14407            "Function parsing confused");
14408   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14409     assert(MD == getCurMethodDecl() && "Method parsing confused");
14410     MD->setBody(Body);
14411     if (!MD->isInvalidDecl()) {
14412       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14413                                              MD->getReturnType(), MD);
14414 
14415       if (Body)
14416         computeNRVO(Body, getCurFunction());
14417     }
14418     if (getCurFunction()->ObjCShouldCallSuper) {
14419       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14420           << MD->getSelector().getAsString();
14421       getCurFunction()->ObjCShouldCallSuper = false;
14422     }
14423     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14424       const ObjCMethodDecl *InitMethod = nullptr;
14425       bool isDesignated =
14426           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14427       assert(isDesignated && InitMethod);
14428       (void)isDesignated;
14429 
14430       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14431         auto IFace = MD->getClassInterface();
14432         if (!IFace)
14433           return false;
14434         auto SuperD = IFace->getSuperClass();
14435         if (!SuperD)
14436           return false;
14437         return SuperD->getIdentifier() ==
14438             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14439       };
14440       // Don't issue this warning for unavailable inits or direct subclasses
14441       // of NSObject.
14442       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14443         Diag(MD->getLocation(),
14444              diag::warn_objc_designated_init_missing_super_call);
14445         Diag(InitMethod->getLocation(),
14446              diag::note_objc_designated_init_marked_here);
14447       }
14448       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14449     }
14450     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14451       // Don't issue this warning for unavaialable inits.
14452       if (!MD->isUnavailable())
14453         Diag(MD->getLocation(),
14454              diag::warn_objc_secondary_init_missing_init_call);
14455       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14456     }
14457 
14458     diagnoseImplicitlyRetainedSelf(*this);
14459   } else {
14460     // Parsing the function declaration failed in some way. Pop the fake scope
14461     // we pushed on.
14462     PopFunctionScopeInfo(ActivePolicy, dcl);
14463     return nullptr;
14464   }
14465 
14466   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14467     DiagnoseUnguardedAvailabilityViolations(dcl);
14468 
14469   assert(!getCurFunction()->ObjCShouldCallSuper &&
14470          "This should only be set for ObjC methods, which should have been "
14471          "handled in the block above.");
14472 
14473   // Verify and clean out per-function state.
14474   if (Body && (!FD || !FD->isDefaulted())) {
14475     // C++ constructors that have function-try-blocks can't have return
14476     // statements in the handlers of that block. (C++ [except.handle]p14)
14477     // Verify this.
14478     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14479       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14480 
14481     // Verify that gotos and switch cases don't jump into scopes illegally.
14482     if (getCurFunction()->NeedsScopeChecking() &&
14483         !PP.isCodeCompletionEnabled())
14484       DiagnoseInvalidJumps(Body);
14485 
14486     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14487       if (!Destructor->getParent()->isDependentType())
14488         CheckDestructor(Destructor);
14489 
14490       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14491                                              Destructor->getParent());
14492     }
14493 
14494     // If any errors have occurred, clear out any temporaries that may have
14495     // been leftover. This ensures that these temporaries won't be picked up for
14496     // deletion in some later function.
14497     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14498         getDiagnostics().getSuppressAllDiagnostics()) {
14499       DiscardCleanupsInEvaluationContext();
14500     }
14501     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14502         !isa<FunctionTemplateDecl>(dcl)) {
14503       // Since the body is valid, issue any analysis-based warnings that are
14504       // enabled.
14505       ActivePolicy = &WP;
14506     }
14507 
14508     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14509         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14510       FD->setInvalidDecl();
14511 
14512     if (FD && FD->hasAttr<NakedAttr>()) {
14513       for (const Stmt *S : Body->children()) {
14514         // Allow local register variables without initializer as they don't
14515         // require prologue.
14516         bool RegisterVariables = false;
14517         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14518           for (const auto *Decl : DS->decls()) {
14519             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14520               RegisterVariables =
14521                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14522               if (!RegisterVariables)
14523                 break;
14524             }
14525           }
14526         }
14527         if (RegisterVariables)
14528           continue;
14529         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14530           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14531           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14532           FD->setInvalidDecl();
14533           break;
14534         }
14535       }
14536     }
14537 
14538     assert(ExprCleanupObjects.size() ==
14539                ExprEvalContexts.back().NumCleanupObjects &&
14540            "Leftover temporaries in function");
14541     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14542     assert(MaybeODRUseExprs.empty() &&
14543            "Leftover expressions for odr-use checking");
14544   }
14545 
14546   if (!IsInstantiation)
14547     PopDeclContext();
14548 
14549   PopFunctionScopeInfo(ActivePolicy, dcl);
14550   // If any errors have occurred, clear out any temporaries that may have
14551   // been leftover. This ensures that these temporaries won't be picked up for
14552   // deletion in some later function.
14553   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14554     DiscardCleanupsInEvaluationContext();
14555   }
14556 
14557   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14558     auto ES = getEmissionStatus(FD);
14559     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14560         ES == Sema::FunctionEmissionStatus::Unknown)
14561       DeclsToCheckForDeferredDiags.push_back(FD);
14562   }
14563 
14564   return dcl;
14565 }
14566 
14567 /// When we finish delayed parsing of an attribute, we must attach it to the
14568 /// relevant Decl.
14569 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14570                                        ParsedAttributes &Attrs) {
14571   // Always attach attributes to the underlying decl.
14572   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14573     D = TD->getTemplatedDecl();
14574   ProcessDeclAttributeList(S, D, Attrs);
14575 
14576   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14577     if (Method->isStatic())
14578       checkThisInStaticMemberFunctionAttributes(Method);
14579 }
14580 
14581 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14582 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14583 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14584                                           IdentifierInfo &II, Scope *S) {
14585   // Find the scope in which the identifier is injected and the corresponding
14586   // DeclContext.
14587   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14588   // In that case, we inject the declaration into the translation unit scope
14589   // instead.
14590   Scope *BlockScope = S;
14591   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14592     BlockScope = BlockScope->getParent();
14593 
14594   Scope *ContextScope = BlockScope;
14595   while (!ContextScope->getEntity())
14596     ContextScope = ContextScope->getParent();
14597   ContextRAII SavedContext(*this, ContextScope->getEntity());
14598 
14599   // Before we produce a declaration for an implicitly defined
14600   // function, see whether there was a locally-scoped declaration of
14601   // this name as a function or variable. If so, use that
14602   // (non-visible) declaration, and complain about it.
14603   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14604   if (ExternCPrev) {
14605     // We still need to inject the function into the enclosing block scope so
14606     // that later (non-call) uses can see it.
14607     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14608 
14609     // C89 footnote 38:
14610     //   If in fact it is not defined as having type "function returning int",
14611     //   the behavior is undefined.
14612     if (!isa<FunctionDecl>(ExternCPrev) ||
14613         !Context.typesAreCompatible(
14614             cast<FunctionDecl>(ExternCPrev)->getType(),
14615             Context.getFunctionNoProtoType(Context.IntTy))) {
14616       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14617           << ExternCPrev << !getLangOpts().C99;
14618       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14619       return ExternCPrev;
14620     }
14621   }
14622 
14623   // Extension in C99.  Legal in C90, but warn about it.
14624   unsigned diag_id;
14625   if (II.getName().startswith("__builtin_"))
14626     diag_id = diag::warn_builtin_unknown;
14627   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14628   else if (getLangOpts().OpenCL)
14629     diag_id = diag::err_opencl_implicit_function_decl;
14630   else if (getLangOpts().C99)
14631     diag_id = diag::ext_implicit_function_decl;
14632   else
14633     diag_id = diag::warn_implicit_function_decl;
14634   Diag(Loc, diag_id) << &II;
14635 
14636   // If we found a prior declaration of this function, don't bother building
14637   // another one. We've already pushed that one into scope, so there's nothing
14638   // more to do.
14639   if (ExternCPrev)
14640     return ExternCPrev;
14641 
14642   // Because typo correction is expensive, only do it if the implicit
14643   // function declaration is going to be treated as an error.
14644   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14645     TypoCorrection Corrected;
14646     DeclFilterCCC<FunctionDecl> CCC{};
14647     if (S && (Corrected =
14648                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14649                               S, nullptr, CCC, CTK_NonError)))
14650       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14651                    /*ErrorRecovery*/false);
14652   }
14653 
14654   // Set a Declarator for the implicit definition: int foo();
14655   const char *Dummy;
14656   AttributeFactory attrFactory;
14657   DeclSpec DS(attrFactory);
14658   unsigned DiagID;
14659   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14660                                   Context.getPrintingPolicy());
14661   (void)Error; // Silence warning.
14662   assert(!Error && "Error setting up implicit decl!");
14663   SourceLocation NoLoc;
14664   Declarator D(DS, DeclaratorContext::BlockContext);
14665   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14666                                              /*IsAmbiguous=*/false,
14667                                              /*LParenLoc=*/NoLoc,
14668                                              /*Params=*/nullptr,
14669                                              /*NumParams=*/0,
14670                                              /*EllipsisLoc=*/NoLoc,
14671                                              /*RParenLoc=*/NoLoc,
14672                                              /*RefQualifierIsLvalueRef=*/true,
14673                                              /*RefQualifierLoc=*/NoLoc,
14674                                              /*MutableLoc=*/NoLoc, EST_None,
14675                                              /*ESpecRange=*/SourceRange(),
14676                                              /*Exceptions=*/nullptr,
14677                                              /*ExceptionRanges=*/nullptr,
14678                                              /*NumExceptions=*/0,
14679                                              /*NoexceptExpr=*/nullptr,
14680                                              /*ExceptionSpecTokens=*/nullptr,
14681                                              /*DeclsInPrototype=*/None, Loc,
14682                                              Loc, D),
14683                 std::move(DS.getAttributes()), SourceLocation());
14684   D.SetIdentifier(&II, Loc);
14685 
14686   // Insert this function into the enclosing block scope.
14687   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14688   FD->setImplicit();
14689 
14690   AddKnownFunctionAttributes(FD);
14691 
14692   return FD;
14693 }
14694 
14695 /// If this function is a C++ replaceable global allocation function
14696 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14697 /// adds any function attributes that we know a priori based on the standard.
14698 ///
14699 /// We need to check for duplicate attributes both here and where user-written
14700 /// attributes are applied to declarations.
14701 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14702     FunctionDecl *FD) {
14703   if (FD->isInvalidDecl())
14704     return;
14705 
14706   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14707       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14708     return;
14709 
14710   Optional<unsigned> AlignmentParam;
14711   bool IsNothrow = false;
14712   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14713     return;
14714 
14715   // C++2a [basic.stc.dynamic.allocation]p4:
14716   //   An allocation function that has a non-throwing exception specification
14717   //   indicates failure by returning a null pointer value. Any other allocation
14718   //   function never returns a null pointer value and indicates failure only by
14719   //   throwing an exception [...]
14720   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14721     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14722 
14723   // C++2a [basic.stc.dynamic.allocation]p2:
14724   //   An allocation function attempts to allocate the requested amount of
14725   //   storage. [...] If the request succeeds, the value returned by a
14726   //   replaceable allocation function is a [...] pointer value p0 different
14727   //   from any previously returned value p1 [...]
14728   //
14729   // However, this particular information is being added in codegen,
14730   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14731 
14732   // C++2a [basic.stc.dynamic.allocation]p2:
14733   //   An allocation function attempts to allocate the requested amount of
14734   //   storage. If it is successful, it returns the address of the start of a
14735   //   block of storage whose length in bytes is at least as large as the
14736   //   requested size.
14737   if (!FD->hasAttr<AllocSizeAttr>()) {
14738     FD->addAttr(AllocSizeAttr::CreateImplicit(
14739         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14740         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14741   }
14742 
14743   // C++2a [basic.stc.dynamic.allocation]p3:
14744   //   For an allocation function [...], the pointer returned on a successful
14745   //   call shall represent the address of storage that is aligned as follows:
14746   //   (3.1) If the allocation function takes an argument of type
14747   //         std​::​align_­val_­t, the storage will have the alignment
14748   //         specified by the value of this argument.
14749   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14750     FD->addAttr(AllocAlignAttr::CreateImplicit(
14751         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14752   }
14753 
14754   // FIXME:
14755   // C++2a [basic.stc.dynamic.allocation]p3:
14756   //   For an allocation function [...], the pointer returned on a successful
14757   //   call shall represent the address of storage that is aligned as follows:
14758   //   (3.2) Otherwise, if the allocation function is named operator new[],
14759   //         the storage is aligned for any object that does not have
14760   //         new-extended alignment ([basic.align]) and is no larger than the
14761   //         requested size.
14762   //   (3.3) Otherwise, the storage is aligned for any object that does not
14763   //         have new-extended alignment and is of the requested size.
14764 }
14765 
14766 /// Adds any function attributes that we know a priori based on
14767 /// the declaration of this function.
14768 ///
14769 /// These attributes can apply both to implicitly-declared builtins
14770 /// (like __builtin___printf_chk) or to library-declared functions
14771 /// like NSLog or printf.
14772 ///
14773 /// We need to check for duplicate attributes both here and where user-written
14774 /// attributes are applied to declarations.
14775 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14776   if (FD->isInvalidDecl())
14777     return;
14778 
14779   // If this is a built-in function, map its builtin attributes to
14780   // actual attributes.
14781   if (unsigned BuiltinID = FD->getBuiltinID()) {
14782     // Handle printf-formatting attributes.
14783     unsigned FormatIdx;
14784     bool HasVAListArg;
14785     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14786       if (!FD->hasAttr<FormatAttr>()) {
14787         const char *fmt = "printf";
14788         unsigned int NumParams = FD->getNumParams();
14789         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14790             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14791           fmt = "NSString";
14792         FD->addAttr(FormatAttr::CreateImplicit(Context,
14793                                                &Context.Idents.get(fmt),
14794                                                FormatIdx+1,
14795                                                HasVAListArg ? 0 : FormatIdx+2,
14796                                                FD->getLocation()));
14797       }
14798     }
14799     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14800                                              HasVAListArg)) {
14801      if (!FD->hasAttr<FormatAttr>())
14802        FD->addAttr(FormatAttr::CreateImplicit(Context,
14803                                               &Context.Idents.get("scanf"),
14804                                               FormatIdx+1,
14805                                               HasVAListArg ? 0 : FormatIdx+2,
14806                                               FD->getLocation()));
14807     }
14808 
14809     // Handle automatically recognized callbacks.
14810     SmallVector<int, 4> Encoding;
14811     if (!FD->hasAttr<CallbackAttr>() &&
14812         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14813       FD->addAttr(CallbackAttr::CreateImplicit(
14814           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14815 
14816     // Mark const if we don't care about errno and that is the only thing
14817     // preventing the function from being const. This allows IRgen to use LLVM
14818     // intrinsics for such functions.
14819     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14820         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14821       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14822 
14823     // We make "fma" on some platforms const because we know it does not set
14824     // errno in those environments even though it could set errno based on the
14825     // C standard.
14826     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14827     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14828         !FD->hasAttr<ConstAttr>()) {
14829       switch (BuiltinID) {
14830       case Builtin::BI__builtin_fma:
14831       case Builtin::BI__builtin_fmaf:
14832       case Builtin::BI__builtin_fmal:
14833       case Builtin::BIfma:
14834       case Builtin::BIfmaf:
14835       case Builtin::BIfmal:
14836         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14837         break;
14838       default:
14839         break;
14840       }
14841     }
14842 
14843     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14844         !FD->hasAttr<ReturnsTwiceAttr>())
14845       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14846                                          FD->getLocation()));
14847     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14848       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14849     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14850       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14851     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14852       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14853     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14854         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14855       // Add the appropriate attribute, depending on the CUDA compilation mode
14856       // and which target the builtin belongs to. For example, during host
14857       // compilation, aux builtins are __device__, while the rest are __host__.
14858       if (getLangOpts().CUDAIsDevice !=
14859           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14860         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14861       else
14862         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14863     }
14864   }
14865 
14866   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14867 
14868   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14869   // throw, add an implicit nothrow attribute to any extern "C" function we come
14870   // across.
14871   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14872       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14873     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14874     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14875       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14876   }
14877 
14878   IdentifierInfo *Name = FD->getIdentifier();
14879   if (!Name)
14880     return;
14881   if ((!getLangOpts().CPlusPlus &&
14882        FD->getDeclContext()->isTranslationUnit()) ||
14883       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14884        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14885        LinkageSpecDecl::lang_c)) {
14886     // Okay: this could be a libc/libm/Objective-C function we know
14887     // about.
14888   } else
14889     return;
14890 
14891   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14892     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14893     // target-specific builtins, perhaps?
14894     if (!FD->hasAttr<FormatAttr>())
14895       FD->addAttr(FormatAttr::CreateImplicit(Context,
14896                                              &Context.Idents.get("printf"), 2,
14897                                              Name->isStr("vasprintf") ? 0 : 3,
14898                                              FD->getLocation()));
14899   }
14900 
14901   if (Name->isStr("__CFStringMakeConstantString")) {
14902     // We already have a __builtin___CFStringMakeConstantString,
14903     // but builds that use -fno-constant-cfstrings don't go through that.
14904     if (!FD->hasAttr<FormatArgAttr>())
14905       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14906                                                 FD->getLocation()));
14907   }
14908 }
14909 
14910 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14911                                     TypeSourceInfo *TInfo) {
14912   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14913   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14914 
14915   if (!TInfo) {
14916     assert(D.isInvalidType() && "no declarator info for valid type");
14917     TInfo = Context.getTrivialTypeSourceInfo(T);
14918   }
14919 
14920   // Scope manipulation handled by caller.
14921   TypedefDecl *NewTD =
14922       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14923                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14924 
14925   // Bail out immediately if we have an invalid declaration.
14926   if (D.isInvalidType()) {
14927     NewTD->setInvalidDecl();
14928     return NewTD;
14929   }
14930 
14931   if (D.getDeclSpec().isModulePrivateSpecified()) {
14932     if (CurContext->isFunctionOrMethod())
14933       Diag(NewTD->getLocation(), diag::err_module_private_local)
14934           << 2 << NewTD
14935           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14936           << FixItHint::CreateRemoval(
14937                  D.getDeclSpec().getModulePrivateSpecLoc());
14938     else
14939       NewTD->setModulePrivate();
14940   }
14941 
14942   // C++ [dcl.typedef]p8:
14943   //   If the typedef declaration defines an unnamed class (or
14944   //   enum), the first typedef-name declared by the declaration
14945   //   to be that class type (or enum type) is used to denote the
14946   //   class type (or enum type) for linkage purposes only.
14947   // We need to check whether the type was declared in the declaration.
14948   switch (D.getDeclSpec().getTypeSpecType()) {
14949   case TST_enum:
14950   case TST_struct:
14951   case TST_interface:
14952   case TST_union:
14953   case TST_class: {
14954     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14955     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14956     break;
14957   }
14958 
14959   default:
14960     break;
14961   }
14962 
14963   return NewTD;
14964 }
14965 
14966 /// Check that this is a valid underlying type for an enum declaration.
14967 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14968   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14969   QualType T = TI->getType();
14970 
14971   if (T->isDependentType())
14972     return false;
14973 
14974   // This doesn't use 'isIntegralType' despite the error message mentioning
14975   // integral type because isIntegralType would also allow enum types in C.
14976   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14977     if (BT->isInteger())
14978       return false;
14979 
14980   if (T->isExtIntType())
14981     return false;
14982 
14983   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14984 }
14985 
14986 /// Check whether this is a valid redeclaration of a previous enumeration.
14987 /// \return true if the redeclaration was invalid.
14988 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14989                                   QualType EnumUnderlyingTy, bool IsFixed,
14990                                   const EnumDecl *Prev) {
14991   if (IsScoped != Prev->isScoped()) {
14992     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14993       << Prev->isScoped();
14994     Diag(Prev->getLocation(), diag::note_previous_declaration);
14995     return true;
14996   }
14997 
14998   if (IsFixed && Prev->isFixed()) {
14999     if (!EnumUnderlyingTy->isDependentType() &&
15000         !Prev->getIntegerType()->isDependentType() &&
15001         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15002                                         Prev->getIntegerType())) {
15003       // TODO: Highlight the underlying type of the redeclaration.
15004       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15005         << EnumUnderlyingTy << Prev->getIntegerType();
15006       Diag(Prev->getLocation(), diag::note_previous_declaration)
15007           << Prev->getIntegerTypeRange();
15008       return true;
15009     }
15010   } else if (IsFixed != Prev->isFixed()) {
15011     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15012       << Prev->isFixed();
15013     Diag(Prev->getLocation(), diag::note_previous_declaration);
15014     return true;
15015   }
15016 
15017   return false;
15018 }
15019 
15020 /// Get diagnostic %select index for tag kind for
15021 /// redeclaration diagnostic message.
15022 /// WARNING: Indexes apply to particular diagnostics only!
15023 ///
15024 /// \returns diagnostic %select index.
15025 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15026   switch (Tag) {
15027   case TTK_Struct: return 0;
15028   case TTK_Interface: return 1;
15029   case TTK_Class:  return 2;
15030   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15031   }
15032 }
15033 
15034 /// Determine if tag kind is a class-key compatible with
15035 /// class for redeclaration (class, struct, or __interface).
15036 ///
15037 /// \returns true iff the tag kind is compatible.
15038 static bool isClassCompatTagKind(TagTypeKind Tag)
15039 {
15040   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15041 }
15042 
15043 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15044                                              TagTypeKind TTK) {
15045   if (isa<TypedefDecl>(PrevDecl))
15046     return NTK_Typedef;
15047   else if (isa<TypeAliasDecl>(PrevDecl))
15048     return NTK_TypeAlias;
15049   else if (isa<ClassTemplateDecl>(PrevDecl))
15050     return NTK_Template;
15051   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15052     return NTK_TypeAliasTemplate;
15053   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15054     return NTK_TemplateTemplateArgument;
15055   switch (TTK) {
15056   case TTK_Struct:
15057   case TTK_Interface:
15058   case TTK_Class:
15059     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15060   case TTK_Union:
15061     return NTK_NonUnion;
15062   case TTK_Enum:
15063     return NTK_NonEnum;
15064   }
15065   llvm_unreachable("invalid TTK");
15066 }
15067 
15068 /// Determine whether a tag with a given kind is acceptable
15069 /// as a redeclaration of the given tag declaration.
15070 ///
15071 /// \returns true if the new tag kind is acceptable, false otherwise.
15072 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15073                                         TagTypeKind NewTag, bool isDefinition,
15074                                         SourceLocation NewTagLoc,
15075                                         const IdentifierInfo *Name) {
15076   // C++ [dcl.type.elab]p3:
15077   //   The class-key or enum keyword present in the
15078   //   elaborated-type-specifier shall agree in kind with the
15079   //   declaration to which the name in the elaborated-type-specifier
15080   //   refers. This rule also applies to the form of
15081   //   elaborated-type-specifier that declares a class-name or
15082   //   friend class since it can be construed as referring to the
15083   //   definition of the class. Thus, in any
15084   //   elaborated-type-specifier, the enum keyword shall be used to
15085   //   refer to an enumeration (7.2), the union class-key shall be
15086   //   used to refer to a union (clause 9), and either the class or
15087   //   struct class-key shall be used to refer to a class (clause 9)
15088   //   declared using the class or struct class-key.
15089   TagTypeKind OldTag = Previous->getTagKind();
15090   if (OldTag != NewTag &&
15091       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15092     return false;
15093 
15094   // Tags are compatible, but we might still want to warn on mismatched tags.
15095   // Non-class tags can't be mismatched at this point.
15096   if (!isClassCompatTagKind(NewTag))
15097     return true;
15098 
15099   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15100   // by our warning analysis. We don't want to warn about mismatches with (eg)
15101   // declarations in system headers that are designed to be specialized, but if
15102   // a user asks us to warn, we should warn if their code contains mismatched
15103   // declarations.
15104   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15105     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15106                                       Loc);
15107   };
15108   if (IsIgnoredLoc(NewTagLoc))
15109     return true;
15110 
15111   auto IsIgnored = [&](const TagDecl *Tag) {
15112     return IsIgnoredLoc(Tag->getLocation());
15113   };
15114   while (IsIgnored(Previous)) {
15115     Previous = Previous->getPreviousDecl();
15116     if (!Previous)
15117       return true;
15118     OldTag = Previous->getTagKind();
15119   }
15120 
15121   bool isTemplate = false;
15122   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15123     isTemplate = Record->getDescribedClassTemplate();
15124 
15125   if (inTemplateInstantiation()) {
15126     if (OldTag != NewTag) {
15127       // In a template instantiation, do not offer fix-its for tag mismatches
15128       // since they usually mess up the template instead of fixing the problem.
15129       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15130         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15131         << getRedeclDiagFromTagKind(OldTag);
15132       // FIXME: Note previous location?
15133     }
15134     return true;
15135   }
15136 
15137   if (isDefinition) {
15138     // On definitions, check all previous tags and issue a fix-it for each
15139     // one that doesn't match the current tag.
15140     if (Previous->getDefinition()) {
15141       // Don't suggest fix-its for redefinitions.
15142       return true;
15143     }
15144 
15145     bool previousMismatch = false;
15146     for (const TagDecl *I : Previous->redecls()) {
15147       if (I->getTagKind() != NewTag) {
15148         // Ignore previous declarations for which the warning was disabled.
15149         if (IsIgnored(I))
15150           continue;
15151 
15152         if (!previousMismatch) {
15153           previousMismatch = true;
15154           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15155             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15156             << getRedeclDiagFromTagKind(I->getTagKind());
15157         }
15158         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15159           << getRedeclDiagFromTagKind(NewTag)
15160           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15161                TypeWithKeyword::getTagTypeKindName(NewTag));
15162       }
15163     }
15164     return true;
15165   }
15166 
15167   // Identify the prevailing tag kind: this is the kind of the definition (if
15168   // there is a non-ignored definition), or otherwise the kind of the prior
15169   // (non-ignored) declaration.
15170   const TagDecl *PrevDef = Previous->getDefinition();
15171   if (PrevDef && IsIgnored(PrevDef))
15172     PrevDef = nullptr;
15173   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15174   if (Redecl->getTagKind() != NewTag) {
15175     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15176       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15177       << getRedeclDiagFromTagKind(OldTag);
15178     Diag(Redecl->getLocation(), diag::note_previous_use);
15179 
15180     // If there is a previous definition, suggest a fix-it.
15181     if (PrevDef) {
15182       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15183         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15184         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15185              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15186     }
15187   }
15188 
15189   return true;
15190 }
15191 
15192 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15193 /// from an outer enclosing namespace or file scope inside a friend declaration.
15194 /// This should provide the commented out code in the following snippet:
15195 ///   namespace N {
15196 ///     struct X;
15197 ///     namespace M {
15198 ///       struct Y { friend struct /*N::*/ X; };
15199 ///     }
15200 ///   }
15201 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15202                                          SourceLocation NameLoc) {
15203   // While the decl is in a namespace, do repeated lookup of that name and see
15204   // if we get the same namespace back.  If we do not, continue until
15205   // translation unit scope, at which point we have a fully qualified NNS.
15206   SmallVector<IdentifierInfo *, 4> Namespaces;
15207   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15208   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15209     // This tag should be declared in a namespace, which can only be enclosed by
15210     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15211     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15212     if (!Namespace || Namespace->isAnonymousNamespace())
15213       return FixItHint();
15214     IdentifierInfo *II = Namespace->getIdentifier();
15215     Namespaces.push_back(II);
15216     NamedDecl *Lookup = SemaRef.LookupSingleName(
15217         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15218     if (Lookup == Namespace)
15219       break;
15220   }
15221 
15222   // Once we have all the namespaces, reverse them to go outermost first, and
15223   // build an NNS.
15224   SmallString<64> Insertion;
15225   llvm::raw_svector_ostream OS(Insertion);
15226   if (DC->isTranslationUnit())
15227     OS << "::";
15228   std::reverse(Namespaces.begin(), Namespaces.end());
15229   for (auto *II : Namespaces)
15230     OS << II->getName() << "::";
15231   return FixItHint::CreateInsertion(NameLoc, Insertion);
15232 }
15233 
15234 /// Determine whether a tag originally declared in context \p OldDC can
15235 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15236 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15237 /// using-declaration).
15238 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15239                                          DeclContext *NewDC) {
15240   OldDC = OldDC->getRedeclContext();
15241   NewDC = NewDC->getRedeclContext();
15242 
15243   if (OldDC->Equals(NewDC))
15244     return true;
15245 
15246   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15247   // encloses the other).
15248   if (S.getLangOpts().MSVCCompat &&
15249       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15250     return true;
15251 
15252   return false;
15253 }
15254 
15255 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15256 /// former case, Name will be non-null.  In the later case, Name will be null.
15257 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15258 /// reference/declaration/definition of a tag.
15259 ///
15260 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15261 /// trailing-type-specifier) other than one in an alias-declaration.
15262 ///
15263 /// \param SkipBody If non-null, will be set to indicate if the caller should
15264 /// skip the definition of this tag and treat it as if it were a declaration.
15265 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15266                      SourceLocation KWLoc, CXXScopeSpec &SS,
15267                      IdentifierInfo *Name, SourceLocation NameLoc,
15268                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15269                      SourceLocation ModulePrivateLoc,
15270                      MultiTemplateParamsArg TemplateParameterLists,
15271                      bool &OwnedDecl, bool &IsDependent,
15272                      SourceLocation ScopedEnumKWLoc,
15273                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15274                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15275                      SkipBodyInfo *SkipBody) {
15276   // If this is not a definition, it must have a name.
15277   IdentifierInfo *OrigName = Name;
15278   assert((Name != nullptr || TUK == TUK_Definition) &&
15279          "Nameless record must be a definition!");
15280   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15281 
15282   OwnedDecl = false;
15283   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15284   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15285 
15286   // FIXME: Check member specializations more carefully.
15287   bool isMemberSpecialization = false;
15288   bool Invalid = false;
15289 
15290   // We only need to do this matching if we have template parameters
15291   // or a scope specifier, which also conveniently avoids this work
15292   // for non-C++ cases.
15293   if (TemplateParameterLists.size() > 0 ||
15294       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15295     if (TemplateParameterList *TemplateParams =
15296             MatchTemplateParametersToScopeSpecifier(
15297                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15298                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15299       if (Kind == TTK_Enum) {
15300         Diag(KWLoc, diag::err_enum_template);
15301         return nullptr;
15302       }
15303 
15304       if (TemplateParams->size() > 0) {
15305         // This is a declaration or definition of a class template (which may
15306         // be a member of another template).
15307 
15308         if (Invalid)
15309           return nullptr;
15310 
15311         OwnedDecl = false;
15312         DeclResult Result = CheckClassTemplate(
15313             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15314             AS, ModulePrivateLoc,
15315             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15316             TemplateParameterLists.data(), SkipBody);
15317         return Result.get();
15318       } else {
15319         // The "template<>" header is extraneous.
15320         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15321           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15322         isMemberSpecialization = true;
15323       }
15324     }
15325 
15326     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15327         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15328       return nullptr;
15329   }
15330 
15331   // Figure out the underlying type if this a enum declaration. We need to do
15332   // this early, because it's needed to detect if this is an incompatible
15333   // redeclaration.
15334   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15335   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15336 
15337   if (Kind == TTK_Enum) {
15338     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15339       // No underlying type explicitly specified, or we failed to parse the
15340       // type, default to int.
15341       EnumUnderlying = Context.IntTy.getTypePtr();
15342     } else if (UnderlyingType.get()) {
15343       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15344       // integral type; any cv-qualification is ignored.
15345       TypeSourceInfo *TI = nullptr;
15346       GetTypeFromParser(UnderlyingType.get(), &TI);
15347       EnumUnderlying = TI;
15348 
15349       if (CheckEnumUnderlyingType(TI))
15350         // Recover by falling back to int.
15351         EnumUnderlying = Context.IntTy.getTypePtr();
15352 
15353       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15354                                           UPPC_FixedUnderlyingType))
15355         EnumUnderlying = Context.IntTy.getTypePtr();
15356 
15357     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15358       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15359       // of 'int'. However, if this is an unfixed forward declaration, don't set
15360       // the underlying type unless the user enables -fms-compatibility. This
15361       // makes unfixed forward declared enums incomplete and is more conforming.
15362       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15363         EnumUnderlying = Context.IntTy.getTypePtr();
15364     }
15365   }
15366 
15367   DeclContext *SearchDC = CurContext;
15368   DeclContext *DC = CurContext;
15369   bool isStdBadAlloc = false;
15370   bool isStdAlignValT = false;
15371 
15372   RedeclarationKind Redecl = forRedeclarationInCurContext();
15373   if (TUK == TUK_Friend || TUK == TUK_Reference)
15374     Redecl = NotForRedeclaration;
15375 
15376   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15377   /// implemented asks for structural equivalence checking, the returned decl
15378   /// here is passed back to the parser, allowing the tag body to be parsed.
15379   auto createTagFromNewDecl = [&]() -> TagDecl * {
15380     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15381     // If there is an identifier, use the location of the identifier as the
15382     // location of the decl, otherwise use the location of the struct/union
15383     // keyword.
15384     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15385     TagDecl *New = nullptr;
15386 
15387     if (Kind == TTK_Enum) {
15388       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15389                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15390       // If this is an undefined enum, bail.
15391       if (TUK != TUK_Definition && !Invalid)
15392         return nullptr;
15393       if (EnumUnderlying) {
15394         EnumDecl *ED = cast<EnumDecl>(New);
15395         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15396           ED->setIntegerTypeSourceInfo(TI);
15397         else
15398           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15399         ED->setPromotionType(ED->getIntegerType());
15400       }
15401     } else { // struct/union
15402       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15403                                nullptr);
15404     }
15405 
15406     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15407       // Add alignment attributes if necessary; these attributes are checked
15408       // when the ASTContext lays out the structure.
15409       //
15410       // It is important for implementing the correct semantics that this
15411       // happen here (in ActOnTag). The #pragma pack stack is
15412       // maintained as a result of parser callbacks which can occur at
15413       // many points during the parsing of a struct declaration (because
15414       // the #pragma tokens are effectively skipped over during the
15415       // parsing of the struct).
15416       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15417         AddAlignmentAttributesForRecord(RD);
15418         AddMsStructLayoutForRecord(RD);
15419       }
15420     }
15421     New->setLexicalDeclContext(CurContext);
15422     return New;
15423   };
15424 
15425   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15426   if (Name && SS.isNotEmpty()) {
15427     // We have a nested-name tag ('struct foo::bar').
15428 
15429     // Check for invalid 'foo::'.
15430     if (SS.isInvalid()) {
15431       Name = nullptr;
15432       goto CreateNewDecl;
15433     }
15434 
15435     // If this is a friend or a reference to a class in a dependent
15436     // context, don't try to make a decl for it.
15437     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15438       DC = computeDeclContext(SS, false);
15439       if (!DC) {
15440         IsDependent = true;
15441         return nullptr;
15442       }
15443     } else {
15444       DC = computeDeclContext(SS, true);
15445       if (!DC) {
15446         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15447           << SS.getRange();
15448         return nullptr;
15449       }
15450     }
15451 
15452     if (RequireCompleteDeclContext(SS, DC))
15453       return nullptr;
15454 
15455     SearchDC = DC;
15456     // Look-up name inside 'foo::'.
15457     LookupQualifiedName(Previous, DC);
15458 
15459     if (Previous.isAmbiguous())
15460       return nullptr;
15461 
15462     if (Previous.empty()) {
15463       // Name lookup did not find anything. However, if the
15464       // nested-name-specifier refers to the current instantiation,
15465       // and that current instantiation has any dependent base
15466       // classes, we might find something at instantiation time: treat
15467       // this as a dependent elaborated-type-specifier.
15468       // But this only makes any sense for reference-like lookups.
15469       if (Previous.wasNotFoundInCurrentInstantiation() &&
15470           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15471         IsDependent = true;
15472         return nullptr;
15473       }
15474 
15475       // A tag 'foo::bar' must already exist.
15476       Diag(NameLoc, diag::err_not_tag_in_scope)
15477         << Kind << Name << DC << SS.getRange();
15478       Name = nullptr;
15479       Invalid = true;
15480       goto CreateNewDecl;
15481     }
15482   } else if (Name) {
15483     // C++14 [class.mem]p14:
15484     //   If T is the name of a class, then each of the following shall have a
15485     //   name different from T:
15486     //    -- every member of class T that is itself a type
15487     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15488         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15489       return nullptr;
15490 
15491     // If this is a named struct, check to see if there was a previous forward
15492     // declaration or definition.
15493     // FIXME: We're looking into outer scopes here, even when we
15494     // shouldn't be. Doing so can result in ambiguities that we
15495     // shouldn't be diagnosing.
15496     LookupName(Previous, S);
15497 
15498     // When declaring or defining a tag, ignore ambiguities introduced
15499     // by types using'ed into this scope.
15500     if (Previous.isAmbiguous() &&
15501         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15502       LookupResult::Filter F = Previous.makeFilter();
15503       while (F.hasNext()) {
15504         NamedDecl *ND = F.next();
15505         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15506                 SearchDC->getRedeclContext()))
15507           F.erase();
15508       }
15509       F.done();
15510     }
15511 
15512     // C++11 [namespace.memdef]p3:
15513     //   If the name in a friend declaration is neither qualified nor
15514     //   a template-id and the declaration is a function or an
15515     //   elaborated-type-specifier, the lookup to determine whether
15516     //   the entity has been previously declared shall not consider
15517     //   any scopes outside the innermost enclosing namespace.
15518     //
15519     // MSVC doesn't implement the above rule for types, so a friend tag
15520     // declaration may be a redeclaration of a type declared in an enclosing
15521     // scope.  They do implement this rule for friend functions.
15522     //
15523     // Does it matter that this should be by scope instead of by
15524     // semantic context?
15525     if (!Previous.empty() && TUK == TUK_Friend) {
15526       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15527       LookupResult::Filter F = Previous.makeFilter();
15528       bool FriendSawTagOutsideEnclosingNamespace = false;
15529       while (F.hasNext()) {
15530         NamedDecl *ND = F.next();
15531         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15532         if (DC->isFileContext() &&
15533             !EnclosingNS->Encloses(ND->getDeclContext())) {
15534           if (getLangOpts().MSVCCompat)
15535             FriendSawTagOutsideEnclosingNamespace = true;
15536           else
15537             F.erase();
15538         }
15539       }
15540       F.done();
15541 
15542       // Diagnose this MSVC extension in the easy case where lookup would have
15543       // unambiguously found something outside the enclosing namespace.
15544       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15545         NamedDecl *ND = Previous.getFoundDecl();
15546         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15547             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15548       }
15549     }
15550 
15551     // Note:  there used to be some attempt at recovery here.
15552     if (Previous.isAmbiguous())
15553       return nullptr;
15554 
15555     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15556       // FIXME: This makes sure that we ignore the contexts associated
15557       // with C structs, unions, and enums when looking for a matching
15558       // tag declaration or definition. See the similar lookup tweak
15559       // in Sema::LookupName; is there a better way to deal with this?
15560       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15561         SearchDC = SearchDC->getParent();
15562     }
15563   }
15564 
15565   if (Previous.isSingleResult() &&
15566       Previous.getFoundDecl()->isTemplateParameter()) {
15567     // Maybe we will complain about the shadowed template parameter.
15568     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15569     // Just pretend that we didn't see the previous declaration.
15570     Previous.clear();
15571   }
15572 
15573   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15574       DC->Equals(getStdNamespace())) {
15575     if (Name->isStr("bad_alloc")) {
15576       // This is a declaration of or a reference to "std::bad_alloc".
15577       isStdBadAlloc = true;
15578 
15579       // If std::bad_alloc has been implicitly declared (but made invisible to
15580       // name lookup), fill in this implicit declaration as the previous
15581       // declaration, so that the declarations get chained appropriately.
15582       if (Previous.empty() && StdBadAlloc)
15583         Previous.addDecl(getStdBadAlloc());
15584     } else if (Name->isStr("align_val_t")) {
15585       isStdAlignValT = true;
15586       if (Previous.empty() && StdAlignValT)
15587         Previous.addDecl(getStdAlignValT());
15588     }
15589   }
15590 
15591   // If we didn't find a previous declaration, and this is a reference
15592   // (or friend reference), move to the correct scope.  In C++, we
15593   // also need to do a redeclaration lookup there, just in case
15594   // there's a shadow friend decl.
15595   if (Name && Previous.empty() &&
15596       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15597     if (Invalid) goto CreateNewDecl;
15598     assert(SS.isEmpty());
15599 
15600     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15601       // C++ [basic.scope.pdecl]p5:
15602       //   -- for an elaborated-type-specifier of the form
15603       //
15604       //          class-key identifier
15605       //
15606       //      if the elaborated-type-specifier is used in the
15607       //      decl-specifier-seq or parameter-declaration-clause of a
15608       //      function defined in namespace scope, the identifier is
15609       //      declared as a class-name in the namespace that contains
15610       //      the declaration; otherwise, except as a friend
15611       //      declaration, the identifier is declared in the smallest
15612       //      non-class, non-function-prototype scope that contains the
15613       //      declaration.
15614       //
15615       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15616       // C structs and unions.
15617       //
15618       // It is an error in C++ to declare (rather than define) an enum
15619       // type, including via an elaborated type specifier.  We'll
15620       // diagnose that later; for now, declare the enum in the same
15621       // scope as we would have picked for any other tag type.
15622       //
15623       // GNU C also supports this behavior as part of its incomplete
15624       // enum types extension, while GNU C++ does not.
15625       //
15626       // Find the context where we'll be declaring the tag.
15627       // FIXME: We would like to maintain the current DeclContext as the
15628       // lexical context,
15629       SearchDC = getTagInjectionContext(SearchDC);
15630 
15631       // Find the scope where we'll be declaring the tag.
15632       S = getTagInjectionScope(S, getLangOpts());
15633     } else {
15634       assert(TUK == TUK_Friend);
15635       // C++ [namespace.memdef]p3:
15636       //   If a friend declaration in a non-local class first declares a
15637       //   class or function, the friend class or function is a member of
15638       //   the innermost enclosing namespace.
15639       SearchDC = SearchDC->getEnclosingNamespaceContext();
15640     }
15641 
15642     // In C++, we need to do a redeclaration lookup to properly
15643     // diagnose some problems.
15644     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15645     // hidden declaration so that we don't get ambiguity errors when using a
15646     // type declared by an elaborated-type-specifier.  In C that is not correct
15647     // and we should instead merge compatible types found by lookup.
15648     if (getLangOpts().CPlusPlus) {
15649       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15650       LookupQualifiedName(Previous, SearchDC);
15651     } else {
15652       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15653       LookupName(Previous, S);
15654     }
15655   }
15656 
15657   // If we have a known previous declaration to use, then use it.
15658   if (Previous.empty() && SkipBody && SkipBody->Previous)
15659     Previous.addDecl(SkipBody->Previous);
15660 
15661   if (!Previous.empty()) {
15662     NamedDecl *PrevDecl = Previous.getFoundDecl();
15663     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15664 
15665     // It's okay to have a tag decl in the same scope as a typedef
15666     // which hides a tag decl in the same scope.  Finding this
15667     // insanity with a redeclaration lookup can only actually happen
15668     // in C++.
15669     //
15670     // This is also okay for elaborated-type-specifiers, which is
15671     // technically forbidden by the current standard but which is
15672     // okay according to the likely resolution of an open issue;
15673     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15674     if (getLangOpts().CPlusPlus) {
15675       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15676         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15677           TagDecl *Tag = TT->getDecl();
15678           if (Tag->getDeclName() == Name &&
15679               Tag->getDeclContext()->getRedeclContext()
15680                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15681             PrevDecl = Tag;
15682             Previous.clear();
15683             Previous.addDecl(Tag);
15684             Previous.resolveKind();
15685           }
15686         }
15687       }
15688     }
15689 
15690     // If this is a redeclaration of a using shadow declaration, it must
15691     // declare a tag in the same context. In MSVC mode, we allow a
15692     // redefinition if either context is within the other.
15693     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15694       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15695       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15696           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15697           !(OldTag && isAcceptableTagRedeclContext(
15698                           *this, OldTag->getDeclContext(), SearchDC))) {
15699         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15700         Diag(Shadow->getTargetDecl()->getLocation(),
15701              diag::note_using_decl_target);
15702         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15703             << 0;
15704         // Recover by ignoring the old declaration.
15705         Previous.clear();
15706         goto CreateNewDecl;
15707       }
15708     }
15709 
15710     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15711       // If this is a use of a previous tag, or if the tag is already declared
15712       // in the same scope (so that the definition/declaration completes or
15713       // rementions the tag), reuse the decl.
15714       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15715           isDeclInScope(DirectPrevDecl, SearchDC, S,
15716                         SS.isNotEmpty() || isMemberSpecialization)) {
15717         // Make sure that this wasn't declared as an enum and now used as a
15718         // struct or something similar.
15719         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15720                                           TUK == TUK_Definition, KWLoc,
15721                                           Name)) {
15722           bool SafeToContinue
15723             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15724                Kind != TTK_Enum);
15725           if (SafeToContinue)
15726             Diag(KWLoc, diag::err_use_with_wrong_tag)
15727               << Name
15728               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15729                                               PrevTagDecl->getKindName());
15730           else
15731             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15732           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15733 
15734           if (SafeToContinue)
15735             Kind = PrevTagDecl->getTagKind();
15736           else {
15737             // Recover by making this an anonymous redefinition.
15738             Name = nullptr;
15739             Previous.clear();
15740             Invalid = true;
15741           }
15742         }
15743 
15744         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15745           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15746           if (TUK == TUK_Reference || TUK == TUK_Friend)
15747             return PrevTagDecl;
15748 
15749           QualType EnumUnderlyingTy;
15750           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15751             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15752           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15753             EnumUnderlyingTy = QualType(T, 0);
15754 
15755           // All conflicts with previous declarations are recovered by
15756           // returning the previous declaration, unless this is a definition,
15757           // in which case we want the caller to bail out.
15758           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15759                                      ScopedEnum, EnumUnderlyingTy,
15760                                      IsFixed, PrevEnum))
15761             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15762         }
15763 
15764         // C++11 [class.mem]p1:
15765         //   A member shall not be declared twice in the member-specification,
15766         //   except that a nested class or member class template can be declared
15767         //   and then later defined.
15768         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15769             S->isDeclScope(PrevDecl)) {
15770           Diag(NameLoc, diag::ext_member_redeclared);
15771           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15772         }
15773 
15774         if (!Invalid) {
15775           // If this is a use, just return the declaration we found, unless
15776           // we have attributes.
15777           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15778             if (!Attrs.empty()) {
15779               // FIXME: Diagnose these attributes. For now, we create a new
15780               // declaration to hold them.
15781             } else if (TUK == TUK_Reference &&
15782                        (PrevTagDecl->getFriendObjectKind() ==
15783                             Decl::FOK_Undeclared ||
15784                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15785                        SS.isEmpty()) {
15786               // This declaration is a reference to an existing entity, but
15787               // has different visibility from that entity: it either makes
15788               // a friend visible or it makes a type visible in a new module.
15789               // In either case, create a new declaration. We only do this if
15790               // the declaration would have meant the same thing if no prior
15791               // declaration were found, that is, if it was found in the same
15792               // scope where we would have injected a declaration.
15793               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15794                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15795                 return PrevTagDecl;
15796               // This is in the injected scope, create a new declaration in
15797               // that scope.
15798               S = getTagInjectionScope(S, getLangOpts());
15799             } else {
15800               return PrevTagDecl;
15801             }
15802           }
15803 
15804           // Diagnose attempts to redefine a tag.
15805           if (TUK == TUK_Definition) {
15806             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15807               // If we're defining a specialization and the previous definition
15808               // is from an implicit instantiation, don't emit an error
15809               // here; we'll catch this in the general case below.
15810               bool IsExplicitSpecializationAfterInstantiation = false;
15811               if (isMemberSpecialization) {
15812                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15813                   IsExplicitSpecializationAfterInstantiation =
15814                     RD->getTemplateSpecializationKind() !=
15815                     TSK_ExplicitSpecialization;
15816                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15817                   IsExplicitSpecializationAfterInstantiation =
15818                     ED->getTemplateSpecializationKind() !=
15819                     TSK_ExplicitSpecialization;
15820               }
15821 
15822               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15823               // not keep more that one definition around (merge them). However,
15824               // ensure the decl passes the structural compatibility check in
15825               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15826               NamedDecl *Hidden = nullptr;
15827               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15828                 // There is a definition of this tag, but it is not visible. We
15829                 // explicitly make use of C++'s one definition rule here, and
15830                 // assume that this definition is identical to the hidden one
15831                 // we already have. Make the existing definition visible and
15832                 // use it in place of this one.
15833                 if (!getLangOpts().CPlusPlus) {
15834                   // Postpone making the old definition visible until after we
15835                   // complete parsing the new one and do the structural
15836                   // comparison.
15837                   SkipBody->CheckSameAsPrevious = true;
15838                   SkipBody->New = createTagFromNewDecl();
15839                   SkipBody->Previous = Def;
15840                   return Def;
15841                 } else {
15842                   SkipBody->ShouldSkip = true;
15843                   SkipBody->Previous = Def;
15844                   makeMergedDefinitionVisible(Hidden);
15845                   // Carry on and handle it like a normal definition. We'll
15846                   // skip starting the definitiion later.
15847                 }
15848               } else if (!IsExplicitSpecializationAfterInstantiation) {
15849                 // A redeclaration in function prototype scope in C isn't
15850                 // visible elsewhere, so merely issue a warning.
15851                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15852                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15853                 else
15854                   Diag(NameLoc, diag::err_redefinition) << Name;
15855                 notePreviousDefinition(Def,
15856                                        NameLoc.isValid() ? NameLoc : KWLoc);
15857                 // If this is a redefinition, recover by making this
15858                 // struct be anonymous, which will make any later
15859                 // references get the previous definition.
15860                 Name = nullptr;
15861                 Previous.clear();
15862                 Invalid = true;
15863               }
15864             } else {
15865               // If the type is currently being defined, complain
15866               // about a nested redefinition.
15867               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15868               if (TD->isBeingDefined()) {
15869                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15870                 Diag(PrevTagDecl->getLocation(),
15871                      diag::note_previous_definition);
15872                 Name = nullptr;
15873                 Previous.clear();
15874                 Invalid = true;
15875               }
15876             }
15877 
15878             // Okay, this is definition of a previously declared or referenced
15879             // tag. We're going to create a new Decl for it.
15880           }
15881 
15882           // Okay, we're going to make a redeclaration.  If this is some kind
15883           // of reference, make sure we build the redeclaration in the same DC
15884           // as the original, and ignore the current access specifier.
15885           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15886             SearchDC = PrevTagDecl->getDeclContext();
15887             AS = AS_none;
15888           }
15889         }
15890         // If we get here we have (another) forward declaration or we
15891         // have a definition.  Just create a new decl.
15892 
15893       } else {
15894         // If we get here, this is a definition of a new tag type in a nested
15895         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15896         // new decl/type.  We set PrevDecl to NULL so that the entities
15897         // have distinct types.
15898         Previous.clear();
15899       }
15900       // If we get here, we're going to create a new Decl. If PrevDecl
15901       // is non-NULL, it's a definition of the tag declared by
15902       // PrevDecl. If it's NULL, we have a new definition.
15903 
15904     // Otherwise, PrevDecl is not a tag, but was found with tag
15905     // lookup.  This is only actually possible in C++, where a few
15906     // things like templates still live in the tag namespace.
15907     } else {
15908       // Use a better diagnostic if an elaborated-type-specifier
15909       // found the wrong kind of type on the first
15910       // (non-redeclaration) lookup.
15911       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15912           !Previous.isForRedeclaration()) {
15913         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15914         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15915                                                        << Kind;
15916         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15917         Invalid = true;
15918 
15919       // Otherwise, only diagnose if the declaration is in scope.
15920       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15921                                 SS.isNotEmpty() || isMemberSpecialization)) {
15922         // do nothing
15923 
15924       // Diagnose implicit declarations introduced by elaborated types.
15925       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15926         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15927         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15928         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15929         Invalid = true;
15930 
15931       // Otherwise it's a declaration.  Call out a particularly common
15932       // case here.
15933       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15934         unsigned Kind = 0;
15935         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15936         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15937           << Name << Kind << TND->getUnderlyingType();
15938         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15939         Invalid = true;
15940 
15941       // Otherwise, diagnose.
15942       } else {
15943         // The tag name clashes with something else in the target scope,
15944         // issue an error and recover by making this tag be anonymous.
15945         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15946         notePreviousDefinition(PrevDecl, NameLoc);
15947         Name = nullptr;
15948         Invalid = true;
15949       }
15950 
15951       // The existing declaration isn't relevant to us; we're in a
15952       // new scope, so clear out the previous declaration.
15953       Previous.clear();
15954     }
15955   }
15956 
15957 CreateNewDecl:
15958 
15959   TagDecl *PrevDecl = nullptr;
15960   if (Previous.isSingleResult())
15961     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15962 
15963   // If there is an identifier, use the location of the identifier as the
15964   // location of the decl, otherwise use the location of the struct/union
15965   // keyword.
15966   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15967 
15968   // Otherwise, create a new declaration. If there is a previous
15969   // declaration of the same entity, the two will be linked via
15970   // PrevDecl.
15971   TagDecl *New;
15972 
15973   if (Kind == TTK_Enum) {
15974     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15975     // enum X { A, B, C } D;    D should chain to X.
15976     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15977                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15978                            ScopedEnumUsesClassTag, IsFixed);
15979 
15980     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15981       StdAlignValT = cast<EnumDecl>(New);
15982 
15983     // If this is an undefined enum, warn.
15984     if (TUK != TUK_Definition && !Invalid) {
15985       TagDecl *Def;
15986       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15987         // C++0x: 7.2p2: opaque-enum-declaration.
15988         // Conflicts are diagnosed above. Do nothing.
15989       }
15990       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15991         Diag(Loc, diag::ext_forward_ref_enum_def)
15992           << New;
15993         Diag(Def->getLocation(), diag::note_previous_definition);
15994       } else {
15995         unsigned DiagID = diag::ext_forward_ref_enum;
15996         if (getLangOpts().MSVCCompat)
15997           DiagID = diag::ext_ms_forward_ref_enum;
15998         else if (getLangOpts().CPlusPlus)
15999           DiagID = diag::err_forward_ref_enum;
16000         Diag(Loc, DiagID);
16001       }
16002     }
16003 
16004     if (EnumUnderlying) {
16005       EnumDecl *ED = cast<EnumDecl>(New);
16006       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16007         ED->setIntegerTypeSourceInfo(TI);
16008       else
16009         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16010       ED->setPromotionType(ED->getIntegerType());
16011       assert(ED->isComplete() && "enum with type should be complete");
16012     }
16013   } else {
16014     // struct/union/class
16015 
16016     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16017     // struct X { int A; } D;    D should chain to X.
16018     if (getLangOpts().CPlusPlus) {
16019       // FIXME: Look for a way to use RecordDecl for simple structs.
16020       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16021                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16022 
16023       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16024         StdBadAlloc = cast<CXXRecordDecl>(New);
16025     } else
16026       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16027                                cast_or_null<RecordDecl>(PrevDecl));
16028   }
16029 
16030   // C++11 [dcl.type]p3:
16031   //   A type-specifier-seq shall not define a class or enumeration [...].
16032   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16033       TUK == TUK_Definition) {
16034     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16035       << Context.getTagDeclType(New);
16036     Invalid = true;
16037   }
16038 
16039   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16040       DC->getDeclKind() == Decl::Enum) {
16041     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16042       << Context.getTagDeclType(New);
16043     Invalid = true;
16044   }
16045 
16046   // Maybe add qualifier info.
16047   if (SS.isNotEmpty()) {
16048     if (SS.isSet()) {
16049       // If this is either a declaration or a definition, check the
16050       // nested-name-specifier against the current context.
16051       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16052           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16053                                        isMemberSpecialization))
16054         Invalid = true;
16055 
16056       New->setQualifierInfo(SS.getWithLocInContext(Context));
16057       if (TemplateParameterLists.size() > 0) {
16058         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16059       }
16060     }
16061     else
16062       Invalid = true;
16063   }
16064 
16065   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16066     // Add alignment attributes if necessary; these attributes are checked when
16067     // the ASTContext lays out the structure.
16068     //
16069     // It is important for implementing the correct semantics that this
16070     // happen here (in ActOnTag). The #pragma pack stack is
16071     // maintained as a result of parser callbacks which can occur at
16072     // many points during the parsing of a struct declaration (because
16073     // the #pragma tokens are effectively skipped over during the
16074     // parsing of the struct).
16075     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16076       AddAlignmentAttributesForRecord(RD);
16077       AddMsStructLayoutForRecord(RD);
16078     }
16079   }
16080 
16081   if (ModulePrivateLoc.isValid()) {
16082     if (isMemberSpecialization)
16083       Diag(New->getLocation(), diag::err_module_private_specialization)
16084         << 2
16085         << FixItHint::CreateRemoval(ModulePrivateLoc);
16086     // __module_private__ does not apply to local classes. However, we only
16087     // diagnose this as an error when the declaration specifiers are
16088     // freestanding. Here, we just ignore the __module_private__.
16089     else if (!SearchDC->isFunctionOrMethod())
16090       New->setModulePrivate();
16091   }
16092 
16093   // If this is a specialization of a member class (of a class template),
16094   // check the specialization.
16095   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16096     Invalid = true;
16097 
16098   // If we're declaring or defining a tag in function prototype scope in C,
16099   // note that this type can only be used within the function and add it to
16100   // the list of decls to inject into the function definition scope.
16101   if ((Name || Kind == TTK_Enum) &&
16102       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16103     if (getLangOpts().CPlusPlus) {
16104       // C++ [dcl.fct]p6:
16105       //   Types shall not be defined in return or parameter types.
16106       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16107         Diag(Loc, diag::err_type_defined_in_param_type)
16108             << Name;
16109         Invalid = true;
16110       }
16111     } else if (!PrevDecl) {
16112       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16113     }
16114   }
16115 
16116   if (Invalid)
16117     New->setInvalidDecl();
16118 
16119   // Set the lexical context. If the tag has a C++ scope specifier, the
16120   // lexical context will be different from the semantic context.
16121   New->setLexicalDeclContext(CurContext);
16122 
16123   // Mark this as a friend decl if applicable.
16124   // In Microsoft mode, a friend declaration also acts as a forward
16125   // declaration so we always pass true to setObjectOfFriendDecl to make
16126   // the tag name visible.
16127   if (TUK == TUK_Friend)
16128     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16129 
16130   // Set the access specifier.
16131   if (!Invalid && SearchDC->isRecord())
16132     SetMemberAccessSpecifier(New, PrevDecl, AS);
16133 
16134   if (PrevDecl)
16135     CheckRedeclarationModuleOwnership(New, PrevDecl);
16136 
16137   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16138     New->startDefinition();
16139 
16140   ProcessDeclAttributeList(S, New, Attrs);
16141   AddPragmaAttributes(S, New);
16142 
16143   // If this has an identifier, add it to the scope stack.
16144   if (TUK == TUK_Friend) {
16145     // We might be replacing an existing declaration in the lookup tables;
16146     // if so, borrow its access specifier.
16147     if (PrevDecl)
16148       New->setAccess(PrevDecl->getAccess());
16149 
16150     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16151     DC->makeDeclVisibleInContext(New);
16152     if (Name) // can be null along some error paths
16153       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16154         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16155   } else if (Name) {
16156     S = getNonFieldDeclScope(S);
16157     PushOnScopeChains(New, S, true);
16158   } else {
16159     CurContext->addDecl(New);
16160   }
16161 
16162   // If this is the C FILE type, notify the AST context.
16163   if (IdentifierInfo *II = New->getIdentifier())
16164     if (!New->isInvalidDecl() &&
16165         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16166         II->isStr("FILE"))
16167       Context.setFILEDecl(New);
16168 
16169   if (PrevDecl)
16170     mergeDeclAttributes(New, PrevDecl);
16171 
16172   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16173     inferGslOwnerPointerAttribute(CXXRD);
16174 
16175   // If there's a #pragma GCC visibility in scope, set the visibility of this
16176   // record.
16177   AddPushedVisibilityAttribute(New);
16178 
16179   if (isMemberSpecialization && !New->isInvalidDecl())
16180     CompleteMemberSpecialization(New, Previous);
16181 
16182   OwnedDecl = true;
16183   // In C++, don't return an invalid declaration. We can't recover well from
16184   // the cases where we make the type anonymous.
16185   if (Invalid && getLangOpts().CPlusPlus) {
16186     if (New->isBeingDefined())
16187       if (auto RD = dyn_cast<RecordDecl>(New))
16188         RD->completeDefinition();
16189     return nullptr;
16190   } else if (SkipBody && SkipBody->ShouldSkip) {
16191     return SkipBody->Previous;
16192   } else {
16193     return New;
16194   }
16195 }
16196 
16197 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16198   AdjustDeclIfTemplate(TagD);
16199   TagDecl *Tag = cast<TagDecl>(TagD);
16200 
16201   // Enter the tag context.
16202   PushDeclContext(S, Tag);
16203 
16204   ActOnDocumentableDecl(TagD);
16205 
16206   // If there's a #pragma GCC visibility in scope, set the visibility of this
16207   // record.
16208   AddPushedVisibilityAttribute(Tag);
16209 }
16210 
16211 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16212                                     SkipBodyInfo &SkipBody) {
16213   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16214     return false;
16215 
16216   // Make the previous decl visible.
16217   makeMergedDefinitionVisible(SkipBody.Previous);
16218   return true;
16219 }
16220 
16221 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16222   assert(isa<ObjCContainerDecl>(IDecl) &&
16223          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16224   DeclContext *OCD = cast<DeclContext>(IDecl);
16225   assert(OCD->getLexicalParent() == CurContext &&
16226       "The next DeclContext should be lexically contained in the current one.");
16227   CurContext = OCD;
16228   return IDecl;
16229 }
16230 
16231 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16232                                            SourceLocation FinalLoc,
16233                                            bool IsFinalSpelledSealed,
16234                                            SourceLocation LBraceLoc) {
16235   AdjustDeclIfTemplate(TagD);
16236   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16237 
16238   FieldCollector->StartClass();
16239 
16240   if (!Record->getIdentifier())
16241     return;
16242 
16243   if (FinalLoc.isValid())
16244     Record->addAttr(FinalAttr::Create(
16245         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16246         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16247 
16248   // C++ [class]p2:
16249   //   [...] The class-name is also inserted into the scope of the
16250   //   class itself; this is known as the injected-class-name. For
16251   //   purposes of access checking, the injected-class-name is treated
16252   //   as if it were a public member name.
16253   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16254       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16255       Record->getLocation(), Record->getIdentifier(),
16256       /*PrevDecl=*/nullptr,
16257       /*DelayTypeCreation=*/true);
16258   Context.getTypeDeclType(InjectedClassName, Record);
16259   InjectedClassName->setImplicit();
16260   InjectedClassName->setAccess(AS_public);
16261   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16262       InjectedClassName->setDescribedClassTemplate(Template);
16263   PushOnScopeChains(InjectedClassName, S);
16264   assert(InjectedClassName->isInjectedClassName() &&
16265          "Broken injected-class-name");
16266 }
16267 
16268 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16269                                     SourceRange BraceRange) {
16270   AdjustDeclIfTemplate(TagD);
16271   TagDecl *Tag = cast<TagDecl>(TagD);
16272   Tag->setBraceRange(BraceRange);
16273 
16274   // Make sure we "complete" the definition even it is invalid.
16275   if (Tag->isBeingDefined()) {
16276     assert(Tag->isInvalidDecl() && "We should already have completed it");
16277     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16278       RD->completeDefinition();
16279   }
16280 
16281   if (isa<CXXRecordDecl>(Tag)) {
16282     FieldCollector->FinishClass();
16283   }
16284 
16285   // Exit this scope of this tag's definition.
16286   PopDeclContext();
16287 
16288   if (getCurLexicalContext()->isObjCContainer() &&
16289       Tag->getDeclContext()->isFileContext())
16290     Tag->setTopLevelDeclInObjCContainer();
16291 
16292   // Notify the consumer that we've defined a tag.
16293   if (!Tag->isInvalidDecl())
16294     Consumer.HandleTagDeclDefinition(Tag);
16295 }
16296 
16297 void Sema::ActOnObjCContainerFinishDefinition() {
16298   // Exit this scope of this interface definition.
16299   PopDeclContext();
16300 }
16301 
16302 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16303   assert(DC == CurContext && "Mismatch of container contexts");
16304   OriginalLexicalContext = DC;
16305   ActOnObjCContainerFinishDefinition();
16306 }
16307 
16308 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16309   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16310   OriginalLexicalContext = nullptr;
16311 }
16312 
16313 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16314   AdjustDeclIfTemplate(TagD);
16315   TagDecl *Tag = cast<TagDecl>(TagD);
16316   Tag->setInvalidDecl();
16317 
16318   // Make sure we "complete" the definition even it is invalid.
16319   if (Tag->isBeingDefined()) {
16320     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16321       RD->completeDefinition();
16322   }
16323 
16324   // We're undoing ActOnTagStartDefinition here, not
16325   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16326   // the FieldCollector.
16327 
16328   PopDeclContext();
16329 }
16330 
16331 // Note that FieldName may be null for anonymous bitfields.
16332 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16333                                 IdentifierInfo *FieldName,
16334                                 QualType FieldTy, bool IsMsStruct,
16335                                 Expr *BitWidth, bool *ZeroWidth) {
16336   assert(BitWidth);
16337   if (BitWidth->containsErrors())
16338     return ExprError();
16339 
16340   // Default to true; that shouldn't confuse checks for emptiness
16341   if (ZeroWidth)
16342     *ZeroWidth = true;
16343 
16344   // C99 6.7.2.1p4 - verify the field type.
16345   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16346   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16347     // Handle incomplete and sizeless types with a specific error.
16348     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16349                                  diag::err_field_incomplete_or_sizeless))
16350       return ExprError();
16351     if (FieldName)
16352       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16353         << FieldName << FieldTy << BitWidth->getSourceRange();
16354     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16355       << FieldTy << BitWidth->getSourceRange();
16356   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16357                                              UPPC_BitFieldWidth))
16358     return ExprError();
16359 
16360   // If the bit-width is type- or value-dependent, don't try to check
16361   // it now.
16362   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16363     return BitWidth;
16364 
16365   llvm::APSInt Value;
16366   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16367   if (ICE.isInvalid())
16368     return ICE;
16369   BitWidth = ICE.get();
16370 
16371   if (Value != 0 && ZeroWidth)
16372     *ZeroWidth = false;
16373 
16374   // Zero-width bitfield is ok for anonymous field.
16375   if (Value == 0 && FieldName)
16376     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16377 
16378   if (Value.isSigned() && Value.isNegative()) {
16379     if (FieldName)
16380       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16381                << FieldName << Value.toString(10);
16382     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16383       << Value.toString(10);
16384   }
16385 
16386   if (!FieldTy->isDependentType()) {
16387     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16388     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16389     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16390 
16391     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16392     // ABI.
16393     bool CStdConstraintViolation =
16394         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16395     bool MSBitfieldViolation =
16396         Value.ugt(TypeStorageSize) &&
16397         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16398     if (CStdConstraintViolation || MSBitfieldViolation) {
16399       unsigned DiagWidth =
16400           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16401       if (FieldName)
16402         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16403                << FieldName << (unsigned)Value.getZExtValue()
16404                << !CStdConstraintViolation << DiagWidth;
16405 
16406       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16407              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16408              << DiagWidth;
16409     }
16410 
16411     // Warn on types where the user might conceivably expect to get all
16412     // specified bits as value bits: that's all integral types other than
16413     // 'bool'.
16414     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16415       if (FieldName)
16416         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16417             << FieldName << (unsigned)Value.getZExtValue()
16418             << (unsigned)TypeWidth;
16419       else
16420         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16421             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16422     }
16423   }
16424 
16425   return BitWidth;
16426 }
16427 
16428 /// ActOnField - Each field of a C struct/union is passed into this in order
16429 /// to create a FieldDecl object for it.
16430 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16431                        Declarator &D, Expr *BitfieldWidth) {
16432   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16433                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16434                                /*InitStyle=*/ICIS_NoInit, AS_public);
16435   return Res;
16436 }
16437 
16438 /// HandleField - Analyze a field of a C struct or a C++ data member.
16439 ///
16440 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16441                              SourceLocation DeclStart,
16442                              Declarator &D, Expr *BitWidth,
16443                              InClassInitStyle InitStyle,
16444                              AccessSpecifier AS) {
16445   if (D.isDecompositionDeclarator()) {
16446     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16447     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16448       << Decomp.getSourceRange();
16449     return nullptr;
16450   }
16451 
16452   IdentifierInfo *II = D.getIdentifier();
16453   SourceLocation Loc = DeclStart;
16454   if (II) Loc = D.getIdentifierLoc();
16455 
16456   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16457   QualType T = TInfo->getType();
16458   if (getLangOpts().CPlusPlus) {
16459     CheckExtraCXXDefaultArguments(D);
16460 
16461     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16462                                         UPPC_DataMemberType)) {
16463       D.setInvalidType();
16464       T = Context.IntTy;
16465       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16466     }
16467   }
16468 
16469   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16470 
16471   if (D.getDeclSpec().isInlineSpecified())
16472     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16473         << getLangOpts().CPlusPlus17;
16474   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16475     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16476          diag::err_invalid_thread)
16477       << DeclSpec::getSpecifierName(TSCS);
16478 
16479   // Check to see if this name was declared as a member previously
16480   NamedDecl *PrevDecl = nullptr;
16481   LookupResult Previous(*this, II, Loc, LookupMemberName,
16482                         ForVisibleRedeclaration);
16483   LookupName(Previous, S);
16484   switch (Previous.getResultKind()) {
16485     case LookupResult::Found:
16486     case LookupResult::FoundUnresolvedValue:
16487       PrevDecl = Previous.getAsSingle<NamedDecl>();
16488       break;
16489 
16490     case LookupResult::FoundOverloaded:
16491       PrevDecl = Previous.getRepresentativeDecl();
16492       break;
16493 
16494     case LookupResult::NotFound:
16495     case LookupResult::NotFoundInCurrentInstantiation:
16496     case LookupResult::Ambiguous:
16497       break;
16498   }
16499   Previous.suppressDiagnostics();
16500 
16501   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16502     // Maybe we will complain about the shadowed template parameter.
16503     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16504     // Just pretend that we didn't see the previous declaration.
16505     PrevDecl = nullptr;
16506   }
16507 
16508   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16509     PrevDecl = nullptr;
16510 
16511   bool Mutable
16512     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16513   SourceLocation TSSL = D.getBeginLoc();
16514   FieldDecl *NewFD
16515     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16516                      TSSL, AS, PrevDecl, &D);
16517 
16518   if (NewFD->isInvalidDecl())
16519     Record->setInvalidDecl();
16520 
16521   if (D.getDeclSpec().isModulePrivateSpecified())
16522     NewFD->setModulePrivate();
16523 
16524   if (NewFD->isInvalidDecl() && PrevDecl) {
16525     // Don't introduce NewFD into scope; there's already something
16526     // with the same name in the same scope.
16527   } else if (II) {
16528     PushOnScopeChains(NewFD, S);
16529   } else
16530     Record->addDecl(NewFD);
16531 
16532   return NewFD;
16533 }
16534 
16535 /// Build a new FieldDecl and check its well-formedness.
16536 ///
16537 /// This routine builds a new FieldDecl given the fields name, type,
16538 /// record, etc. \p PrevDecl should refer to any previous declaration
16539 /// with the same name and in the same scope as the field to be
16540 /// created.
16541 ///
16542 /// \returns a new FieldDecl.
16543 ///
16544 /// \todo The Declarator argument is a hack. It will be removed once
16545 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16546                                 TypeSourceInfo *TInfo,
16547                                 RecordDecl *Record, SourceLocation Loc,
16548                                 bool Mutable, Expr *BitWidth,
16549                                 InClassInitStyle InitStyle,
16550                                 SourceLocation TSSL,
16551                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16552                                 Declarator *D) {
16553   IdentifierInfo *II = Name.getAsIdentifierInfo();
16554   bool InvalidDecl = false;
16555   if (D) InvalidDecl = D->isInvalidType();
16556 
16557   // If we receive a broken type, recover by assuming 'int' and
16558   // marking this declaration as invalid.
16559   if (T.isNull() || T->containsErrors()) {
16560     InvalidDecl = true;
16561     T = Context.IntTy;
16562   }
16563 
16564   QualType EltTy = Context.getBaseElementType(T);
16565   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16566     if (RequireCompleteSizedType(Loc, EltTy,
16567                                  diag::err_field_incomplete_or_sizeless)) {
16568       // Fields of incomplete type force their record to be invalid.
16569       Record->setInvalidDecl();
16570       InvalidDecl = true;
16571     } else {
16572       NamedDecl *Def;
16573       EltTy->isIncompleteType(&Def);
16574       if (Def && Def->isInvalidDecl()) {
16575         Record->setInvalidDecl();
16576         InvalidDecl = true;
16577       }
16578     }
16579   }
16580 
16581   // TR 18037 does not allow fields to be declared with address space
16582   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16583       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16584     Diag(Loc, diag::err_field_with_address_space);
16585     Record->setInvalidDecl();
16586     InvalidDecl = true;
16587   }
16588 
16589   if (LangOpts.OpenCL) {
16590     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16591     // used as structure or union field: image, sampler, event or block types.
16592     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16593         T->isBlockPointerType()) {
16594       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16595       Record->setInvalidDecl();
16596       InvalidDecl = true;
16597     }
16598     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16599     if (BitWidth) {
16600       Diag(Loc, diag::err_opencl_bitfields);
16601       InvalidDecl = true;
16602     }
16603   }
16604 
16605   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16606   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16607       T.hasQualifiers()) {
16608     InvalidDecl = true;
16609     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16610   }
16611 
16612   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16613   // than a variably modified type.
16614   if (!InvalidDecl && T->isVariablyModifiedType()) {
16615     bool SizeIsNegative;
16616     llvm::APSInt Oversized;
16617 
16618     TypeSourceInfo *FixedTInfo =
16619       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16620                                                     SizeIsNegative,
16621                                                     Oversized);
16622     if (FixedTInfo) {
16623       Diag(Loc, diag::warn_illegal_constant_array_size);
16624       TInfo = FixedTInfo;
16625       T = FixedTInfo->getType();
16626     } else {
16627       if (SizeIsNegative)
16628         Diag(Loc, diag::err_typecheck_negative_array_size);
16629       else if (Oversized.getBoolValue())
16630         Diag(Loc, diag::err_array_too_large)
16631           << Oversized.toString(10);
16632       else
16633         Diag(Loc, diag::err_typecheck_field_variable_size);
16634       InvalidDecl = true;
16635     }
16636   }
16637 
16638   // Fields can not have abstract class types
16639   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16640                                              diag::err_abstract_type_in_decl,
16641                                              AbstractFieldType))
16642     InvalidDecl = true;
16643 
16644   bool ZeroWidth = false;
16645   if (InvalidDecl)
16646     BitWidth = nullptr;
16647   // If this is declared as a bit-field, check the bit-field.
16648   if (BitWidth) {
16649     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16650                               &ZeroWidth).get();
16651     if (!BitWidth) {
16652       InvalidDecl = true;
16653       BitWidth = nullptr;
16654       ZeroWidth = false;
16655     }
16656 
16657     // Only data members can have in-class initializers.
16658     if (BitWidth && !II && InitStyle) {
16659       Diag(Loc, diag::err_anon_bitfield_init);
16660       InvalidDecl = true;
16661       BitWidth = nullptr;
16662       ZeroWidth = false;
16663     }
16664   }
16665 
16666   // Check that 'mutable' is consistent with the type of the declaration.
16667   if (!InvalidDecl && Mutable) {
16668     unsigned DiagID = 0;
16669     if (T->isReferenceType())
16670       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16671                                         : diag::err_mutable_reference;
16672     else if (T.isConstQualified())
16673       DiagID = diag::err_mutable_const;
16674 
16675     if (DiagID) {
16676       SourceLocation ErrLoc = Loc;
16677       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16678         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16679       Diag(ErrLoc, DiagID);
16680       if (DiagID != diag::ext_mutable_reference) {
16681         Mutable = false;
16682         InvalidDecl = true;
16683       }
16684     }
16685   }
16686 
16687   // C++11 [class.union]p8 (DR1460):
16688   //   At most one variant member of a union may have a
16689   //   brace-or-equal-initializer.
16690   if (InitStyle != ICIS_NoInit)
16691     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16692 
16693   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16694                                        BitWidth, Mutable, InitStyle);
16695   if (InvalidDecl)
16696     NewFD->setInvalidDecl();
16697 
16698   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16699     Diag(Loc, diag::err_duplicate_member) << II;
16700     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16701     NewFD->setInvalidDecl();
16702   }
16703 
16704   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16705     if (Record->isUnion()) {
16706       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16707         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16708         if (RDecl->getDefinition()) {
16709           // C++ [class.union]p1: An object of a class with a non-trivial
16710           // constructor, a non-trivial copy constructor, a non-trivial
16711           // destructor, or a non-trivial copy assignment operator
16712           // cannot be a member of a union, nor can an array of such
16713           // objects.
16714           if (CheckNontrivialField(NewFD))
16715             NewFD->setInvalidDecl();
16716         }
16717       }
16718 
16719       // C++ [class.union]p1: If a union contains a member of reference type,
16720       // the program is ill-formed, except when compiling with MSVC extensions
16721       // enabled.
16722       if (EltTy->isReferenceType()) {
16723         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16724                                     diag::ext_union_member_of_reference_type :
16725                                     diag::err_union_member_of_reference_type)
16726           << NewFD->getDeclName() << EltTy;
16727         if (!getLangOpts().MicrosoftExt)
16728           NewFD->setInvalidDecl();
16729       }
16730     }
16731   }
16732 
16733   // FIXME: We need to pass in the attributes given an AST
16734   // representation, not a parser representation.
16735   if (D) {
16736     // FIXME: The current scope is almost... but not entirely... correct here.
16737     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16738 
16739     if (NewFD->hasAttrs())
16740       CheckAlignasUnderalignment(NewFD);
16741   }
16742 
16743   // In auto-retain/release, infer strong retension for fields of
16744   // retainable type.
16745   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16746     NewFD->setInvalidDecl();
16747 
16748   if (T.isObjCGCWeak())
16749     Diag(Loc, diag::warn_attribute_weak_on_field);
16750 
16751   NewFD->setAccess(AS);
16752   return NewFD;
16753 }
16754 
16755 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16756   assert(FD);
16757   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16758 
16759   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16760     return false;
16761 
16762   QualType EltTy = Context.getBaseElementType(FD->getType());
16763   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16764     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16765     if (RDecl->getDefinition()) {
16766       // We check for copy constructors before constructors
16767       // because otherwise we'll never get complaints about
16768       // copy constructors.
16769 
16770       CXXSpecialMember member = CXXInvalid;
16771       // We're required to check for any non-trivial constructors. Since the
16772       // implicit default constructor is suppressed if there are any
16773       // user-declared constructors, we just need to check that there is a
16774       // trivial default constructor and a trivial copy constructor. (We don't
16775       // worry about move constructors here, since this is a C++98 check.)
16776       if (RDecl->hasNonTrivialCopyConstructor())
16777         member = CXXCopyConstructor;
16778       else if (!RDecl->hasTrivialDefaultConstructor())
16779         member = CXXDefaultConstructor;
16780       else if (RDecl->hasNonTrivialCopyAssignment())
16781         member = CXXCopyAssignment;
16782       else if (RDecl->hasNonTrivialDestructor())
16783         member = CXXDestructor;
16784 
16785       if (member != CXXInvalid) {
16786         if (!getLangOpts().CPlusPlus11 &&
16787             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16788           // Objective-C++ ARC: it is an error to have a non-trivial field of
16789           // a union. However, system headers in Objective-C programs
16790           // occasionally have Objective-C lifetime objects within unions,
16791           // and rather than cause the program to fail, we make those
16792           // members unavailable.
16793           SourceLocation Loc = FD->getLocation();
16794           if (getSourceManager().isInSystemHeader(Loc)) {
16795             if (!FD->hasAttr<UnavailableAttr>())
16796               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16797                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16798             return false;
16799           }
16800         }
16801 
16802         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16803                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16804                diag::err_illegal_union_or_anon_struct_member)
16805           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16806         DiagnoseNontrivial(RDecl, member);
16807         return !getLangOpts().CPlusPlus11;
16808       }
16809     }
16810   }
16811 
16812   return false;
16813 }
16814 
16815 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16816 ///  AST enum value.
16817 static ObjCIvarDecl::AccessControl
16818 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16819   switch (ivarVisibility) {
16820   default: llvm_unreachable("Unknown visitibility kind");
16821   case tok::objc_private: return ObjCIvarDecl::Private;
16822   case tok::objc_public: return ObjCIvarDecl::Public;
16823   case tok::objc_protected: return ObjCIvarDecl::Protected;
16824   case tok::objc_package: return ObjCIvarDecl::Package;
16825   }
16826 }
16827 
16828 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16829 /// in order to create an IvarDecl object for it.
16830 Decl *Sema::ActOnIvar(Scope *S,
16831                                 SourceLocation DeclStart,
16832                                 Declarator &D, Expr *BitfieldWidth,
16833                                 tok::ObjCKeywordKind Visibility) {
16834 
16835   IdentifierInfo *II = D.getIdentifier();
16836   Expr *BitWidth = (Expr*)BitfieldWidth;
16837   SourceLocation Loc = DeclStart;
16838   if (II) Loc = D.getIdentifierLoc();
16839 
16840   // FIXME: Unnamed fields can be handled in various different ways, for
16841   // example, unnamed unions inject all members into the struct namespace!
16842 
16843   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16844   QualType T = TInfo->getType();
16845 
16846   if (BitWidth) {
16847     // 6.7.2.1p3, 6.7.2.1p4
16848     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16849     if (!BitWidth)
16850       D.setInvalidType();
16851   } else {
16852     // Not a bitfield.
16853 
16854     // validate II.
16855 
16856   }
16857   if (T->isReferenceType()) {
16858     Diag(Loc, diag::err_ivar_reference_type);
16859     D.setInvalidType();
16860   }
16861   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16862   // than a variably modified type.
16863   else if (T->isVariablyModifiedType()) {
16864     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16865     D.setInvalidType();
16866   }
16867 
16868   // Get the visibility (access control) for this ivar.
16869   ObjCIvarDecl::AccessControl ac =
16870     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16871                                         : ObjCIvarDecl::None;
16872   // Must set ivar's DeclContext to its enclosing interface.
16873   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16874   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16875     return nullptr;
16876   ObjCContainerDecl *EnclosingContext;
16877   if (ObjCImplementationDecl *IMPDecl =
16878       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16879     if (LangOpts.ObjCRuntime.isFragile()) {
16880     // Case of ivar declared in an implementation. Context is that of its class.
16881       EnclosingContext = IMPDecl->getClassInterface();
16882       assert(EnclosingContext && "Implementation has no class interface!");
16883     }
16884     else
16885       EnclosingContext = EnclosingDecl;
16886   } else {
16887     if (ObjCCategoryDecl *CDecl =
16888         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16889       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16890         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16891         return nullptr;
16892       }
16893     }
16894     EnclosingContext = EnclosingDecl;
16895   }
16896 
16897   // Construct the decl.
16898   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16899                                              DeclStart, Loc, II, T,
16900                                              TInfo, ac, (Expr *)BitfieldWidth);
16901 
16902   if (II) {
16903     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16904                                            ForVisibleRedeclaration);
16905     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16906         && !isa<TagDecl>(PrevDecl)) {
16907       Diag(Loc, diag::err_duplicate_member) << II;
16908       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16909       NewID->setInvalidDecl();
16910     }
16911   }
16912 
16913   // Process attributes attached to the ivar.
16914   ProcessDeclAttributes(S, NewID, D);
16915 
16916   if (D.isInvalidType())
16917     NewID->setInvalidDecl();
16918 
16919   // In ARC, infer 'retaining' for ivars of retainable type.
16920   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16921     NewID->setInvalidDecl();
16922 
16923   if (D.getDeclSpec().isModulePrivateSpecified())
16924     NewID->setModulePrivate();
16925 
16926   if (II) {
16927     // FIXME: When interfaces are DeclContexts, we'll need to add
16928     // these to the interface.
16929     S->AddDecl(NewID);
16930     IdResolver.AddDecl(NewID);
16931   }
16932 
16933   if (LangOpts.ObjCRuntime.isNonFragile() &&
16934       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16935     Diag(Loc, diag::warn_ivars_in_interface);
16936 
16937   return NewID;
16938 }
16939 
16940 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16941 /// class and class extensions. For every class \@interface and class
16942 /// extension \@interface, if the last ivar is a bitfield of any type,
16943 /// then add an implicit `char :0` ivar to the end of that interface.
16944 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16945                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16946   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16947     return;
16948 
16949   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16950   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16951 
16952   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16953     return;
16954   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16955   if (!ID) {
16956     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16957       if (!CD->IsClassExtension())
16958         return;
16959     }
16960     // No need to add this to end of @implementation.
16961     else
16962       return;
16963   }
16964   // All conditions are met. Add a new bitfield to the tail end of ivars.
16965   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16966   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16967 
16968   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16969                               DeclLoc, DeclLoc, nullptr,
16970                               Context.CharTy,
16971                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16972                                                                DeclLoc),
16973                               ObjCIvarDecl::Private, BW,
16974                               true);
16975   AllIvarDecls.push_back(Ivar);
16976 }
16977 
16978 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16979                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16980                        SourceLocation RBrac,
16981                        const ParsedAttributesView &Attrs) {
16982   assert(EnclosingDecl && "missing record or interface decl");
16983 
16984   // If this is an Objective-C @implementation or category and we have
16985   // new fields here we should reset the layout of the interface since
16986   // it will now change.
16987   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16988     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16989     switch (DC->getKind()) {
16990     default: break;
16991     case Decl::ObjCCategory:
16992       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16993       break;
16994     case Decl::ObjCImplementation:
16995       Context.
16996         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16997       break;
16998     }
16999   }
17000 
17001   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17002   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17003 
17004   // Start counting up the number of named members; make sure to include
17005   // members of anonymous structs and unions in the total.
17006   unsigned NumNamedMembers = 0;
17007   if (Record) {
17008     for (const auto *I : Record->decls()) {
17009       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17010         if (IFD->getDeclName())
17011           ++NumNamedMembers;
17012     }
17013   }
17014 
17015   // Verify that all the fields are okay.
17016   SmallVector<FieldDecl*, 32> RecFields;
17017 
17018   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17019        i != end; ++i) {
17020     FieldDecl *FD = cast<FieldDecl>(*i);
17021 
17022     // Get the type for the field.
17023     const Type *FDTy = FD->getType().getTypePtr();
17024 
17025     if (!FD->isAnonymousStructOrUnion()) {
17026       // Remember all fields written by the user.
17027       RecFields.push_back(FD);
17028     }
17029 
17030     // If the field is already invalid for some reason, don't emit more
17031     // diagnostics about it.
17032     if (FD->isInvalidDecl()) {
17033       EnclosingDecl->setInvalidDecl();
17034       continue;
17035     }
17036 
17037     // C99 6.7.2.1p2:
17038     //   A structure or union shall not contain a member with
17039     //   incomplete or function type (hence, a structure shall not
17040     //   contain an instance of itself, but may contain a pointer to
17041     //   an instance of itself), except that the last member of a
17042     //   structure with more than one named member may have incomplete
17043     //   array type; such a structure (and any union containing,
17044     //   possibly recursively, a member that is such a structure)
17045     //   shall not be a member of a structure or an element of an
17046     //   array.
17047     bool IsLastField = (i + 1 == Fields.end());
17048     if (FDTy->isFunctionType()) {
17049       // Field declared as a function.
17050       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17051         << FD->getDeclName();
17052       FD->setInvalidDecl();
17053       EnclosingDecl->setInvalidDecl();
17054       continue;
17055     } else if (FDTy->isIncompleteArrayType() &&
17056                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17057       if (Record) {
17058         // Flexible array member.
17059         // Microsoft and g++ is more permissive regarding flexible array.
17060         // It will accept flexible array in union and also
17061         // as the sole element of a struct/class.
17062         unsigned DiagID = 0;
17063         if (!Record->isUnion() && !IsLastField) {
17064           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17065             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17066           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17067           FD->setInvalidDecl();
17068           EnclosingDecl->setInvalidDecl();
17069           continue;
17070         } else if (Record->isUnion())
17071           DiagID = getLangOpts().MicrosoftExt
17072                        ? diag::ext_flexible_array_union_ms
17073                        : getLangOpts().CPlusPlus
17074                              ? diag::ext_flexible_array_union_gnu
17075                              : diag::err_flexible_array_union;
17076         else if (NumNamedMembers < 1)
17077           DiagID = getLangOpts().MicrosoftExt
17078                        ? diag::ext_flexible_array_empty_aggregate_ms
17079                        : getLangOpts().CPlusPlus
17080                              ? diag::ext_flexible_array_empty_aggregate_gnu
17081                              : diag::err_flexible_array_empty_aggregate;
17082 
17083         if (DiagID)
17084           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17085                                           << Record->getTagKind();
17086         // While the layout of types that contain virtual bases is not specified
17087         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17088         // virtual bases after the derived members.  This would make a flexible
17089         // array member declared at the end of an object not adjacent to the end
17090         // of the type.
17091         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17092           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17093               << FD->getDeclName() << Record->getTagKind();
17094         if (!getLangOpts().C99)
17095           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17096             << FD->getDeclName() << Record->getTagKind();
17097 
17098         // If the element type has a non-trivial destructor, we would not
17099         // implicitly destroy the elements, so disallow it for now.
17100         //
17101         // FIXME: GCC allows this. We should probably either implicitly delete
17102         // the destructor of the containing class, or just allow this.
17103         QualType BaseElem = Context.getBaseElementType(FD->getType());
17104         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17105           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17106             << FD->getDeclName() << FD->getType();
17107           FD->setInvalidDecl();
17108           EnclosingDecl->setInvalidDecl();
17109           continue;
17110         }
17111         // Okay, we have a legal flexible array member at the end of the struct.
17112         Record->setHasFlexibleArrayMember(true);
17113       } else {
17114         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17115         // unless they are followed by another ivar. That check is done
17116         // elsewhere, after synthesized ivars are known.
17117       }
17118     } else if (!FDTy->isDependentType() &&
17119                RequireCompleteSizedType(
17120                    FD->getLocation(), FD->getType(),
17121                    diag::err_field_incomplete_or_sizeless)) {
17122       // Incomplete type
17123       FD->setInvalidDecl();
17124       EnclosingDecl->setInvalidDecl();
17125       continue;
17126     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17127       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17128         // A type which contains a flexible array member is considered to be a
17129         // flexible array member.
17130         Record->setHasFlexibleArrayMember(true);
17131         if (!Record->isUnion()) {
17132           // If this is a struct/class and this is not the last element, reject
17133           // it.  Note that GCC supports variable sized arrays in the middle of
17134           // structures.
17135           if (!IsLastField)
17136             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17137               << FD->getDeclName() << FD->getType();
17138           else {
17139             // We support flexible arrays at the end of structs in
17140             // other structs as an extension.
17141             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17142               << FD->getDeclName();
17143           }
17144         }
17145       }
17146       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17147           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17148                                  diag::err_abstract_type_in_decl,
17149                                  AbstractIvarType)) {
17150         // Ivars can not have abstract class types
17151         FD->setInvalidDecl();
17152       }
17153       if (Record && FDTTy->getDecl()->hasObjectMember())
17154         Record->setHasObjectMember(true);
17155       if (Record && FDTTy->getDecl()->hasVolatileMember())
17156         Record->setHasVolatileMember(true);
17157     } else if (FDTy->isObjCObjectType()) {
17158       /// A field cannot be an Objective-c object
17159       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17160         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17161       QualType T = Context.getObjCObjectPointerType(FD->getType());
17162       FD->setType(T);
17163     } else if (Record && Record->isUnion() &&
17164                FD->getType().hasNonTrivialObjCLifetime() &&
17165                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17166                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17167                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17168                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17169       // For backward compatibility, fields of C unions declared in system
17170       // headers that have non-trivial ObjC ownership qualifications are marked
17171       // as unavailable unless the qualifier is explicit and __strong. This can
17172       // break ABI compatibility between programs compiled with ARC and MRR, but
17173       // is a better option than rejecting programs using those unions under
17174       // ARC.
17175       FD->addAttr(UnavailableAttr::CreateImplicit(
17176           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17177           FD->getLocation()));
17178     } else if (getLangOpts().ObjC &&
17179                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17180                !Record->hasObjectMember()) {
17181       if (FD->getType()->isObjCObjectPointerType() ||
17182           FD->getType().isObjCGCStrong())
17183         Record->setHasObjectMember(true);
17184       else if (Context.getAsArrayType(FD->getType())) {
17185         QualType BaseType = Context.getBaseElementType(FD->getType());
17186         if (BaseType->isRecordType() &&
17187             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17188           Record->setHasObjectMember(true);
17189         else if (BaseType->isObjCObjectPointerType() ||
17190                  BaseType.isObjCGCStrong())
17191                Record->setHasObjectMember(true);
17192       }
17193     }
17194 
17195     if (Record && !getLangOpts().CPlusPlus &&
17196         !shouldIgnoreForRecordTriviality(FD)) {
17197       QualType FT = FD->getType();
17198       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17199         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17200         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17201             Record->isUnion())
17202           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17203       }
17204       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17205       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17206         Record->setNonTrivialToPrimitiveCopy(true);
17207         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17208           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17209       }
17210       if (FT.isDestructedType()) {
17211         Record->setNonTrivialToPrimitiveDestroy(true);
17212         Record->setParamDestroyedInCallee(true);
17213         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17214           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17215       }
17216 
17217       if (const auto *RT = FT->getAs<RecordType>()) {
17218         if (RT->getDecl()->getArgPassingRestrictions() ==
17219             RecordDecl::APK_CanNeverPassInRegs)
17220           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17221       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17222         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17223     }
17224 
17225     if (Record && FD->getType().isVolatileQualified())
17226       Record->setHasVolatileMember(true);
17227     // Keep track of the number of named members.
17228     if (FD->getIdentifier())
17229       ++NumNamedMembers;
17230   }
17231 
17232   // Okay, we successfully defined 'Record'.
17233   if (Record) {
17234     bool Completed = false;
17235     if (CXXRecord) {
17236       if (!CXXRecord->isInvalidDecl()) {
17237         // Set access bits correctly on the directly-declared conversions.
17238         for (CXXRecordDecl::conversion_iterator
17239                I = CXXRecord->conversion_begin(),
17240                E = CXXRecord->conversion_end(); I != E; ++I)
17241           I.setAccess((*I)->getAccess());
17242       }
17243 
17244       // Add any implicitly-declared members to this class.
17245       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17246 
17247       if (!CXXRecord->isDependentType()) {
17248         if (!CXXRecord->isInvalidDecl()) {
17249           // If we have virtual base classes, we may end up finding multiple
17250           // final overriders for a given virtual function. Check for this
17251           // problem now.
17252           if (CXXRecord->getNumVBases()) {
17253             CXXFinalOverriderMap FinalOverriders;
17254             CXXRecord->getFinalOverriders(FinalOverriders);
17255 
17256             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17257                                              MEnd = FinalOverriders.end();
17258                  M != MEnd; ++M) {
17259               for (OverridingMethods::iterator SO = M->second.begin(),
17260                                             SOEnd = M->second.end();
17261                    SO != SOEnd; ++SO) {
17262                 assert(SO->second.size() > 0 &&
17263                        "Virtual function without overriding functions?");
17264                 if (SO->second.size() == 1)
17265                   continue;
17266 
17267                 // C++ [class.virtual]p2:
17268                 //   In a derived class, if a virtual member function of a base
17269                 //   class subobject has more than one final overrider the
17270                 //   program is ill-formed.
17271                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17272                   << (const NamedDecl *)M->first << Record;
17273                 Diag(M->first->getLocation(),
17274                      diag::note_overridden_virtual_function);
17275                 for (OverridingMethods::overriding_iterator
17276                           OM = SO->second.begin(),
17277                        OMEnd = SO->second.end();
17278                      OM != OMEnd; ++OM)
17279                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17280                     << (const NamedDecl *)M->first << OM->Method->getParent();
17281 
17282                 Record->setInvalidDecl();
17283               }
17284             }
17285             CXXRecord->completeDefinition(&FinalOverriders);
17286             Completed = true;
17287           }
17288         }
17289       }
17290     }
17291 
17292     if (!Completed)
17293       Record->completeDefinition();
17294 
17295     // Handle attributes before checking the layout.
17296     ProcessDeclAttributeList(S, Record, Attrs);
17297 
17298     // We may have deferred checking for a deleted destructor. Check now.
17299     if (CXXRecord) {
17300       auto *Dtor = CXXRecord->getDestructor();
17301       if (Dtor && Dtor->isImplicit() &&
17302           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17303         CXXRecord->setImplicitDestructorIsDeleted();
17304         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17305       }
17306     }
17307 
17308     if (Record->hasAttrs()) {
17309       CheckAlignasUnderalignment(Record);
17310 
17311       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17312         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17313                                            IA->getRange(), IA->getBestCase(),
17314                                            IA->getInheritanceModel());
17315     }
17316 
17317     // Check if the structure/union declaration is a type that can have zero
17318     // size in C. For C this is a language extension, for C++ it may cause
17319     // compatibility problems.
17320     bool CheckForZeroSize;
17321     if (!getLangOpts().CPlusPlus) {
17322       CheckForZeroSize = true;
17323     } else {
17324       // For C++ filter out types that cannot be referenced in C code.
17325       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17326       CheckForZeroSize =
17327           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17328           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17329           CXXRecord->isCLike();
17330     }
17331     if (CheckForZeroSize) {
17332       bool ZeroSize = true;
17333       bool IsEmpty = true;
17334       unsigned NonBitFields = 0;
17335       for (RecordDecl::field_iterator I = Record->field_begin(),
17336                                       E = Record->field_end();
17337            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17338         IsEmpty = false;
17339         if (I->isUnnamedBitfield()) {
17340           if (!I->isZeroLengthBitField(Context))
17341             ZeroSize = false;
17342         } else {
17343           ++NonBitFields;
17344           QualType FieldType = I->getType();
17345           if (FieldType->isIncompleteType() ||
17346               !Context.getTypeSizeInChars(FieldType).isZero())
17347             ZeroSize = false;
17348         }
17349       }
17350 
17351       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17352       // allowed in C++, but warn if its declaration is inside
17353       // extern "C" block.
17354       if (ZeroSize) {
17355         Diag(RecLoc, getLangOpts().CPlusPlus ?
17356                          diag::warn_zero_size_struct_union_in_extern_c :
17357                          diag::warn_zero_size_struct_union_compat)
17358           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17359       }
17360 
17361       // Structs without named members are extension in C (C99 6.7.2.1p7),
17362       // but are accepted by GCC.
17363       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17364         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17365                                diag::ext_no_named_members_in_struct_union)
17366           << Record->isUnion();
17367       }
17368     }
17369   } else {
17370     ObjCIvarDecl **ClsFields =
17371       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17372     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17373       ID->setEndOfDefinitionLoc(RBrac);
17374       // Add ivar's to class's DeclContext.
17375       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17376         ClsFields[i]->setLexicalDeclContext(ID);
17377         ID->addDecl(ClsFields[i]);
17378       }
17379       // Must enforce the rule that ivars in the base classes may not be
17380       // duplicates.
17381       if (ID->getSuperClass())
17382         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17383     } else if (ObjCImplementationDecl *IMPDecl =
17384                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17385       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17386       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17387         // Ivar declared in @implementation never belongs to the implementation.
17388         // Only it is in implementation's lexical context.
17389         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17390       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17391       IMPDecl->setIvarLBraceLoc(LBrac);
17392       IMPDecl->setIvarRBraceLoc(RBrac);
17393     } else if (ObjCCategoryDecl *CDecl =
17394                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17395       // case of ivars in class extension; all other cases have been
17396       // reported as errors elsewhere.
17397       // FIXME. Class extension does not have a LocEnd field.
17398       // CDecl->setLocEnd(RBrac);
17399       // Add ivar's to class extension's DeclContext.
17400       // Diagnose redeclaration of private ivars.
17401       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17402       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17403         if (IDecl) {
17404           if (const ObjCIvarDecl *ClsIvar =
17405               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17406             Diag(ClsFields[i]->getLocation(),
17407                  diag::err_duplicate_ivar_declaration);
17408             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17409             continue;
17410           }
17411           for (const auto *Ext : IDecl->known_extensions()) {
17412             if (const ObjCIvarDecl *ClsExtIvar
17413                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17414               Diag(ClsFields[i]->getLocation(),
17415                    diag::err_duplicate_ivar_declaration);
17416               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17417               continue;
17418             }
17419           }
17420         }
17421         ClsFields[i]->setLexicalDeclContext(CDecl);
17422         CDecl->addDecl(ClsFields[i]);
17423       }
17424       CDecl->setIvarLBraceLoc(LBrac);
17425       CDecl->setIvarRBraceLoc(RBrac);
17426     }
17427   }
17428 }
17429 
17430 /// Determine whether the given integral value is representable within
17431 /// the given type T.
17432 static bool isRepresentableIntegerValue(ASTContext &Context,
17433                                         llvm::APSInt &Value,
17434                                         QualType T) {
17435   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17436          "Integral type required!");
17437   unsigned BitWidth = Context.getIntWidth(T);
17438 
17439   if (Value.isUnsigned() || Value.isNonNegative()) {
17440     if (T->isSignedIntegerOrEnumerationType())
17441       --BitWidth;
17442     return Value.getActiveBits() <= BitWidth;
17443   }
17444   return Value.getMinSignedBits() <= BitWidth;
17445 }
17446 
17447 // Given an integral type, return the next larger integral type
17448 // (or a NULL type of no such type exists).
17449 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17450   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17451   // enum checking below.
17452   assert((T->isIntegralType(Context) ||
17453          T->isEnumeralType()) && "Integral type required!");
17454   const unsigned NumTypes = 4;
17455   QualType SignedIntegralTypes[NumTypes] = {
17456     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17457   };
17458   QualType UnsignedIntegralTypes[NumTypes] = {
17459     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17460     Context.UnsignedLongLongTy
17461   };
17462 
17463   unsigned BitWidth = Context.getTypeSize(T);
17464   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17465                                                         : UnsignedIntegralTypes;
17466   for (unsigned I = 0; I != NumTypes; ++I)
17467     if (Context.getTypeSize(Types[I]) > BitWidth)
17468       return Types[I];
17469 
17470   return QualType();
17471 }
17472 
17473 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17474                                           EnumConstantDecl *LastEnumConst,
17475                                           SourceLocation IdLoc,
17476                                           IdentifierInfo *Id,
17477                                           Expr *Val) {
17478   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17479   llvm::APSInt EnumVal(IntWidth);
17480   QualType EltTy;
17481 
17482   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17483     Val = nullptr;
17484 
17485   if (Val)
17486     Val = DefaultLvalueConversion(Val).get();
17487 
17488   if (Val) {
17489     if (Enum->isDependentType() || Val->isTypeDependent())
17490       EltTy = Context.DependentTy;
17491     else {
17492       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17493         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17494         // constant-expression in the enumerator-definition shall be a converted
17495         // constant expression of the underlying type.
17496         EltTy = Enum->getIntegerType();
17497         ExprResult Converted =
17498           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17499                                            CCEK_Enumerator);
17500         if (Converted.isInvalid())
17501           Val = nullptr;
17502         else
17503           Val = Converted.get();
17504       } else if (!Val->isValueDependent() &&
17505                  !(Val = VerifyIntegerConstantExpression(Val,
17506                                                          &EnumVal).get())) {
17507         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17508       } else {
17509         if (Enum->isComplete()) {
17510           EltTy = Enum->getIntegerType();
17511 
17512           // In Obj-C and Microsoft mode, require the enumeration value to be
17513           // representable in the underlying type of the enumeration. In C++11,
17514           // we perform a non-narrowing conversion as part of converted constant
17515           // expression checking.
17516           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17517             if (Context.getTargetInfo()
17518                     .getTriple()
17519                     .isWindowsMSVCEnvironment()) {
17520               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17521             } else {
17522               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17523             }
17524           }
17525 
17526           // Cast to the underlying type.
17527           Val = ImpCastExprToType(Val, EltTy,
17528                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17529                                                          : CK_IntegralCast)
17530                     .get();
17531         } else if (getLangOpts().CPlusPlus) {
17532           // C++11 [dcl.enum]p5:
17533           //   If the underlying type is not fixed, the type of each enumerator
17534           //   is the type of its initializing value:
17535           //     - If an initializer is specified for an enumerator, the
17536           //       initializing value has the same type as the expression.
17537           EltTy = Val->getType();
17538         } else {
17539           // C99 6.7.2.2p2:
17540           //   The expression that defines the value of an enumeration constant
17541           //   shall be an integer constant expression that has a value
17542           //   representable as an int.
17543 
17544           // Complain if the value is not representable in an int.
17545           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17546             Diag(IdLoc, diag::ext_enum_value_not_int)
17547               << EnumVal.toString(10) << Val->getSourceRange()
17548               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17549           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17550             // Force the type of the expression to 'int'.
17551             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17552           }
17553           EltTy = Val->getType();
17554         }
17555       }
17556     }
17557   }
17558 
17559   if (!Val) {
17560     if (Enum->isDependentType())
17561       EltTy = Context.DependentTy;
17562     else if (!LastEnumConst) {
17563       // C++0x [dcl.enum]p5:
17564       //   If the underlying type is not fixed, the type of each enumerator
17565       //   is the type of its initializing value:
17566       //     - If no initializer is specified for the first enumerator, the
17567       //       initializing value has an unspecified integral type.
17568       //
17569       // GCC uses 'int' for its unspecified integral type, as does
17570       // C99 6.7.2.2p3.
17571       if (Enum->isFixed()) {
17572         EltTy = Enum->getIntegerType();
17573       }
17574       else {
17575         EltTy = Context.IntTy;
17576       }
17577     } else {
17578       // Assign the last value + 1.
17579       EnumVal = LastEnumConst->getInitVal();
17580       ++EnumVal;
17581       EltTy = LastEnumConst->getType();
17582 
17583       // Check for overflow on increment.
17584       if (EnumVal < LastEnumConst->getInitVal()) {
17585         // C++0x [dcl.enum]p5:
17586         //   If the underlying type is not fixed, the type of each enumerator
17587         //   is the type of its initializing value:
17588         //
17589         //     - Otherwise the type of the initializing value is the same as
17590         //       the type of the initializing value of the preceding enumerator
17591         //       unless the incremented value is not representable in that type,
17592         //       in which case the type is an unspecified integral type
17593         //       sufficient to contain the incremented value. If no such type
17594         //       exists, the program is ill-formed.
17595         QualType T = getNextLargerIntegralType(Context, EltTy);
17596         if (T.isNull() || Enum->isFixed()) {
17597           // There is no integral type larger enough to represent this
17598           // value. Complain, then allow the value to wrap around.
17599           EnumVal = LastEnumConst->getInitVal();
17600           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17601           ++EnumVal;
17602           if (Enum->isFixed())
17603             // When the underlying type is fixed, this is ill-formed.
17604             Diag(IdLoc, diag::err_enumerator_wrapped)
17605               << EnumVal.toString(10)
17606               << EltTy;
17607           else
17608             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17609               << EnumVal.toString(10);
17610         } else {
17611           EltTy = T;
17612         }
17613 
17614         // Retrieve the last enumerator's value, extent that type to the
17615         // type that is supposed to be large enough to represent the incremented
17616         // value, then increment.
17617         EnumVal = LastEnumConst->getInitVal();
17618         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17619         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17620         ++EnumVal;
17621 
17622         // If we're not in C++, diagnose the overflow of enumerator values,
17623         // which in C99 means that the enumerator value is not representable in
17624         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17625         // permits enumerator values that are representable in some larger
17626         // integral type.
17627         if (!getLangOpts().CPlusPlus && !T.isNull())
17628           Diag(IdLoc, diag::warn_enum_value_overflow);
17629       } else if (!getLangOpts().CPlusPlus &&
17630                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17631         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17632         Diag(IdLoc, diag::ext_enum_value_not_int)
17633           << EnumVal.toString(10) << 1;
17634       }
17635     }
17636   }
17637 
17638   if (!EltTy->isDependentType()) {
17639     // Make the enumerator value match the signedness and size of the
17640     // enumerator's type.
17641     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17642     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17643   }
17644 
17645   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17646                                   Val, EnumVal);
17647 }
17648 
17649 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17650                                                 SourceLocation IILoc) {
17651   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17652       !getLangOpts().CPlusPlus)
17653     return SkipBodyInfo();
17654 
17655   // We have an anonymous enum definition. Look up the first enumerator to
17656   // determine if we should merge the definition with an existing one and
17657   // skip the body.
17658   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17659                                          forRedeclarationInCurContext());
17660   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17661   if (!PrevECD)
17662     return SkipBodyInfo();
17663 
17664   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17665   NamedDecl *Hidden;
17666   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17667     SkipBodyInfo Skip;
17668     Skip.Previous = Hidden;
17669     return Skip;
17670   }
17671 
17672   return SkipBodyInfo();
17673 }
17674 
17675 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17676                               SourceLocation IdLoc, IdentifierInfo *Id,
17677                               const ParsedAttributesView &Attrs,
17678                               SourceLocation EqualLoc, Expr *Val) {
17679   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17680   EnumConstantDecl *LastEnumConst =
17681     cast_or_null<EnumConstantDecl>(lastEnumConst);
17682 
17683   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17684   // we find one that is.
17685   S = getNonFieldDeclScope(S);
17686 
17687   // Verify that there isn't already something declared with this name in this
17688   // scope.
17689   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17690   LookupName(R, S);
17691   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17692 
17693   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17694     // Maybe we will complain about the shadowed template parameter.
17695     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17696     // Just pretend that we didn't see the previous declaration.
17697     PrevDecl = nullptr;
17698   }
17699 
17700   // C++ [class.mem]p15:
17701   // If T is the name of a class, then each of the following shall have a name
17702   // different from T:
17703   // - every enumerator of every member of class T that is an unscoped
17704   // enumerated type
17705   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17706     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17707                             DeclarationNameInfo(Id, IdLoc));
17708 
17709   EnumConstantDecl *New =
17710     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17711   if (!New)
17712     return nullptr;
17713 
17714   if (PrevDecl) {
17715     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17716       // Check for other kinds of shadowing not already handled.
17717       CheckShadow(New, PrevDecl, R);
17718     }
17719 
17720     // When in C++, we may get a TagDecl with the same name; in this case the
17721     // enum constant will 'hide' the tag.
17722     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17723            "Received TagDecl when not in C++!");
17724     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17725       if (isa<EnumConstantDecl>(PrevDecl))
17726         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17727       else
17728         Diag(IdLoc, diag::err_redefinition) << Id;
17729       notePreviousDefinition(PrevDecl, IdLoc);
17730       return nullptr;
17731     }
17732   }
17733 
17734   // Process attributes.
17735   ProcessDeclAttributeList(S, New, Attrs);
17736   AddPragmaAttributes(S, New);
17737 
17738   // Register this decl in the current scope stack.
17739   New->setAccess(TheEnumDecl->getAccess());
17740   PushOnScopeChains(New, S);
17741 
17742   ActOnDocumentableDecl(New);
17743 
17744   return New;
17745 }
17746 
17747 // Returns true when the enum initial expression does not trigger the
17748 // duplicate enum warning.  A few common cases are exempted as follows:
17749 // Element2 = Element1
17750 // Element2 = Element1 + 1
17751 // Element2 = Element1 - 1
17752 // Where Element2 and Element1 are from the same enum.
17753 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17754   Expr *InitExpr = ECD->getInitExpr();
17755   if (!InitExpr)
17756     return true;
17757   InitExpr = InitExpr->IgnoreImpCasts();
17758 
17759   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17760     if (!BO->isAdditiveOp())
17761       return true;
17762     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17763     if (!IL)
17764       return true;
17765     if (IL->getValue() != 1)
17766       return true;
17767 
17768     InitExpr = BO->getLHS();
17769   }
17770 
17771   // This checks if the elements are from the same enum.
17772   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17773   if (!DRE)
17774     return true;
17775 
17776   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17777   if (!EnumConstant)
17778     return true;
17779 
17780   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17781       Enum)
17782     return true;
17783 
17784   return false;
17785 }
17786 
17787 // Emits a warning when an element is implicitly set a value that
17788 // a previous element has already been set to.
17789 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17790                                         EnumDecl *Enum, QualType EnumType) {
17791   // Avoid anonymous enums
17792   if (!Enum->getIdentifier())
17793     return;
17794 
17795   // Only check for small enums.
17796   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17797     return;
17798 
17799   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17800     return;
17801 
17802   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17803   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17804 
17805   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17806 
17807   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17808   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17809 
17810   // Use int64_t as a key to avoid needing special handling for map keys.
17811   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17812     llvm::APSInt Val = D->getInitVal();
17813     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17814   };
17815 
17816   DuplicatesVector DupVector;
17817   ValueToVectorMap EnumMap;
17818 
17819   // Populate the EnumMap with all values represented by enum constants without
17820   // an initializer.
17821   for (auto *Element : Elements) {
17822     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17823 
17824     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17825     // this constant.  Skip this enum since it may be ill-formed.
17826     if (!ECD) {
17827       return;
17828     }
17829 
17830     // Constants with initalizers are handled in the next loop.
17831     if (ECD->getInitExpr())
17832       continue;
17833 
17834     // Duplicate values are handled in the next loop.
17835     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17836   }
17837 
17838   if (EnumMap.size() == 0)
17839     return;
17840 
17841   // Create vectors for any values that has duplicates.
17842   for (auto *Element : Elements) {
17843     // The last loop returned if any constant was null.
17844     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17845     if (!ValidDuplicateEnum(ECD, Enum))
17846       continue;
17847 
17848     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17849     if (Iter == EnumMap.end())
17850       continue;
17851 
17852     DeclOrVector& Entry = Iter->second;
17853     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17854       // Ensure constants are different.
17855       if (D == ECD)
17856         continue;
17857 
17858       // Create new vector and push values onto it.
17859       auto Vec = std::make_unique<ECDVector>();
17860       Vec->push_back(D);
17861       Vec->push_back(ECD);
17862 
17863       // Update entry to point to the duplicates vector.
17864       Entry = Vec.get();
17865 
17866       // Store the vector somewhere we can consult later for quick emission of
17867       // diagnostics.
17868       DupVector.emplace_back(std::move(Vec));
17869       continue;
17870     }
17871 
17872     ECDVector *Vec = Entry.get<ECDVector*>();
17873     // Make sure constants are not added more than once.
17874     if (*Vec->begin() == ECD)
17875       continue;
17876 
17877     Vec->push_back(ECD);
17878   }
17879 
17880   // Emit diagnostics.
17881   for (const auto &Vec : DupVector) {
17882     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17883 
17884     // Emit warning for one enum constant.
17885     auto *FirstECD = Vec->front();
17886     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17887       << FirstECD << FirstECD->getInitVal().toString(10)
17888       << FirstECD->getSourceRange();
17889 
17890     // Emit one note for each of the remaining enum constants with
17891     // the same value.
17892     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17893       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17894         << ECD << ECD->getInitVal().toString(10)
17895         << ECD->getSourceRange();
17896   }
17897 }
17898 
17899 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17900                              bool AllowMask) const {
17901   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17902   assert(ED->isCompleteDefinition() && "expected enum definition");
17903 
17904   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17905   llvm::APInt &FlagBits = R.first->second;
17906 
17907   if (R.second) {
17908     for (auto *E : ED->enumerators()) {
17909       const auto &EVal = E->getInitVal();
17910       // Only single-bit enumerators introduce new flag values.
17911       if (EVal.isPowerOf2())
17912         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17913     }
17914   }
17915 
17916   // A value is in a flag enum if either its bits are a subset of the enum's
17917   // flag bits (the first condition) or we are allowing masks and the same is
17918   // true of its complement (the second condition). When masks are allowed, we
17919   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17920   //
17921   // While it's true that any value could be used as a mask, the assumption is
17922   // that a mask will have all of the insignificant bits set. Anything else is
17923   // likely a logic error.
17924   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17925   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17926 }
17927 
17928 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17929                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17930                          const ParsedAttributesView &Attrs) {
17931   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17932   QualType EnumType = Context.getTypeDeclType(Enum);
17933 
17934   ProcessDeclAttributeList(S, Enum, Attrs);
17935 
17936   if (Enum->isDependentType()) {
17937     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17938       EnumConstantDecl *ECD =
17939         cast_or_null<EnumConstantDecl>(Elements[i]);
17940       if (!ECD) continue;
17941 
17942       ECD->setType(EnumType);
17943     }
17944 
17945     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17946     return;
17947   }
17948 
17949   // TODO: If the result value doesn't fit in an int, it must be a long or long
17950   // long value.  ISO C does not support this, but GCC does as an extension,
17951   // emit a warning.
17952   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17953   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17954   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17955 
17956   // Verify that all the values are okay, compute the size of the values, and
17957   // reverse the list.
17958   unsigned NumNegativeBits = 0;
17959   unsigned NumPositiveBits = 0;
17960 
17961   // Keep track of whether all elements have type int.
17962   bool AllElementsInt = true;
17963 
17964   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17965     EnumConstantDecl *ECD =
17966       cast_or_null<EnumConstantDecl>(Elements[i]);
17967     if (!ECD) continue;  // Already issued a diagnostic.
17968 
17969     const llvm::APSInt &InitVal = ECD->getInitVal();
17970 
17971     // Keep track of the size of positive and negative values.
17972     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17973       NumPositiveBits = std::max(NumPositiveBits,
17974                                  (unsigned)InitVal.getActiveBits());
17975     else
17976       NumNegativeBits = std::max(NumNegativeBits,
17977                                  (unsigned)InitVal.getMinSignedBits());
17978 
17979     // Keep track of whether every enum element has type int (very common).
17980     if (AllElementsInt)
17981       AllElementsInt = ECD->getType() == Context.IntTy;
17982   }
17983 
17984   // Figure out the type that should be used for this enum.
17985   QualType BestType;
17986   unsigned BestWidth;
17987 
17988   // C++0x N3000 [conv.prom]p3:
17989   //   An rvalue of an unscoped enumeration type whose underlying
17990   //   type is not fixed can be converted to an rvalue of the first
17991   //   of the following types that can represent all the values of
17992   //   the enumeration: int, unsigned int, long int, unsigned long
17993   //   int, long long int, or unsigned long long int.
17994   // C99 6.4.4.3p2:
17995   //   An identifier declared as an enumeration constant has type int.
17996   // The C99 rule is modified by a gcc extension
17997   QualType BestPromotionType;
17998 
17999   bool Packed = Enum->hasAttr<PackedAttr>();
18000   // -fshort-enums is the equivalent to specifying the packed attribute on all
18001   // enum definitions.
18002   if (LangOpts.ShortEnums)
18003     Packed = true;
18004 
18005   // If the enum already has a type because it is fixed or dictated by the
18006   // target, promote that type instead of analyzing the enumerators.
18007   if (Enum->isComplete()) {
18008     BestType = Enum->getIntegerType();
18009     if (BestType->isPromotableIntegerType())
18010       BestPromotionType = Context.getPromotedIntegerType(BestType);
18011     else
18012       BestPromotionType = BestType;
18013 
18014     BestWidth = Context.getIntWidth(BestType);
18015   }
18016   else if (NumNegativeBits) {
18017     // If there is a negative value, figure out the smallest integer type (of
18018     // int/long/longlong) that fits.
18019     // If it's packed, check also if it fits a char or a short.
18020     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18021       BestType = Context.SignedCharTy;
18022       BestWidth = CharWidth;
18023     } else if (Packed && NumNegativeBits <= ShortWidth &&
18024                NumPositiveBits < ShortWidth) {
18025       BestType = Context.ShortTy;
18026       BestWidth = ShortWidth;
18027     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18028       BestType = Context.IntTy;
18029       BestWidth = IntWidth;
18030     } else {
18031       BestWidth = Context.getTargetInfo().getLongWidth();
18032 
18033       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18034         BestType = Context.LongTy;
18035       } else {
18036         BestWidth = Context.getTargetInfo().getLongLongWidth();
18037 
18038         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18039           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18040         BestType = Context.LongLongTy;
18041       }
18042     }
18043     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18044   } else {
18045     // If there is no negative value, figure out the smallest type that fits
18046     // all of the enumerator values.
18047     // If it's packed, check also if it fits a char or a short.
18048     if (Packed && NumPositiveBits <= CharWidth) {
18049       BestType = Context.UnsignedCharTy;
18050       BestPromotionType = Context.IntTy;
18051       BestWidth = CharWidth;
18052     } else if (Packed && NumPositiveBits <= ShortWidth) {
18053       BestType = Context.UnsignedShortTy;
18054       BestPromotionType = Context.IntTy;
18055       BestWidth = ShortWidth;
18056     } else if (NumPositiveBits <= IntWidth) {
18057       BestType = Context.UnsignedIntTy;
18058       BestWidth = IntWidth;
18059       BestPromotionType
18060         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18061                            ? Context.UnsignedIntTy : Context.IntTy;
18062     } else if (NumPositiveBits <=
18063                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18064       BestType = Context.UnsignedLongTy;
18065       BestPromotionType
18066         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18067                            ? Context.UnsignedLongTy : Context.LongTy;
18068     } else {
18069       BestWidth = Context.getTargetInfo().getLongLongWidth();
18070       assert(NumPositiveBits <= BestWidth &&
18071              "How could an initializer get larger than ULL?");
18072       BestType = Context.UnsignedLongLongTy;
18073       BestPromotionType
18074         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18075                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18076     }
18077   }
18078 
18079   // Loop over all of the enumerator constants, changing their types to match
18080   // the type of the enum if needed.
18081   for (auto *D : Elements) {
18082     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18083     if (!ECD) continue;  // Already issued a diagnostic.
18084 
18085     // Standard C says the enumerators have int type, but we allow, as an
18086     // extension, the enumerators to be larger than int size.  If each
18087     // enumerator value fits in an int, type it as an int, otherwise type it the
18088     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18089     // that X has type 'int', not 'unsigned'.
18090 
18091     // Determine whether the value fits into an int.
18092     llvm::APSInt InitVal = ECD->getInitVal();
18093 
18094     // If it fits into an integer type, force it.  Otherwise force it to match
18095     // the enum decl type.
18096     QualType NewTy;
18097     unsigned NewWidth;
18098     bool NewSign;
18099     if (!getLangOpts().CPlusPlus &&
18100         !Enum->isFixed() &&
18101         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18102       NewTy = Context.IntTy;
18103       NewWidth = IntWidth;
18104       NewSign = true;
18105     } else if (ECD->getType() == BestType) {
18106       // Already the right type!
18107       if (getLangOpts().CPlusPlus)
18108         // C++ [dcl.enum]p4: Following the closing brace of an
18109         // enum-specifier, each enumerator has the type of its
18110         // enumeration.
18111         ECD->setType(EnumType);
18112       continue;
18113     } else {
18114       NewTy = BestType;
18115       NewWidth = BestWidth;
18116       NewSign = BestType->isSignedIntegerOrEnumerationType();
18117     }
18118 
18119     // Adjust the APSInt value.
18120     InitVal = InitVal.extOrTrunc(NewWidth);
18121     InitVal.setIsSigned(NewSign);
18122     ECD->setInitVal(InitVal);
18123 
18124     // Adjust the Expr initializer and type.
18125     if (ECD->getInitExpr() &&
18126         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18127       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
18128                                                 CK_IntegralCast,
18129                                                 ECD->getInitExpr(),
18130                                                 /*base paths*/ nullptr,
18131                                                 VK_RValue));
18132     if (getLangOpts().CPlusPlus)
18133       // C++ [dcl.enum]p4: Following the closing brace of an
18134       // enum-specifier, each enumerator has the type of its
18135       // enumeration.
18136       ECD->setType(EnumType);
18137     else
18138       ECD->setType(NewTy);
18139   }
18140 
18141   Enum->completeDefinition(BestType, BestPromotionType,
18142                            NumPositiveBits, NumNegativeBits);
18143 
18144   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18145 
18146   if (Enum->isClosedFlag()) {
18147     for (Decl *D : Elements) {
18148       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18149       if (!ECD) continue;  // Already issued a diagnostic.
18150 
18151       llvm::APSInt InitVal = ECD->getInitVal();
18152       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18153           !IsValueInFlagEnum(Enum, InitVal, true))
18154         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18155           << ECD << Enum;
18156     }
18157   }
18158 
18159   // Now that the enum type is defined, ensure it's not been underaligned.
18160   if (Enum->hasAttrs())
18161     CheckAlignasUnderalignment(Enum);
18162 }
18163 
18164 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18165                                   SourceLocation StartLoc,
18166                                   SourceLocation EndLoc) {
18167   StringLiteral *AsmString = cast<StringLiteral>(expr);
18168 
18169   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18170                                                    AsmString, StartLoc,
18171                                                    EndLoc);
18172   CurContext->addDecl(New);
18173   return New;
18174 }
18175 
18176 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18177                                       IdentifierInfo* AliasName,
18178                                       SourceLocation PragmaLoc,
18179                                       SourceLocation NameLoc,
18180                                       SourceLocation AliasNameLoc) {
18181   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18182                                          LookupOrdinaryName);
18183   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18184                            AttributeCommonInfo::AS_Pragma);
18185   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18186       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18187 
18188   // If a declaration that:
18189   // 1) declares a function or a variable
18190   // 2) has external linkage
18191   // already exists, add a label attribute to it.
18192   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18193     if (isDeclExternC(PrevDecl))
18194       PrevDecl->addAttr(Attr);
18195     else
18196       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18197           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18198   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18199   } else
18200     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18201 }
18202 
18203 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18204                              SourceLocation PragmaLoc,
18205                              SourceLocation NameLoc) {
18206   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18207 
18208   if (PrevDecl) {
18209     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18210   } else {
18211     (void)WeakUndeclaredIdentifiers.insert(
18212       std::pair<IdentifierInfo*,WeakInfo>
18213         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18214   }
18215 }
18216 
18217 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18218                                 IdentifierInfo* AliasName,
18219                                 SourceLocation PragmaLoc,
18220                                 SourceLocation NameLoc,
18221                                 SourceLocation AliasNameLoc) {
18222   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18223                                     LookupOrdinaryName);
18224   WeakInfo W = WeakInfo(Name, NameLoc);
18225 
18226   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18227     if (!PrevDecl->hasAttr<AliasAttr>())
18228       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18229         DeclApplyPragmaWeak(TUScope, ND, W);
18230   } else {
18231     (void)WeakUndeclaredIdentifiers.insert(
18232       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18233   }
18234 }
18235 
18236 Decl *Sema::getObjCDeclContext() const {
18237   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18238 }
18239 
18240 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18241                                                      bool Final) {
18242   // SYCL functions can be template, so we check if they have appropriate
18243   // attribute prior to checking if it is a template.
18244   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18245     return FunctionEmissionStatus::Emitted;
18246 
18247   // Templates are emitted when they're instantiated.
18248   if (FD->isDependentContext())
18249     return FunctionEmissionStatus::TemplateDiscarded;
18250 
18251   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18252   if (LangOpts.OpenMPIsDevice) {
18253     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18254         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18255     if (DevTy.hasValue()) {
18256       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18257         OMPES = FunctionEmissionStatus::OMPDiscarded;
18258       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18259                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18260         OMPES = FunctionEmissionStatus::Emitted;
18261       }
18262     }
18263   } else if (LangOpts.OpenMP) {
18264     // In OpenMP 4.5 all the functions are host functions.
18265     if (LangOpts.OpenMP <= 45) {
18266       OMPES = FunctionEmissionStatus::Emitted;
18267     } else {
18268       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18269           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18270       // In OpenMP 5.0 or above, DevTy may be changed later by
18271       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18272       // having no value does not imply host. The emission status will be
18273       // checked again at the end of compilation unit.
18274       if (DevTy.hasValue()) {
18275         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18276           OMPES = FunctionEmissionStatus::OMPDiscarded;
18277         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18278                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18279           OMPES = FunctionEmissionStatus::Emitted;
18280       } else if (Final)
18281         OMPES = FunctionEmissionStatus::Emitted;
18282     }
18283   }
18284   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18285       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18286     return OMPES;
18287 
18288   if (LangOpts.CUDA) {
18289     // When compiling for device, host functions are never emitted.  Similarly,
18290     // when compiling for host, device and global functions are never emitted.
18291     // (Technically, we do emit a host-side stub for global functions, but this
18292     // doesn't count for our purposes here.)
18293     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18294     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18295       return FunctionEmissionStatus::CUDADiscarded;
18296     if (!LangOpts.CUDAIsDevice &&
18297         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18298       return FunctionEmissionStatus::CUDADiscarded;
18299 
18300     // Check whether this function is externally visible -- if so, it's
18301     // known-emitted.
18302     //
18303     // We have to check the GVA linkage of the function's *definition* -- if we
18304     // only have a declaration, we don't know whether or not the function will
18305     // be emitted, because (say) the definition could include "inline".
18306     FunctionDecl *Def = FD->getDefinition();
18307 
18308     if (Def &&
18309         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18310         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18311       return FunctionEmissionStatus::Emitted;
18312   }
18313 
18314   // Otherwise, the function is known-emitted if it's in our set of
18315   // known-emitted functions.
18316   return FunctionEmissionStatus::Unknown;
18317 }
18318 
18319 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18320   // Host-side references to a __global__ function refer to the stub, so the
18321   // function itself is never emitted and therefore should not be marked.
18322   // If we have host fn calls kernel fn calls host+device, the HD function
18323   // does not get instantiated on the host. We model this by omitting at the
18324   // call to the kernel from the callgraph. This ensures that, when compiling
18325   // for host, only HD functions actually called from the host get marked as
18326   // known-emitted.
18327   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18328          IdentifyCUDATarget(Callee) == CFT_Global;
18329 }
18330