1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439         if (!IIDecl || (*Res)->getLocation() < IIDecl->getLocation())
440           IIDecl = *Res;
441       }
442     }
443 
444     if (!IIDecl) {
445       // None of the entities we found is a type, so there is no way
446       // to even assume that the result is a type. In this case, don't
447       // complain about the ambiguity. The parser will either try to
448       // perform this lookup again (e.g., as an object name), which
449       // will produce the ambiguity, or will complain that it expected
450       // a type name.
451       Result.suppressDiagnostics();
452       return nullptr;
453     }
454 
455     // We found a type within the ambiguous lookup; diagnose the
456     // ambiguity and then return that type. This might be the right
457     // answer, or it might not be, but it suppresses any attempt to
458     // perform the name lookup again.
459     break;
460 
461   case LookupResult::Found:
462     IIDecl = Result.getFoundDecl();
463     break;
464   }
465 
466   assert(IIDecl && "Didn't find decl");
467 
468   QualType T;
469   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470     // C++ [class.qual]p2: A lookup that would find the injected-class-name
471     // instead names the constructors of the class, except when naming a class.
472     // This is ill-formed when we're not actually forming a ctor or dtor name.
473     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476         FoundRD->isInjectedClassName() &&
477         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479           << &II << /*Type*/1;
480 
481     DiagnoseUseOfDecl(IIDecl, NameLoc);
482 
483     T = Context.getTypeDeclType(TD);
484     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487     if (!HasTrailingDot)
488       T = Context.getObjCInterfaceType(IDecl);
489   } else if (AllowDeducedTemplate) {
490     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492                                                        QualType(), false);
493   }
494 
495   if (T.isNull()) {
496     // If it's not plausibly a type, suppress diagnostics.
497     Result.suppressDiagnostics();
498     return nullptr;
499   }
500 
501   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502   // constructor or destructor name (in such a case, the scope specifier
503   // will be attached to the enclosing Expr or Decl node).
504   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505       !isa<ObjCInterfaceDecl>(IIDecl)) {
506     if (WantNontrivialTypeSourceInfo) {
507       // Construct a type with type-source information.
508       TypeLocBuilder Builder;
509       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510 
511       T = getElaboratedType(ETK_None, *SS, T);
512       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513       ElabTL.setElaboratedKeywordLoc(SourceLocation());
514       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516     } else {
517       T = getElaboratedType(ETK_None, *SS, T);
518     }
519   }
520 
521   return ParsedType::make(T);
522 }
523 
524 // Builds a fake NNS for the given decl context.
525 static NestedNameSpecifier *
526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527   for (;; DC = DC->getLookupParent()) {
528     DC = DC->getPrimaryContext();
529     auto *ND = dyn_cast<NamespaceDecl>(DC);
530     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531       return NestedNameSpecifier::Create(Context, nullptr, ND);
532     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534                                          RD->getTypeForDecl());
535     else if (isa<TranslationUnitDecl>(DC))
536       return NestedNameSpecifier::GlobalSpecifier(Context);
537   }
538   llvm_unreachable("something isn't in TU scope?");
539 }
540 
541 /// Find the parent class with dependent bases of the innermost enclosing method
542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543 /// up allowing unqualified dependent type names at class-level, which MSVC
544 /// correctly rejects.
545 static const CXXRecordDecl *
546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548     DC = DC->getPrimaryContext();
549     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550       if (MD->getParent()->hasAnyDependentBases())
551         return MD->getParent();
552   }
553   return nullptr;
554 }
555 
556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557                                           SourceLocation NameLoc,
558                                           bool IsTemplateTypeArg) {
559   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
560 
561   NestedNameSpecifier *NNS = nullptr;
562   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563     // If we weren't able to parse a default template argument, delay lookup
564     // until instantiation time by making a non-dependent DependentTypeName. We
565     // pretend we saw a NestedNameSpecifier referring to the current scope, and
566     // lookup is retried.
567     // FIXME: This hurts our diagnostic quality, since we get errors like "no
568     // type named 'Foo' in 'current_namespace'" when the user didn't write any
569     // name specifiers.
570     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572   } else if (const CXXRecordDecl *RD =
573                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574     // Build a DependentNameType that will perform lookup into RD at
575     // instantiation time.
576     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577                                       RD->getTypeForDecl());
578 
579     // Diagnose that this identifier was undeclared, and retry the lookup during
580     // template instantiation.
581     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582                                                                       << RD;
583   } else {
584     // This is not a situation that we should recover from.
585     return ParsedType();
586   }
587 
588   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589 
590   // Build type location information.  We synthesized the qualifier, so we have
591   // to build a fake NestedNameSpecifierLoc.
592   NestedNameSpecifierLocBuilder NNSLocBuilder;
593   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595 
596   TypeLocBuilder Builder;
597   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598   DepTL.setNameLoc(NameLoc);
599   DepTL.setElaboratedKeywordLoc(SourceLocation());
600   DepTL.setQualifierLoc(QualifierLoc);
601   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602 }
603 
604 /// isTagName() - This method is called *for error recovery purposes only*
605 /// to determine if the specified name is a valid tag name ("struct foo").  If
606 /// so, this returns the TST for the tag corresponding to it (TST_enum,
607 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
608 /// cases in C where the user forgot to specify the tag.
609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610   // Do a tag name lookup in this scope.
611   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612   LookupName(R, S, false);
613   R.suppressDiagnostics();
614   if (R.getResultKind() == LookupResult::Found)
615     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616       switch (TD->getTagKind()) {
617       case TTK_Struct: return DeclSpec::TST_struct;
618       case TTK_Interface: return DeclSpec::TST_interface;
619       case TTK_Union:  return DeclSpec::TST_union;
620       case TTK_Class:  return DeclSpec::TST_class;
621       case TTK_Enum:   return DeclSpec::TST_enum;
622       }
623     }
624 
625   return DeclSpec::TST_unspecified;
626 }
627 
628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
630 /// then downgrade the missing typename error to a warning.
631 /// This is needed for MSVC compatibility; Example:
632 /// @code
633 /// template<class T> class A {
634 /// public:
635 ///   typedef int TYPE;
636 /// };
637 /// template<class T> class B : public A<T> {
638 /// public:
639 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
640 /// };
641 /// @endcode
642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643   if (CurContext->isRecord()) {
644     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645       return true;
646 
647     const Type *Ty = SS->getScopeRep()->getAsType();
648 
649     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650     for (const auto &Base : RD->bases())
651       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
652         return true;
653     return S->isFunctionPrototypeScope();
654   }
655   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
656 }
657 
658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659                                    SourceLocation IILoc,
660                                    Scope *S,
661                                    CXXScopeSpec *SS,
662                                    ParsedType &SuggestedType,
663                                    bool IsTemplateName) {
664   // Don't report typename errors for editor placeholders.
665   if (II->isEditorPlaceholder())
666     return;
667   // We don't have anything to suggest (yet).
668   SuggestedType = nullptr;
669 
670   // There may have been a typo in the name of the type. Look up typo
671   // results, in case we have something that we can suggest.
672   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673                            /*AllowTemplates=*/IsTemplateName,
674                            /*AllowNonTemplates=*/!IsTemplateName);
675   if (TypoCorrection Corrected =
676           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677                       CCC, CTK_ErrorRecovery)) {
678     // FIXME: Support error recovery for the template-name case.
679     bool CanRecover = !IsTemplateName;
680     if (Corrected.isKeyword()) {
681       // We corrected to a keyword.
682       diagnoseTypo(Corrected,
683                    PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                         : diag::err_unknown_typename_suggest)
685                        << II);
686       II = Corrected.getCorrectionAsIdentifierInfo();
687     } else {
688       // We found a similarly-named type or interface; suggest that.
689       if (!SS || !SS->isSet()) {
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName ? diag::err_no_template_suggest
692                                           : diag::err_unknown_typename_suggest)
693                          << II, CanRecover);
694       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697                                 II->getName().equals(CorrectedStr);
698         diagnoseTypo(Corrected,
699                      PDiag(IsTemplateName
700                                ? diag::err_no_member_template_suggest
701                                : diag::err_unknown_nested_typename_suggest)
702                          << II << DC << DroppedSpecifier << SS->getRange(),
703                      CanRecover);
704       } else {
705         llvm_unreachable("could not have corrected a typo here");
706       }
707 
708       if (!CanRecover)
709         return;
710 
711       CXXScopeSpec tmpSS;
712       if (Corrected.getCorrectionSpecifier())
713         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714                           SourceRange(IILoc));
715       // FIXME: Support class template argument deduction here.
716       SuggestedType =
717           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719                       /*IsCtorOrDtorName=*/false,
720                       /*WantNontrivialTypeSourceInfo=*/true);
721     }
722     return;
723   }
724 
725   if (getLangOpts().CPlusPlus && !IsTemplateName) {
726     // See if II is a class template that the user forgot to pass arguments to.
727     UnqualifiedId Name;
728     Name.setIdentifier(II, IILoc);
729     CXXScopeSpec EmptySS;
730     TemplateTy TemplateResult;
731     bool MemberOfUnknownSpecialization;
732     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733                        Name, nullptr, true, TemplateResult,
734                        MemberOfUnknownSpecialization) == TNK_Type_template) {
735       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736       return;
737     }
738   }
739 
740   // FIXME: Should we move the logic that tries to recover from a missing tag
741   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742 
743   if (!SS || (!SS->isSet() && !SS->isInvalid()))
744     Diag(IILoc, IsTemplateName ? diag::err_no_template
745                                : diag::err_unknown_typename)
746         << II;
747   else if (DeclContext *DC = computeDeclContext(*SS, false))
748     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749                                : diag::err_typename_nested_not_found)
750         << II << DC << SS->getRange();
751   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
752     SuggestedType =
753         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
754   } else if (isDependentScopeSpecifier(*SS)) {
755     unsigned DiagID = diag::err_typename_missing;
756     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
757       DiagID = diag::ext_typename_missing;
758 
759     Diag(SS->getRange().getBegin(), DiagID)
760       << SS->getScopeRep() << II->getName()
761       << SourceRange(SS->getRange().getBegin(), IILoc)
762       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
763     SuggestedType = ActOnTypenameType(S, SourceLocation(),
764                                       *SS, *II, IILoc).get();
765   } else {
766     assert(SS && SS->isInvalid() &&
767            "Invalid scope specifier has already been diagnosed");
768   }
769 }
770 
771 /// Determine whether the given result set contains either a type name
772 /// or
773 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
774   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
775                        NextToken.is(tok::less);
776 
777   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
778     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
779       return true;
780 
781     if (CheckTemplate && isa<TemplateDecl>(*I))
782       return true;
783   }
784 
785   return false;
786 }
787 
788 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
789                                     Scope *S, CXXScopeSpec &SS,
790                                     IdentifierInfo *&Name,
791                                     SourceLocation NameLoc) {
792   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
793   SemaRef.LookupParsedName(R, S, &SS);
794   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
795     StringRef FixItTagName;
796     switch (Tag->getTagKind()) {
797       case TTK_Class:
798         FixItTagName = "class ";
799         break;
800 
801       case TTK_Enum:
802         FixItTagName = "enum ";
803         break;
804 
805       case TTK_Struct:
806         FixItTagName = "struct ";
807         break;
808 
809       case TTK_Interface:
810         FixItTagName = "__interface ";
811         break;
812 
813       case TTK_Union:
814         FixItTagName = "union ";
815         break;
816     }
817 
818     StringRef TagName = FixItTagName.drop_back();
819     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
820       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
821       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
822 
823     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
824          I != IEnd; ++I)
825       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
826         << Name << TagName;
827 
828     // Replace lookup results with just the tag decl.
829     Result.clear(Sema::LookupTagName);
830     SemaRef.LookupParsedName(Result, S, &SS);
831     return true;
832   }
833 
834   return false;
835 }
836 
837 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
838 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
839                                   QualType T, SourceLocation NameLoc) {
840   ASTContext &Context = S.Context;
841 
842   TypeLocBuilder Builder;
843   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
844 
845   T = S.getElaboratedType(ETK_None, SS, T);
846   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
847   ElabTL.setElaboratedKeywordLoc(SourceLocation());
848   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
849   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
850 }
851 
852 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
853                                             IdentifierInfo *&Name,
854                                             SourceLocation NameLoc,
855                                             const Token &NextToken,
856                                             CorrectionCandidateCallback *CCC) {
857   DeclarationNameInfo NameInfo(Name, NameLoc);
858   ObjCMethodDecl *CurMethod = getCurMethodDecl();
859 
860   assert(NextToken.isNot(tok::coloncolon) &&
861          "parse nested name specifiers before calling ClassifyName");
862   if (getLangOpts().CPlusPlus && SS.isSet() &&
863       isCurrentClassName(*Name, S, &SS)) {
864     // Per [class.qual]p2, this names the constructors of SS, not the
865     // injected-class-name. We don't have a classification for that.
866     // There's not much point caching this result, since the parser
867     // will reject it later.
868     return NameClassification::Unknown();
869   }
870 
871   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
872   LookupParsedName(Result, S, &SS, !CurMethod);
873 
874   if (SS.isInvalid())
875     return NameClassification::Error();
876 
877   // For unqualified lookup in a class template in MSVC mode, look into
878   // dependent base classes where the primary class template is known.
879   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
880     if (ParsedType TypeInBase =
881             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
882       return TypeInBase;
883   }
884 
885   // Perform lookup for Objective-C instance variables (including automatically
886   // synthesized instance variables), if we're in an Objective-C method.
887   // FIXME: This lookup really, really needs to be folded in to the normal
888   // unqualified lookup mechanism.
889   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
890     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
891     if (Ivar.isInvalid())
892       return NameClassification::Error();
893     if (Ivar.isUsable())
894       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
895 
896     // We defer builtin creation until after ivar lookup inside ObjC methods.
897     if (Result.empty())
898       LookupBuiltin(Result);
899   }
900 
901   bool SecondTry = false;
902   bool IsFilteredTemplateName = false;
903 
904 Corrected:
905   switch (Result.getResultKind()) {
906   case LookupResult::NotFound:
907     // If an unqualified-id is followed by a '(', then we have a function
908     // call.
909     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
910       // In C++, this is an ADL-only call.
911       // FIXME: Reference?
912       if (getLangOpts().CPlusPlus)
913         return NameClassification::UndeclaredNonType();
914 
915       // C90 6.3.2.2:
916       //   If the expression that precedes the parenthesized argument list in a
917       //   function call consists solely of an identifier, and if no
918       //   declaration is visible for this identifier, the identifier is
919       //   implicitly declared exactly as if, in the innermost block containing
920       //   the function call, the declaration
921       //
922       //     extern int identifier ();
923       //
924       //   appeared.
925       //
926       // We also allow this in C99 as an extension.
927       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
928         return NameClassification::NonType(D);
929     }
930 
931     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
932       // In C++20 onwards, this could be an ADL-only call to a function
933       // template, and we're required to assume that this is a template name.
934       //
935       // FIXME: Find a way to still do typo correction in this case.
936       TemplateName Template =
937           Context.getAssumedTemplateName(NameInfo.getName());
938       return NameClassification::UndeclaredTemplate(Template);
939     }
940 
941     // In C, we first see whether there is a tag type by the same name, in
942     // which case it's likely that the user just forgot to write "enum",
943     // "struct", or "union".
944     if (!getLangOpts().CPlusPlus && !SecondTry &&
945         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
946       break;
947     }
948 
949     // Perform typo correction to determine if there is another name that is
950     // close to this name.
951     if (!SecondTry && CCC) {
952       SecondTry = true;
953       if (TypoCorrection Corrected =
954               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
955                           &SS, *CCC, CTK_ErrorRecovery)) {
956         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
957         unsigned QualifiedDiag = diag::err_no_member_suggest;
958 
959         NamedDecl *FirstDecl = Corrected.getFoundDecl();
960         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
961         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
962             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
963           UnqualifiedDiag = diag::err_no_template_suggest;
964           QualifiedDiag = diag::err_no_member_template_suggest;
965         } else if (UnderlyingFirstDecl &&
966                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
967                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
968                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
969           UnqualifiedDiag = diag::err_unknown_typename_suggest;
970           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
971         }
972 
973         if (SS.isEmpty()) {
974           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
975         } else {// FIXME: is this even reachable? Test it.
976           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
977           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
978                                   Name->getName().equals(CorrectedStr);
979           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
980                                     << Name << computeDeclContext(SS, false)
981                                     << DroppedSpecifier << SS.getRange());
982         }
983 
984         // Update the name, so that the caller has the new name.
985         Name = Corrected.getCorrectionAsIdentifierInfo();
986 
987         // Typo correction corrected to a keyword.
988         if (Corrected.isKeyword())
989           return Name;
990 
991         // Also update the LookupResult...
992         // FIXME: This should probably go away at some point
993         Result.clear();
994         Result.setLookupName(Corrected.getCorrection());
995         if (FirstDecl)
996           Result.addDecl(FirstDecl);
997 
998         // If we found an Objective-C instance variable, let
999         // LookupInObjCMethod build the appropriate expression to
1000         // reference the ivar.
1001         // FIXME: This is a gross hack.
1002         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1003           DeclResult R =
1004               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1005           if (R.isInvalid())
1006             return NameClassification::Error();
1007           if (R.isUsable())
1008             return NameClassification::NonType(Ivar);
1009         }
1010 
1011         goto Corrected;
1012       }
1013     }
1014 
1015     // We failed to correct; just fall through and let the parser deal with it.
1016     Result.suppressDiagnostics();
1017     return NameClassification::Unknown();
1018 
1019   case LookupResult::NotFoundInCurrentInstantiation: {
1020     // We performed name lookup into the current instantiation, and there were
1021     // dependent bases, so we treat this result the same way as any other
1022     // dependent nested-name-specifier.
1023 
1024     // C++ [temp.res]p2:
1025     //   A name used in a template declaration or definition and that is
1026     //   dependent on a template-parameter is assumed not to name a type
1027     //   unless the applicable name lookup finds a type name or the name is
1028     //   qualified by the keyword typename.
1029     //
1030     // FIXME: If the next token is '<', we might want to ask the parser to
1031     // perform some heroics to see if we actually have a
1032     // template-argument-list, which would indicate a missing 'template'
1033     // keyword here.
1034     return NameClassification::DependentNonType();
1035   }
1036 
1037   case LookupResult::Found:
1038   case LookupResult::FoundOverloaded:
1039   case LookupResult::FoundUnresolvedValue:
1040     break;
1041 
1042   case LookupResult::Ambiguous:
1043     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1044         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1045                                       /*AllowDependent=*/false)) {
1046       // C++ [temp.local]p3:
1047       //   A lookup that finds an injected-class-name (10.2) can result in an
1048       //   ambiguity in certain cases (for example, if it is found in more than
1049       //   one base class). If all of the injected-class-names that are found
1050       //   refer to specializations of the same class template, and if the name
1051       //   is followed by a template-argument-list, the reference refers to the
1052       //   class template itself and not a specialization thereof, and is not
1053       //   ambiguous.
1054       //
1055       // This filtering can make an ambiguous result into an unambiguous one,
1056       // so try again after filtering out template names.
1057       FilterAcceptableTemplateNames(Result);
1058       if (!Result.isAmbiguous()) {
1059         IsFilteredTemplateName = true;
1060         break;
1061       }
1062     }
1063 
1064     // Diagnose the ambiguity and return an error.
1065     return NameClassification::Error();
1066   }
1067 
1068   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1069       (IsFilteredTemplateName ||
1070        hasAnyAcceptableTemplateNames(
1071            Result, /*AllowFunctionTemplates=*/true,
1072            /*AllowDependent=*/false,
1073            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1074                getLangOpts().CPlusPlus20))) {
1075     // C++ [temp.names]p3:
1076     //   After name lookup (3.4) finds that a name is a template-name or that
1077     //   an operator-function-id or a literal- operator-id refers to a set of
1078     //   overloaded functions any member of which is a function template if
1079     //   this is followed by a <, the < is always taken as the delimiter of a
1080     //   template-argument-list and never as the less-than operator.
1081     // C++2a [temp.names]p2:
1082     //   A name is also considered to refer to a template if it is an
1083     //   unqualified-id followed by a < and name lookup finds either one
1084     //   or more functions or finds nothing.
1085     if (!IsFilteredTemplateName)
1086       FilterAcceptableTemplateNames(Result);
1087 
1088     bool IsFunctionTemplate;
1089     bool IsVarTemplate;
1090     TemplateName Template;
1091     if (Result.end() - Result.begin() > 1) {
1092       IsFunctionTemplate = true;
1093       Template = Context.getOverloadedTemplateName(Result.begin(),
1094                                                    Result.end());
1095     } else if (!Result.empty()) {
1096       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1097           *Result.begin(), /*AllowFunctionTemplates=*/true,
1098           /*AllowDependent=*/false));
1099       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1100       IsVarTemplate = isa<VarTemplateDecl>(TD);
1101 
1102       if (SS.isNotEmpty())
1103         Template =
1104             Context.getQualifiedTemplateName(SS.getScopeRep(),
1105                                              /*TemplateKeyword=*/false, TD);
1106       else
1107         Template = TemplateName(TD);
1108     } else {
1109       // All results were non-template functions. This is a function template
1110       // name.
1111       IsFunctionTemplate = true;
1112       Template = Context.getAssumedTemplateName(NameInfo.getName());
1113     }
1114 
1115     if (IsFunctionTemplate) {
1116       // Function templates always go through overload resolution, at which
1117       // point we'll perform the various checks (e.g., accessibility) we need
1118       // to based on which function we selected.
1119       Result.suppressDiagnostics();
1120 
1121       return NameClassification::FunctionTemplate(Template);
1122     }
1123 
1124     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1125                          : NameClassification::TypeTemplate(Template);
1126   }
1127 
1128   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1129   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1130     DiagnoseUseOfDecl(Type, NameLoc);
1131     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1132     QualType T = Context.getTypeDeclType(Type);
1133     if (SS.isNotEmpty())
1134       return buildNestedType(*this, SS, T, NameLoc);
1135     return ParsedType::make(T);
1136   }
1137 
1138   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1139   if (!Class) {
1140     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1141     if (ObjCCompatibleAliasDecl *Alias =
1142             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1143       Class = Alias->getClassInterface();
1144   }
1145 
1146   if (Class) {
1147     DiagnoseUseOfDecl(Class, NameLoc);
1148 
1149     if (NextToken.is(tok::period)) {
1150       // Interface. <something> is parsed as a property reference expression.
1151       // Just return "unknown" as a fall-through for now.
1152       Result.suppressDiagnostics();
1153       return NameClassification::Unknown();
1154     }
1155 
1156     QualType T = Context.getObjCInterfaceType(Class);
1157     return ParsedType::make(T);
1158   }
1159 
1160   if (isa<ConceptDecl>(FirstDecl))
1161     return NameClassification::Concept(
1162         TemplateName(cast<TemplateDecl>(FirstDecl)));
1163 
1164   // We can have a type template here if we're classifying a template argument.
1165   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1166       !isa<VarTemplateDecl>(FirstDecl))
1167     return NameClassification::TypeTemplate(
1168         TemplateName(cast<TemplateDecl>(FirstDecl)));
1169 
1170   // Check for a tag type hidden by a non-type decl in a few cases where it
1171   // seems likely a type is wanted instead of the non-type that was found.
1172   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1173   if ((NextToken.is(tok::identifier) ||
1174        (NextIsOp &&
1175         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1176       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1177     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1178     DiagnoseUseOfDecl(Type, NameLoc);
1179     QualType T = Context.getTypeDeclType(Type);
1180     if (SS.isNotEmpty())
1181       return buildNestedType(*this, SS, T, NameLoc);
1182     return ParsedType::make(T);
1183   }
1184 
1185   // If we already know which single declaration is referenced, just annotate
1186   // that declaration directly. Defer resolving even non-overloaded class
1187   // member accesses, as we need to defer certain access checks until we know
1188   // the context.
1189   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1190   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1191     return NameClassification::NonType(Result.getRepresentativeDecl());
1192 
1193   // Otherwise, this is an overload set that we will need to resolve later.
1194   Result.suppressDiagnostics();
1195   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1196       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1197       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1198       Result.begin(), Result.end()));
1199 }
1200 
1201 ExprResult
1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203                                              SourceLocation NameLoc) {
1204   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1205   CXXScopeSpec SS;
1206   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208 }
1209 
1210 ExprResult
1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212                                             IdentifierInfo *Name,
1213                                             SourceLocation NameLoc,
1214                                             bool IsAddressOfOperand) {
1215   DeclarationNameInfo NameInfo(Name, NameLoc);
1216   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217                                     NameInfo, IsAddressOfOperand,
1218                                     /*TemplateArgs=*/nullptr);
1219 }
1220 
1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222                                               NamedDecl *Found,
1223                                               SourceLocation NameLoc,
1224                                               const Token &NextToken) {
1225   if (getCurMethodDecl() && SS.isEmpty())
1226     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227       return BuildIvarRefExpr(S, NameLoc, Ivar);
1228 
1229   // Reconstruct the lookup result.
1230   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231   Result.addDecl(Found);
1232   Result.resolveKind();
1233 
1234   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235   return BuildDeclarationNameExpr(SS, Result, ADL);
1236 }
1237 
1238 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1239   // For an implicit class member access, transform the result into a member
1240   // access expression if necessary.
1241   auto *ULE = cast<UnresolvedLookupExpr>(E);
1242   if ((*ULE->decls_begin())->isCXXClassMember()) {
1243     CXXScopeSpec SS;
1244     SS.Adopt(ULE->getQualifierLoc());
1245 
1246     // Reconstruct the lookup result.
1247     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1248                         LookupOrdinaryName);
1249     Result.setNamingClass(ULE->getNamingClass());
1250     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1251       Result.addDecl(*I, I.getAccess());
1252     Result.resolveKind();
1253     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1254                                            nullptr, S);
1255   }
1256 
1257   // Otherwise, this is already in the form we needed, and no further checks
1258   // are necessary.
1259   return ULE;
1260 }
1261 
1262 Sema::TemplateNameKindForDiagnostics
1263 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1264   auto *TD = Name.getAsTemplateDecl();
1265   if (!TD)
1266     return TemplateNameKindForDiagnostics::DependentTemplate;
1267   if (isa<ClassTemplateDecl>(TD))
1268     return TemplateNameKindForDiagnostics::ClassTemplate;
1269   if (isa<FunctionTemplateDecl>(TD))
1270     return TemplateNameKindForDiagnostics::FunctionTemplate;
1271   if (isa<VarTemplateDecl>(TD))
1272     return TemplateNameKindForDiagnostics::VarTemplate;
1273   if (isa<TypeAliasTemplateDecl>(TD))
1274     return TemplateNameKindForDiagnostics::AliasTemplate;
1275   if (isa<TemplateTemplateParmDecl>(TD))
1276     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1277   if (isa<ConceptDecl>(TD))
1278     return TemplateNameKindForDiagnostics::Concept;
1279   return TemplateNameKindForDiagnostics::DependentTemplate;
1280 }
1281 
1282 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1283   assert(DC->getLexicalParent() == CurContext &&
1284       "The next DeclContext should be lexically contained in the current one.");
1285   CurContext = DC;
1286   S->setEntity(DC);
1287 }
1288 
1289 void Sema::PopDeclContext() {
1290   assert(CurContext && "DeclContext imbalance!");
1291 
1292   CurContext = CurContext->getLexicalParent();
1293   assert(CurContext && "Popped translation unit!");
1294 }
1295 
1296 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1297                                                                     Decl *D) {
1298   // Unlike PushDeclContext, the context to which we return is not necessarily
1299   // the containing DC of TD, because the new context will be some pre-existing
1300   // TagDecl definition instead of a fresh one.
1301   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1302   CurContext = cast<TagDecl>(D)->getDefinition();
1303   assert(CurContext && "skipping definition of undefined tag");
1304   // Start lookups from the parent of the current context; we don't want to look
1305   // into the pre-existing complete definition.
1306   S->setEntity(CurContext->getLookupParent());
1307   return Result;
1308 }
1309 
1310 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1311   CurContext = static_cast<decltype(CurContext)>(Context);
1312 }
1313 
1314 /// EnterDeclaratorContext - Used when we must lookup names in the context
1315 /// of a declarator's nested name specifier.
1316 ///
1317 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1318   // C++0x [basic.lookup.unqual]p13:
1319   //   A name used in the definition of a static data member of class
1320   //   X (after the qualified-id of the static member) is looked up as
1321   //   if the name was used in a member function of X.
1322   // C++0x [basic.lookup.unqual]p14:
1323   //   If a variable member of a namespace is defined outside of the
1324   //   scope of its namespace then any name used in the definition of
1325   //   the variable member (after the declarator-id) is looked up as
1326   //   if the definition of the variable member occurred in its
1327   //   namespace.
1328   // Both of these imply that we should push a scope whose context
1329   // is the semantic context of the declaration.  We can't use
1330   // PushDeclContext here because that context is not necessarily
1331   // lexically contained in the current context.  Fortunately,
1332   // the containing scope should have the appropriate information.
1333 
1334   assert(!S->getEntity() && "scope already has entity");
1335 
1336 #ifndef NDEBUG
1337   Scope *Ancestor = S->getParent();
1338   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1339   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1340 #endif
1341 
1342   CurContext = DC;
1343   S->setEntity(DC);
1344 
1345   if (S->getParent()->isTemplateParamScope()) {
1346     // Also set the corresponding entities for all immediately-enclosing
1347     // template parameter scopes.
1348     EnterTemplatedContext(S->getParent(), DC);
1349   }
1350 }
1351 
1352 void Sema::ExitDeclaratorContext(Scope *S) {
1353   assert(S->getEntity() == CurContext && "Context imbalance!");
1354 
1355   // Switch back to the lexical context.  The safety of this is
1356   // enforced by an assert in EnterDeclaratorContext.
1357   Scope *Ancestor = S->getParent();
1358   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1359   CurContext = Ancestor->getEntity();
1360 
1361   // We don't need to do anything with the scope, which is going to
1362   // disappear.
1363 }
1364 
1365 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1366   assert(S->isTemplateParamScope() &&
1367          "expected to be initializing a template parameter scope");
1368 
1369   // C++20 [temp.local]p7:
1370   //   In the definition of a member of a class template that appears outside
1371   //   of the class template definition, the name of a member of the class
1372   //   template hides the name of a template-parameter of any enclosing class
1373   //   templates (but not a template-parameter of the member if the member is a
1374   //   class or function template).
1375   // C++20 [temp.local]p9:
1376   //   In the definition of a class template or in the definition of a member
1377   //   of such a template that appears outside of the template definition, for
1378   //   each non-dependent base class (13.8.2.1), if the name of the base class
1379   //   or the name of a member of the base class is the same as the name of a
1380   //   template-parameter, the base class name or member name hides the
1381   //   template-parameter name (6.4.10).
1382   //
1383   // This means that a template parameter scope should be searched immediately
1384   // after searching the DeclContext for which it is a template parameter
1385   // scope. For example, for
1386   //   template<typename T> template<typename U> template<typename V>
1387   //     void N::A<T>::B<U>::f(...)
1388   // we search V then B<U> (and base classes) then U then A<T> (and base
1389   // classes) then T then N then ::.
1390   unsigned ScopeDepth = getTemplateDepth(S);
1391   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1392     DeclContext *SearchDCAfterScope = DC;
1393     for (; DC; DC = DC->getLookupParent()) {
1394       if (const TemplateParameterList *TPL =
1395               cast<Decl>(DC)->getDescribedTemplateParams()) {
1396         unsigned DCDepth = TPL->getDepth() + 1;
1397         if (DCDepth > ScopeDepth)
1398           continue;
1399         if (ScopeDepth == DCDepth)
1400           SearchDCAfterScope = DC = DC->getLookupParent();
1401         break;
1402       }
1403     }
1404     S->setLookupEntity(SearchDCAfterScope);
1405   }
1406 }
1407 
1408 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1409   // We assume that the caller has already called
1410   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1411   FunctionDecl *FD = D->getAsFunction();
1412   if (!FD)
1413     return;
1414 
1415   // Same implementation as PushDeclContext, but enters the context
1416   // from the lexical parent, rather than the top-level class.
1417   assert(CurContext == FD->getLexicalParent() &&
1418     "The next DeclContext should be lexically contained in the current one.");
1419   CurContext = FD;
1420   S->setEntity(CurContext);
1421 
1422   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1423     ParmVarDecl *Param = FD->getParamDecl(P);
1424     // If the parameter has an identifier, then add it to the scope
1425     if (Param->getIdentifier()) {
1426       S->AddDecl(Param);
1427       IdResolver.AddDecl(Param);
1428     }
1429   }
1430 }
1431 
1432 void Sema::ActOnExitFunctionContext() {
1433   // Same implementation as PopDeclContext, but returns to the lexical parent,
1434   // rather than the top-level class.
1435   assert(CurContext && "DeclContext imbalance!");
1436   CurContext = CurContext->getLexicalParent();
1437   assert(CurContext && "Popped translation unit!");
1438 }
1439 
1440 /// Determine whether we allow overloading of the function
1441 /// PrevDecl with another declaration.
1442 ///
1443 /// This routine determines whether overloading is possible, not
1444 /// whether some new function is actually an overload. It will return
1445 /// true in C++ (where we can always provide overloads) or, as an
1446 /// extension, in C when the previous function is already an
1447 /// overloaded function declaration or has the "overloadable"
1448 /// attribute.
1449 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1450                                        ASTContext &Context,
1451                                        const FunctionDecl *New) {
1452   if (Context.getLangOpts().CPlusPlus)
1453     return true;
1454 
1455   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1456     return true;
1457 
1458   return Previous.getResultKind() == LookupResult::Found &&
1459          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1460           New->hasAttr<OverloadableAttr>());
1461 }
1462 
1463 /// Add this decl to the scope shadowed decl chains.
1464 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1465   // Move up the scope chain until we find the nearest enclosing
1466   // non-transparent context. The declaration will be introduced into this
1467   // scope.
1468   while (S->getEntity() && S->getEntity()->isTransparentContext())
1469     S = S->getParent();
1470 
1471   // Add scoped declarations into their context, so that they can be
1472   // found later. Declarations without a context won't be inserted
1473   // into any context.
1474   if (AddToContext)
1475     CurContext->addDecl(D);
1476 
1477   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1478   // are function-local declarations.
1479   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1480     return;
1481 
1482   // Template instantiations should also not be pushed into scope.
1483   if (isa<FunctionDecl>(D) &&
1484       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1485     return;
1486 
1487   // If this replaces anything in the current scope,
1488   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1489                                IEnd = IdResolver.end();
1490   for (; I != IEnd; ++I) {
1491     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1492       S->RemoveDecl(*I);
1493       IdResolver.RemoveDecl(*I);
1494 
1495       // Should only need to replace one decl.
1496       break;
1497     }
1498   }
1499 
1500   S->AddDecl(D);
1501 
1502   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1503     // Implicitly-generated labels may end up getting generated in an order that
1504     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1505     // the label at the appropriate place in the identifier chain.
1506     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1507       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1508       if (IDC == CurContext) {
1509         if (!S->isDeclScope(*I))
1510           continue;
1511       } else if (IDC->Encloses(CurContext))
1512         break;
1513     }
1514 
1515     IdResolver.InsertDeclAfter(I, D);
1516   } else {
1517     IdResolver.AddDecl(D);
1518   }
1519 }
1520 
1521 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1522                          bool AllowInlineNamespace) {
1523   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1524 }
1525 
1526 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1527   DeclContext *TargetDC = DC->getPrimaryContext();
1528   do {
1529     if (DeclContext *ScopeDC = S->getEntity())
1530       if (ScopeDC->getPrimaryContext() == TargetDC)
1531         return S;
1532   } while ((S = S->getParent()));
1533 
1534   return nullptr;
1535 }
1536 
1537 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1538                                             DeclContext*,
1539                                             ASTContext&);
1540 
1541 /// Filters out lookup results that don't fall within the given scope
1542 /// as determined by isDeclInScope.
1543 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1544                                 bool ConsiderLinkage,
1545                                 bool AllowInlineNamespace) {
1546   LookupResult::Filter F = R.makeFilter();
1547   while (F.hasNext()) {
1548     NamedDecl *D = F.next();
1549 
1550     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1551       continue;
1552 
1553     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1554       continue;
1555 
1556     F.erase();
1557   }
1558 
1559   F.done();
1560 }
1561 
1562 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1563 /// have compatible owning modules.
1564 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1565   // FIXME: The Modules TS is not clear about how friend declarations are
1566   // to be treated. It's not meaningful to have different owning modules for
1567   // linkage in redeclarations of the same entity, so for now allow the
1568   // redeclaration and change the owning modules to match.
1569   if (New->getFriendObjectKind() &&
1570       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1571     New->setLocalOwningModule(Old->getOwningModule());
1572     makeMergedDefinitionVisible(New);
1573     return false;
1574   }
1575 
1576   Module *NewM = New->getOwningModule();
1577   Module *OldM = Old->getOwningModule();
1578 
1579   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1580     NewM = NewM->Parent;
1581   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1582     OldM = OldM->Parent;
1583 
1584   if (NewM == OldM)
1585     return false;
1586 
1587   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1588   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1589   if (NewIsModuleInterface || OldIsModuleInterface) {
1590     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1591     //   if a declaration of D [...] appears in the purview of a module, all
1592     //   other such declarations shall appear in the purview of the same module
1593     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1594       << New
1595       << NewIsModuleInterface
1596       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1597       << OldIsModuleInterface
1598       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1599     Diag(Old->getLocation(), diag::note_previous_declaration);
1600     New->setInvalidDecl();
1601     return true;
1602   }
1603 
1604   return false;
1605 }
1606 
1607 static bool isUsingDecl(NamedDecl *D) {
1608   return isa<UsingShadowDecl>(D) ||
1609          isa<UnresolvedUsingTypenameDecl>(D) ||
1610          isa<UnresolvedUsingValueDecl>(D);
1611 }
1612 
1613 /// Removes using shadow declarations from the lookup results.
1614 static void RemoveUsingDecls(LookupResult &R) {
1615   LookupResult::Filter F = R.makeFilter();
1616   while (F.hasNext())
1617     if (isUsingDecl(F.next()))
1618       F.erase();
1619 
1620   F.done();
1621 }
1622 
1623 /// Check for this common pattern:
1624 /// @code
1625 /// class S {
1626 ///   S(const S&); // DO NOT IMPLEMENT
1627 ///   void operator=(const S&); // DO NOT IMPLEMENT
1628 /// };
1629 /// @endcode
1630 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1631   // FIXME: Should check for private access too but access is set after we get
1632   // the decl here.
1633   if (D->doesThisDeclarationHaveABody())
1634     return false;
1635 
1636   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1637     return CD->isCopyConstructor();
1638   return D->isCopyAssignmentOperator();
1639 }
1640 
1641 // We need this to handle
1642 //
1643 // typedef struct {
1644 //   void *foo() { return 0; }
1645 // } A;
1646 //
1647 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1648 // for example. If 'A', foo will have external linkage. If we have '*A',
1649 // foo will have no linkage. Since we can't know until we get to the end
1650 // of the typedef, this function finds out if D might have non-external linkage.
1651 // Callers should verify at the end of the TU if it D has external linkage or
1652 // not.
1653 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1654   const DeclContext *DC = D->getDeclContext();
1655   while (!DC->isTranslationUnit()) {
1656     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1657       if (!RD->hasNameForLinkage())
1658         return true;
1659     }
1660     DC = DC->getParent();
1661   }
1662 
1663   return !D->isExternallyVisible();
1664 }
1665 
1666 // FIXME: This needs to be refactored; some other isInMainFile users want
1667 // these semantics.
1668 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1669   if (S.TUKind != TU_Complete)
1670     return false;
1671   return S.SourceMgr.isInMainFile(Loc);
1672 }
1673 
1674 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1675   assert(D);
1676 
1677   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1678     return false;
1679 
1680   // Ignore all entities declared within templates, and out-of-line definitions
1681   // of members of class templates.
1682   if (D->getDeclContext()->isDependentContext() ||
1683       D->getLexicalDeclContext()->isDependentContext())
1684     return false;
1685 
1686   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1687     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688       return false;
1689     // A non-out-of-line declaration of a member specialization was implicitly
1690     // instantiated; it's the out-of-line declaration that we're interested in.
1691     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1692         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1693       return false;
1694 
1695     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1696       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1697         return false;
1698     } else {
1699       // 'static inline' functions are defined in headers; don't warn.
1700       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1701         return false;
1702     }
1703 
1704     if (FD->doesThisDeclarationHaveABody() &&
1705         Context.DeclMustBeEmitted(FD))
1706       return false;
1707   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1708     // Constants and utility variables are defined in headers with internal
1709     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1710     // like "inline".)
1711     if (!isMainFileLoc(*this, VD->getLocation()))
1712       return false;
1713 
1714     if (Context.DeclMustBeEmitted(VD))
1715       return false;
1716 
1717     if (VD->isStaticDataMember() &&
1718         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1719       return false;
1720     if (VD->isStaticDataMember() &&
1721         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1722         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1723       return false;
1724 
1725     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1726       return false;
1727   } else {
1728     return false;
1729   }
1730 
1731   // Only warn for unused decls internal to the translation unit.
1732   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1733   // for inline functions defined in the main source file, for instance.
1734   return mightHaveNonExternalLinkage(D);
1735 }
1736 
1737 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1738   if (!D)
1739     return;
1740 
1741   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1742     const FunctionDecl *First = FD->getFirstDecl();
1743     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1744       return; // First should already be in the vector.
1745   }
1746 
1747   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1748     const VarDecl *First = VD->getFirstDecl();
1749     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1750       return; // First should already be in the vector.
1751   }
1752 
1753   if (ShouldWarnIfUnusedFileScopedDecl(D))
1754     UnusedFileScopedDecls.push_back(D);
1755 }
1756 
1757 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1758   if (D->isInvalidDecl())
1759     return false;
1760 
1761   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1762     // For a decomposition declaration, warn if none of the bindings are
1763     // referenced, instead of if the variable itself is referenced (which
1764     // it is, by the bindings' expressions).
1765     for (auto *BD : DD->bindings())
1766       if (BD->isReferenced())
1767         return false;
1768   } else if (!D->getDeclName()) {
1769     return false;
1770   } else if (D->isReferenced() || D->isUsed()) {
1771     return false;
1772   }
1773 
1774   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1775     return false;
1776 
1777   if (isa<LabelDecl>(D))
1778     return true;
1779 
1780   // Except for labels, we only care about unused decls that are local to
1781   // functions.
1782   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1783   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1784     // For dependent types, the diagnostic is deferred.
1785     WithinFunction =
1786         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1787   if (!WithinFunction)
1788     return false;
1789 
1790   if (isa<TypedefNameDecl>(D))
1791     return true;
1792 
1793   // White-list anything that isn't a local variable.
1794   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1795     return false;
1796 
1797   // Types of valid local variables should be complete, so this should succeed.
1798   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1799 
1800     // White-list anything with an __attribute__((unused)) type.
1801     const auto *Ty = VD->getType().getTypePtr();
1802 
1803     // Only look at the outermost level of typedef.
1804     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1805       if (TT->getDecl()->hasAttr<UnusedAttr>())
1806         return false;
1807     }
1808 
1809     // If we failed to complete the type for some reason, or if the type is
1810     // dependent, don't diagnose the variable.
1811     if (Ty->isIncompleteType() || Ty->isDependentType())
1812       return false;
1813 
1814     // Look at the element type to ensure that the warning behaviour is
1815     // consistent for both scalars and arrays.
1816     Ty = Ty->getBaseElementTypeUnsafe();
1817 
1818     if (const TagType *TT = Ty->getAs<TagType>()) {
1819       const TagDecl *Tag = TT->getDecl();
1820       if (Tag->hasAttr<UnusedAttr>())
1821         return false;
1822 
1823       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1824         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1825           return false;
1826 
1827         if (const Expr *Init = VD->getInit()) {
1828           if (const ExprWithCleanups *Cleanups =
1829                   dyn_cast<ExprWithCleanups>(Init))
1830             Init = Cleanups->getSubExpr();
1831           const CXXConstructExpr *Construct =
1832             dyn_cast<CXXConstructExpr>(Init);
1833           if (Construct && !Construct->isElidable()) {
1834             CXXConstructorDecl *CD = Construct->getConstructor();
1835             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1836                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1837               return false;
1838           }
1839 
1840           // Suppress the warning if we don't know how this is constructed, and
1841           // it could possibly be non-trivial constructor.
1842           if (Init->isTypeDependent())
1843             for (const CXXConstructorDecl *Ctor : RD->ctors())
1844               if (!Ctor->isTrivial())
1845                 return false;
1846         }
1847       }
1848     }
1849 
1850     // TODO: __attribute__((unused)) templates?
1851   }
1852 
1853   return true;
1854 }
1855 
1856 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1857                                      FixItHint &Hint) {
1858   if (isa<LabelDecl>(D)) {
1859     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1860         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1861         true);
1862     if (AfterColon.isInvalid())
1863       return;
1864     Hint = FixItHint::CreateRemoval(
1865         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1866   }
1867 }
1868 
1869 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1870   if (D->getTypeForDecl()->isDependentType())
1871     return;
1872 
1873   for (auto *TmpD : D->decls()) {
1874     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1875       DiagnoseUnusedDecl(T);
1876     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1877       DiagnoseUnusedNestedTypedefs(R);
1878   }
1879 }
1880 
1881 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1882 /// unless they are marked attr(unused).
1883 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1884   if (!ShouldDiagnoseUnusedDecl(D))
1885     return;
1886 
1887   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1888     // typedefs can be referenced later on, so the diagnostics are emitted
1889     // at end-of-translation-unit.
1890     UnusedLocalTypedefNameCandidates.insert(TD);
1891     return;
1892   }
1893 
1894   FixItHint Hint;
1895   GenerateFixForUnusedDecl(D, Context, Hint);
1896 
1897   unsigned DiagID;
1898   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1899     DiagID = diag::warn_unused_exception_param;
1900   else if (isa<LabelDecl>(D))
1901     DiagID = diag::warn_unused_label;
1902   else
1903     DiagID = diag::warn_unused_variable;
1904 
1905   Diag(D->getLocation(), DiagID) << D << Hint;
1906 }
1907 
1908 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1909   // Verify that we have no forward references left.  If so, there was a goto
1910   // or address of a label taken, but no definition of it.  Label fwd
1911   // definitions are indicated with a null substmt which is also not a resolved
1912   // MS inline assembly label name.
1913   bool Diagnose = false;
1914   if (L->isMSAsmLabel())
1915     Diagnose = !L->isResolvedMSAsmLabel();
1916   else
1917     Diagnose = L->getStmt() == nullptr;
1918   if (Diagnose)
1919     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1920 }
1921 
1922 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1923   S->mergeNRVOIntoParent();
1924 
1925   if (S->decl_empty()) return;
1926   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1927          "Scope shouldn't contain decls!");
1928 
1929   for (auto *TmpD : S->decls()) {
1930     assert(TmpD && "This decl didn't get pushed??");
1931 
1932     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1933     NamedDecl *D = cast<NamedDecl>(TmpD);
1934 
1935     // Diagnose unused variables in this scope.
1936     if (!S->hasUnrecoverableErrorOccurred()) {
1937       DiagnoseUnusedDecl(D);
1938       if (const auto *RD = dyn_cast<RecordDecl>(D))
1939         DiagnoseUnusedNestedTypedefs(RD);
1940     }
1941 
1942     if (!D->getDeclName()) continue;
1943 
1944     // If this was a forward reference to a label, verify it was defined.
1945     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1946       CheckPoppedLabel(LD, *this);
1947 
1948     // Remove this name from our lexical scope, and warn on it if we haven't
1949     // already.
1950     IdResolver.RemoveDecl(D);
1951     auto ShadowI = ShadowingDecls.find(D);
1952     if (ShadowI != ShadowingDecls.end()) {
1953       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1954         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1955             << D << FD << FD->getParent();
1956         Diag(FD->getLocation(), diag::note_previous_declaration);
1957       }
1958       ShadowingDecls.erase(ShadowI);
1959     }
1960   }
1961 }
1962 
1963 /// Look for an Objective-C class in the translation unit.
1964 ///
1965 /// \param Id The name of the Objective-C class we're looking for. If
1966 /// typo-correction fixes this name, the Id will be updated
1967 /// to the fixed name.
1968 ///
1969 /// \param IdLoc The location of the name in the translation unit.
1970 ///
1971 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1972 /// if there is no class with the given name.
1973 ///
1974 /// \returns The declaration of the named Objective-C class, or NULL if the
1975 /// class could not be found.
1976 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1977                                               SourceLocation IdLoc,
1978                                               bool DoTypoCorrection) {
1979   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1980   // creation from this context.
1981   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1982 
1983   if (!IDecl && DoTypoCorrection) {
1984     // Perform typo correction at the given location, but only if we
1985     // find an Objective-C class name.
1986     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1987     if (TypoCorrection C =
1988             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1989                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1990       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1991       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1992       Id = IDecl->getIdentifier();
1993     }
1994   }
1995   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1996   // This routine must always return a class definition, if any.
1997   if (Def && Def->getDefinition())
1998       Def = Def->getDefinition();
1999   return Def;
2000 }
2001 
2002 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2003 /// from S, where a non-field would be declared. This routine copes
2004 /// with the difference between C and C++ scoping rules in structs and
2005 /// unions. For example, the following code is well-formed in C but
2006 /// ill-formed in C++:
2007 /// @code
2008 /// struct S6 {
2009 ///   enum { BAR } e;
2010 /// };
2011 ///
2012 /// void test_S6() {
2013 ///   struct S6 a;
2014 ///   a.e = BAR;
2015 /// }
2016 /// @endcode
2017 /// For the declaration of BAR, this routine will return a different
2018 /// scope. The scope S will be the scope of the unnamed enumeration
2019 /// within S6. In C++, this routine will return the scope associated
2020 /// with S6, because the enumeration's scope is a transparent
2021 /// context but structures can contain non-field names. In C, this
2022 /// routine will return the translation unit scope, since the
2023 /// enumeration's scope is a transparent context and structures cannot
2024 /// contain non-field names.
2025 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2026   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2027          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2028          (S->isClassScope() && !getLangOpts().CPlusPlus))
2029     S = S->getParent();
2030   return S;
2031 }
2032 
2033 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2034                                ASTContext::GetBuiltinTypeError Error) {
2035   switch (Error) {
2036   case ASTContext::GE_None:
2037     return "";
2038   case ASTContext::GE_Missing_type:
2039     return BuiltinInfo.getHeaderName(ID);
2040   case ASTContext::GE_Missing_stdio:
2041     return "stdio.h";
2042   case ASTContext::GE_Missing_setjmp:
2043     return "setjmp.h";
2044   case ASTContext::GE_Missing_ucontext:
2045     return "ucontext.h";
2046   }
2047   llvm_unreachable("unhandled error kind");
2048 }
2049 
2050 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2051                                   unsigned ID, SourceLocation Loc) {
2052   DeclContext *Parent = Context.getTranslationUnitDecl();
2053 
2054   if (getLangOpts().CPlusPlus) {
2055     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2056         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2057     CLinkageDecl->setImplicit();
2058     Parent->addDecl(CLinkageDecl);
2059     Parent = CLinkageDecl;
2060   }
2061 
2062   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2063                                            /*TInfo=*/nullptr, SC_Extern, false,
2064                                            Type->isFunctionProtoType());
2065   New->setImplicit();
2066   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2067 
2068   // Create Decl objects for each parameter, adding them to the
2069   // FunctionDecl.
2070   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2071     SmallVector<ParmVarDecl *, 16> Params;
2072     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2073       ParmVarDecl *parm = ParmVarDecl::Create(
2074           Context, New, SourceLocation(), SourceLocation(), nullptr,
2075           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2076       parm->setScopeInfo(0, i);
2077       Params.push_back(parm);
2078     }
2079     New->setParams(Params);
2080   }
2081 
2082   AddKnownFunctionAttributes(New);
2083   return New;
2084 }
2085 
2086 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2087 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2088 /// if we're creating this built-in in anticipation of redeclaring the
2089 /// built-in.
2090 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2091                                      Scope *S, bool ForRedeclaration,
2092                                      SourceLocation Loc) {
2093   LookupNecessaryTypesForBuiltin(S, ID);
2094 
2095   ASTContext::GetBuiltinTypeError Error;
2096   QualType R = Context.GetBuiltinType(ID, Error);
2097   if (Error) {
2098     if (!ForRedeclaration)
2099       return nullptr;
2100 
2101     // If we have a builtin without an associated type we should not emit a
2102     // warning when we were not able to find a type for it.
2103     if (Error == ASTContext::GE_Missing_type ||
2104         Context.BuiltinInfo.allowTypeMismatch(ID))
2105       return nullptr;
2106 
2107     // If we could not find a type for setjmp it is because the jmp_buf type was
2108     // not defined prior to the setjmp declaration.
2109     if (Error == ASTContext::GE_Missing_setjmp) {
2110       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2111           << Context.BuiltinInfo.getName(ID);
2112       return nullptr;
2113     }
2114 
2115     // Generally, we emit a warning that the declaration requires the
2116     // appropriate header.
2117     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2118         << getHeaderName(Context.BuiltinInfo, ID, Error)
2119         << Context.BuiltinInfo.getName(ID);
2120     return nullptr;
2121   }
2122 
2123   if (!ForRedeclaration &&
2124       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2125        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2126     Diag(Loc, diag::ext_implicit_lib_function_decl)
2127         << Context.BuiltinInfo.getName(ID) << R;
2128     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2129       Diag(Loc, diag::note_include_header_or_declare)
2130           << Header << Context.BuiltinInfo.getName(ID);
2131   }
2132 
2133   if (R.isNull())
2134     return nullptr;
2135 
2136   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2137   RegisterLocallyScopedExternCDecl(New, S);
2138 
2139   // TUScope is the translation-unit scope to insert this function into.
2140   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2141   // relate Scopes to DeclContexts, and probably eliminate CurContext
2142   // entirely, but we're not there yet.
2143   DeclContext *SavedContext = CurContext;
2144   CurContext = New->getDeclContext();
2145   PushOnScopeChains(New, TUScope);
2146   CurContext = SavedContext;
2147   return New;
2148 }
2149 
2150 /// Typedef declarations don't have linkage, but they still denote the same
2151 /// entity if their types are the same.
2152 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2153 /// isSameEntity.
2154 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2155                                                      TypedefNameDecl *Decl,
2156                                                      LookupResult &Previous) {
2157   // This is only interesting when modules are enabled.
2158   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2159     return;
2160 
2161   // Empty sets are uninteresting.
2162   if (Previous.empty())
2163     return;
2164 
2165   LookupResult::Filter Filter = Previous.makeFilter();
2166   while (Filter.hasNext()) {
2167     NamedDecl *Old = Filter.next();
2168 
2169     // Non-hidden declarations are never ignored.
2170     if (S.isVisible(Old))
2171       continue;
2172 
2173     // Declarations of the same entity are not ignored, even if they have
2174     // different linkages.
2175     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2176       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2177                                 Decl->getUnderlyingType()))
2178         continue;
2179 
2180       // If both declarations give a tag declaration a typedef name for linkage
2181       // purposes, then they declare the same entity.
2182       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2183           Decl->getAnonDeclWithTypedefName())
2184         continue;
2185     }
2186 
2187     Filter.erase();
2188   }
2189 
2190   Filter.done();
2191 }
2192 
2193 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2194   QualType OldType;
2195   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2196     OldType = OldTypedef->getUnderlyingType();
2197   else
2198     OldType = Context.getTypeDeclType(Old);
2199   QualType NewType = New->getUnderlyingType();
2200 
2201   if (NewType->isVariablyModifiedType()) {
2202     // Must not redefine a typedef with a variably-modified type.
2203     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2204     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2205       << Kind << NewType;
2206     if (Old->getLocation().isValid())
2207       notePreviousDefinition(Old, New->getLocation());
2208     New->setInvalidDecl();
2209     return true;
2210   }
2211 
2212   if (OldType != NewType &&
2213       !OldType->isDependentType() &&
2214       !NewType->isDependentType() &&
2215       !Context.hasSameType(OldType, NewType)) {
2216     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2217     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2218       << Kind << NewType << OldType;
2219     if (Old->getLocation().isValid())
2220       notePreviousDefinition(Old, New->getLocation());
2221     New->setInvalidDecl();
2222     return true;
2223   }
2224   return false;
2225 }
2226 
2227 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2228 /// same name and scope as a previous declaration 'Old'.  Figure out
2229 /// how to resolve this situation, merging decls or emitting
2230 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2231 ///
2232 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2233                                 LookupResult &OldDecls) {
2234   // If the new decl is known invalid already, don't bother doing any
2235   // merging checks.
2236   if (New->isInvalidDecl()) return;
2237 
2238   // Allow multiple definitions for ObjC built-in typedefs.
2239   // FIXME: Verify the underlying types are equivalent!
2240   if (getLangOpts().ObjC) {
2241     const IdentifierInfo *TypeID = New->getIdentifier();
2242     switch (TypeID->getLength()) {
2243     default: break;
2244     case 2:
2245       {
2246         if (!TypeID->isStr("id"))
2247           break;
2248         QualType T = New->getUnderlyingType();
2249         if (!T->isPointerType())
2250           break;
2251         if (!T->isVoidPointerType()) {
2252           QualType PT = T->castAs<PointerType>()->getPointeeType();
2253           if (!PT->isStructureType())
2254             break;
2255         }
2256         Context.setObjCIdRedefinitionType(T);
2257         // Install the built-in type for 'id', ignoring the current definition.
2258         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2259         return;
2260       }
2261     case 5:
2262       if (!TypeID->isStr("Class"))
2263         break;
2264       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2265       // Install the built-in type for 'Class', ignoring the current definition.
2266       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2267       return;
2268     case 3:
2269       if (!TypeID->isStr("SEL"))
2270         break;
2271       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2272       // Install the built-in type for 'SEL', ignoring the current definition.
2273       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2274       return;
2275     }
2276     // Fall through - the typedef name was not a builtin type.
2277   }
2278 
2279   // Verify the old decl was also a type.
2280   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2281   if (!Old) {
2282     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2283       << New->getDeclName();
2284 
2285     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2286     if (OldD->getLocation().isValid())
2287       notePreviousDefinition(OldD, New->getLocation());
2288 
2289     return New->setInvalidDecl();
2290   }
2291 
2292   // If the old declaration is invalid, just give up here.
2293   if (Old->isInvalidDecl())
2294     return New->setInvalidDecl();
2295 
2296   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2297     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2298     auto *NewTag = New->getAnonDeclWithTypedefName();
2299     NamedDecl *Hidden = nullptr;
2300     if (OldTag && NewTag &&
2301         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2302         !hasVisibleDefinition(OldTag, &Hidden)) {
2303       // There is a definition of this tag, but it is not visible. Use it
2304       // instead of our tag.
2305       New->setTypeForDecl(OldTD->getTypeForDecl());
2306       if (OldTD->isModed())
2307         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2308                                     OldTD->getUnderlyingType());
2309       else
2310         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2311 
2312       // Make the old tag definition visible.
2313       makeMergedDefinitionVisible(Hidden);
2314 
2315       // If this was an unscoped enumeration, yank all of its enumerators
2316       // out of the scope.
2317       if (isa<EnumDecl>(NewTag)) {
2318         Scope *EnumScope = getNonFieldDeclScope(S);
2319         for (auto *D : NewTag->decls()) {
2320           auto *ED = cast<EnumConstantDecl>(D);
2321           assert(EnumScope->isDeclScope(ED));
2322           EnumScope->RemoveDecl(ED);
2323           IdResolver.RemoveDecl(ED);
2324           ED->getLexicalDeclContext()->removeDecl(ED);
2325         }
2326       }
2327     }
2328   }
2329 
2330   // If the typedef types are not identical, reject them in all languages and
2331   // with any extensions enabled.
2332   if (isIncompatibleTypedef(Old, New))
2333     return;
2334 
2335   // The types match.  Link up the redeclaration chain and merge attributes if
2336   // the old declaration was a typedef.
2337   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2338     New->setPreviousDecl(Typedef);
2339     mergeDeclAttributes(New, Old);
2340   }
2341 
2342   if (getLangOpts().MicrosoftExt)
2343     return;
2344 
2345   if (getLangOpts().CPlusPlus) {
2346     // C++ [dcl.typedef]p2:
2347     //   In a given non-class scope, a typedef specifier can be used to
2348     //   redefine the name of any type declared in that scope to refer
2349     //   to the type to which it already refers.
2350     if (!isa<CXXRecordDecl>(CurContext))
2351       return;
2352 
2353     // C++0x [dcl.typedef]p4:
2354     //   In a given class scope, a typedef specifier can be used to redefine
2355     //   any class-name declared in that scope that is not also a typedef-name
2356     //   to refer to the type to which it already refers.
2357     //
2358     // This wording came in via DR424, which was a correction to the
2359     // wording in DR56, which accidentally banned code like:
2360     //
2361     //   struct S {
2362     //     typedef struct A { } A;
2363     //   };
2364     //
2365     // in the C++03 standard. We implement the C++0x semantics, which
2366     // allow the above but disallow
2367     //
2368     //   struct S {
2369     //     typedef int I;
2370     //     typedef int I;
2371     //   };
2372     //
2373     // since that was the intent of DR56.
2374     if (!isa<TypedefNameDecl>(Old))
2375       return;
2376 
2377     Diag(New->getLocation(), diag::err_redefinition)
2378       << New->getDeclName();
2379     notePreviousDefinition(Old, New->getLocation());
2380     return New->setInvalidDecl();
2381   }
2382 
2383   // Modules always permit redefinition of typedefs, as does C11.
2384   if (getLangOpts().Modules || getLangOpts().C11)
2385     return;
2386 
2387   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2388   // is normally mapped to an error, but can be controlled with
2389   // -Wtypedef-redefinition.  If either the original or the redefinition is
2390   // in a system header, don't emit this for compatibility with GCC.
2391   if (getDiagnostics().getSuppressSystemWarnings() &&
2392       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2393       (Old->isImplicit() ||
2394        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2395        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2396     return;
2397 
2398   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2399     << New->getDeclName();
2400   notePreviousDefinition(Old, New->getLocation());
2401 }
2402 
2403 /// DeclhasAttr - returns true if decl Declaration already has the target
2404 /// attribute.
2405 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2406   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2407   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2408   for (const auto *i : D->attrs())
2409     if (i->getKind() == A->getKind()) {
2410       if (Ann) {
2411         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2412           return true;
2413         continue;
2414       }
2415       // FIXME: Don't hardcode this check
2416       if (OA && isa<OwnershipAttr>(i))
2417         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2418       return true;
2419     }
2420 
2421   return false;
2422 }
2423 
2424 static bool isAttributeTargetADefinition(Decl *D) {
2425   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2426     return VD->isThisDeclarationADefinition();
2427   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2428     return TD->isCompleteDefinition() || TD->isBeingDefined();
2429   return true;
2430 }
2431 
2432 /// Merge alignment attributes from \p Old to \p New, taking into account the
2433 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2434 ///
2435 /// \return \c true if any attributes were added to \p New.
2436 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2437   // Look for alignas attributes on Old, and pick out whichever attribute
2438   // specifies the strictest alignment requirement.
2439   AlignedAttr *OldAlignasAttr = nullptr;
2440   AlignedAttr *OldStrictestAlignAttr = nullptr;
2441   unsigned OldAlign = 0;
2442   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2443     // FIXME: We have no way of representing inherited dependent alignments
2444     // in a case like:
2445     //   template<int A, int B> struct alignas(A) X;
2446     //   template<int A, int B> struct alignas(B) X {};
2447     // For now, we just ignore any alignas attributes which are not on the
2448     // definition in such a case.
2449     if (I->isAlignmentDependent())
2450       return false;
2451 
2452     if (I->isAlignas())
2453       OldAlignasAttr = I;
2454 
2455     unsigned Align = I->getAlignment(S.Context);
2456     if (Align > OldAlign) {
2457       OldAlign = Align;
2458       OldStrictestAlignAttr = I;
2459     }
2460   }
2461 
2462   // Look for alignas attributes on New.
2463   AlignedAttr *NewAlignasAttr = nullptr;
2464   unsigned NewAlign = 0;
2465   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2466     if (I->isAlignmentDependent())
2467       return false;
2468 
2469     if (I->isAlignas())
2470       NewAlignasAttr = I;
2471 
2472     unsigned Align = I->getAlignment(S.Context);
2473     if (Align > NewAlign)
2474       NewAlign = Align;
2475   }
2476 
2477   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2478     // Both declarations have 'alignas' attributes. We require them to match.
2479     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2480     // fall short. (If two declarations both have alignas, they must both match
2481     // every definition, and so must match each other if there is a definition.)
2482 
2483     // If either declaration only contains 'alignas(0)' specifiers, then it
2484     // specifies the natural alignment for the type.
2485     if (OldAlign == 0 || NewAlign == 0) {
2486       QualType Ty;
2487       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2488         Ty = VD->getType();
2489       else
2490         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2491 
2492       if (OldAlign == 0)
2493         OldAlign = S.Context.getTypeAlign(Ty);
2494       if (NewAlign == 0)
2495         NewAlign = S.Context.getTypeAlign(Ty);
2496     }
2497 
2498     if (OldAlign != NewAlign) {
2499       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2500         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2501         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2502       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2503     }
2504   }
2505 
2506   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2507     // C++11 [dcl.align]p6:
2508     //   if any declaration of an entity has an alignment-specifier,
2509     //   every defining declaration of that entity shall specify an
2510     //   equivalent alignment.
2511     // C11 6.7.5/7:
2512     //   If the definition of an object does not have an alignment
2513     //   specifier, any other declaration of that object shall also
2514     //   have no alignment specifier.
2515     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2516       << OldAlignasAttr;
2517     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2518       << OldAlignasAttr;
2519   }
2520 
2521   bool AnyAdded = false;
2522 
2523   // Ensure we have an attribute representing the strictest alignment.
2524   if (OldAlign > NewAlign) {
2525     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2526     Clone->setInherited(true);
2527     New->addAttr(Clone);
2528     AnyAdded = true;
2529   }
2530 
2531   // Ensure we have an alignas attribute if the old declaration had one.
2532   if (OldAlignasAttr && !NewAlignasAttr &&
2533       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2534     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2535     Clone->setInherited(true);
2536     New->addAttr(Clone);
2537     AnyAdded = true;
2538   }
2539 
2540   return AnyAdded;
2541 }
2542 
2543 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2544                                const InheritableAttr *Attr,
2545                                Sema::AvailabilityMergeKind AMK) {
2546   // This function copies an attribute Attr from a previous declaration to the
2547   // new declaration D if the new declaration doesn't itself have that attribute
2548   // yet or if that attribute allows duplicates.
2549   // If you're adding a new attribute that requires logic different from
2550   // "use explicit attribute on decl if present, else use attribute from
2551   // previous decl", for example if the attribute needs to be consistent
2552   // between redeclarations, you need to call a custom merge function here.
2553   InheritableAttr *NewAttr = nullptr;
2554   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2555     NewAttr = S.mergeAvailabilityAttr(
2556         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2557         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2558         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2559         AA->getPriority());
2560   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2561     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2562   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2563     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2564   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2565     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2566   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2567     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2568   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2569     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2570                                 FA->getFirstArg());
2571   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2572     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2573   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2574     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2575   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2576     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2577                                        IA->getInheritanceModel());
2578   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2579     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2580                                       &S.Context.Idents.get(AA->getSpelling()));
2581   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2582            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2583             isa<CUDAGlobalAttr>(Attr))) {
2584     // CUDA target attributes are part of function signature for
2585     // overloading purposes and must not be merged.
2586     return false;
2587   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2588     NewAttr = S.mergeMinSizeAttr(D, *MA);
2589   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2590     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2591   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2592     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2593   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2594     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2595   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2596     NewAttr = S.mergeCommonAttr(D, *CommonA);
2597   else if (isa<AlignedAttr>(Attr))
2598     // AlignedAttrs are handled separately, because we need to handle all
2599     // such attributes on a declaration at the same time.
2600     NewAttr = nullptr;
2601   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2602            (AMK == Sema::AMK_Override ||
2603             AMK == Sema::AMK_ProtocolImplementation))
2604     NewAttr = nullptr;
2605   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2606     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2607   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2608     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2609   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2610     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2611   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2612     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2613   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2614     NewAttr = S.mergeImportNameAttr(D, *INA);
2615   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2616     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2617   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2618     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2619   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2620     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2621 
2622   if (NewAttr) {
2623     NewAttr->setInherited(true);
2624     D->addAttr(NewAttr);
2625     if (isa<MSInheritanceAttr>(NewAttr))
2626       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2627     return true;
2628   }
2629 
2630   return false;
2631 }
2632 
2633 static const NamedDecl *getDefinition(const Decl *D) {
2634   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2635     return TD->getDefinition();
2636   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2637     const VarDecl *Def = VD->getDefinition();
2638     if (Def)
2639       return Def;
2640     return VD->getActingDefinition();
2641   }
2642   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2643     const FunctionDecl *Def = nullptr;
2644     if (FD->isDefined(Def, true))
2645       return Def;
2646   }
2647   return nullptr;
2648 }
2649 
2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2651   for (const auto *Attribute : D->attrs())
2652     if (Attribute->getKind() == Kind)
2653       return true;
2654   return false;
2655 }
2656 
2657 /// checkNewAttributesAfterDef - If we already have a definition, check that
2658 /// there are no new attributes in this declaration.
2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2660   if (!New->hasAttrs())
2661     return;
2662 
2663   const NamedDecl *Def = getDefinition(Old);
2664   if (!Def || Def == New)
2665     return;
2666 
2667   AttrVec &NewAttributes = New->getAttrs();
2668   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2669     const Attr *NewAttribute = NewAttributes[I];
2670 
2671     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2672       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2673         Sema::SkipBodyInfo SkipBody;
2674         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2675 
2676         // If we're skipping this definition, drop the "alias" attribute.
2677         if (SkipBody.ShouldSkip) {
2678           NewAttributes.erase(NewAttributes.begin() + I);
2679           --E;
2680           continue;
2681         }
2682       } else {
2683         VarDecl *VD = cast<VarDecl>(New);
2684         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2685                                 VarDecl::TentativeDefinition
2686                             ? diag::err_alias_after_tentative
2687                             : diag::err_redefinition;
2688         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2689         if (Diag == diag::err_redefinition)
2690           S.notePreviousDefinition(Def, VD->getLocation());
2691         else
2692           S.Diag(Def->getLocation(), diag::note_previous_definition);
2693         VD->setInvalidDecl();
2694       }
2695       ++I;
2696       continue;
2697     }
2698 
2699     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2700       // Tentative definitions are only interesting for the alias check above.
2701       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2702         ++I;
2703         continue;
2704       }
2705     }
2706 
2707     if (hasAttribute(Def, NewAttribute->getKind())) {
2708       ++I;
2709       continue; // regular attr merging will take care of validating this.
2710     }
2711 
2712     if (isa<C11NoReturnAttr>(NewAttribute)) {
2713       // C's _Noreturn is allowed to be added to a function after it is defined.
2714       ++I;
2715       continue;
2716     } else if (isa<UuidAttr>(NewAttribute)) {
2717       // msvc will allow a subsequent definition to add an uuid to a class
2718       ++I;
2719       continue;
2720     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2721       if (AA->isAlignas()) {
2722         // C++11 [dcl.align]p6:
2723         //   if any declaration of an entity has an alignment-specifier,
2724         //   every defining declaration of that entity shall specify an
2725         //   equivalent alignment.
2726         // C11 6.7.5/7:
2727         //   If the definition of an object does not have an alignment
2728         //   specifier, any other declaration of that object shall also
2729         //   have no alignment specifier.
2730         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2731           << AA;
2732         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2733           << AA;
2734         NewAttributes.erase(NewAttributes.begin() + I);
2735         --E;
2736         continue;
2737       }
2738     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2739       // If there is a C definition followed by a redeclaration with this
2740       // attribute then there are two different definitions. In C++, prefer the
2741       // standard diagnostics.
2742       if (!S.getLangOpts().CPlusPlus) {
2743         S.Diag(NewAttribute->getLocation(),
2744                diag::err_loader_uninitialized_redeclaration);
2745         S.Diag(Def->getLocation(), diag::note_previous_definition);
2746         NewAttributes.erase(NewAttributes.begin() + I);
2747         --E;
2748         continue;
2749       }
2750     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2751                cast<VarDecl>(New)->isInline() &&
2752                !cast<VarDecl>(New)->isInlineSpecified()) {
2753       // Don't warn about applying selectany to implicitly inline variables.
2754       // Older compilers and language modes would require the use of selectany
2755       // to make such variables inline, and it would have no effect if we
2756       // honored it.
2757       ++I;
2758       continue;
2759     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2760       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2761       // declarations after defintions.
2762       ++I;
2763       continue;
2764     }
2765 
2766     S.Diag(NewAttribute->getLocation(),
2767            diag::warn_attribute_precede_definition);
2768     S.Diag(Def->getLocation(), diag::note_previous_definition);
2769     NewAttributes.erase(NewAttributes.begin() + I);
2770     --E;
2771   }
2772 }
2773 
2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2775                                      const ConstInitAttr *CIAttr,
2776                                      bool AttrBeforeInit) {
2777   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2778 
2779   // Figure out a good way to write this specifier on the old declaration.
2780   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2781   // enough of the attribute list spelling information to extract that without
2782   // heroics.
2783   std::string SuitableSpelling;
2784   if (S.getLangOpts().CPlusPlus20)
2785     SuitableSpelling = std::string(
2786         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2787   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2788     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2789         InsertLoc, {tok::l_square, tok::l_square,
2790                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2791                     S.PP.getIdentifierInfo("require_constant_initialization"),
2792                     tok::r_square, tok::r_square}));
2793   if (SuitableSpelling.empty())
2794     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2795         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2796                     S.PP.getIdentifierInfo("require_constant_initialization"),
2797                     tok::r_paren, tok::r_paren}));
2798   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2799     SuitableSpelling = "constinit";
2800   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2801     SuitableSpelling = "[[clang::require_constant_initialization]]";
2802   if (SuitableSpelling.empty())
2803     SuitableSpelling = "__attribute__((require_constant_initialization))";
2804   SuitableSpelling += " ";
2805 
2806   if (AttrBeforeInit) {
2807     // extern constinit int a;
2808     // int a = 0; // error (missing 'constinit'), accepted as extension
2809     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2810     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2811         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2812     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2813   } else {
2814     // int a = 0;
2815     // constinit extern int a; // error (missing 'constinit')
2816     S.Diag(CIAttr->getLocation(),
2817            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2818                                  : diag::warn_require_const_init_added_too_late)
2819         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2820     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2821         << CIAttr->isConstinit()
2822         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2823   }
2824 }
2825 
2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2828                                AvailabilityMergeKind AMK) {
2829   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2830     UsedAttr *NewAttr = OldAttr->clone(Context);
2831     NewAttr->setInherited(true);
2832     New->addAttr(NewAttr);
2833   }
2834   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2835     RetainAttr *NewAttr = OldAttr->clone(Context);
2836     NewAttr->setInherited(true);
2837     New->addAttr(NewAttr);
2838   }
2839 
2840   if (!Old->hasAttrs() && !New->hasAttrs())
2841     return;
2842 
2843   // [dcl.constinit]p1:
2844   //   If the [constinit] specifier is applied to any declaration of a
2845   //   variable, it shall be applied to the initializing declaration.
2846   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2847   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2848   if (bool(OldConstInit) != bool(NewConstInit)) {
2849     const auto *OldVD = cast<VarDecl>(Old);
2850     auto *NewVD = cast<VarDecl>(New);
2851 
2852     // Find the initializing declaration. Note that we might not have linked
2853     // the new declaration into the redeclaration chain yet.
2854     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2855     if (!InitDecl &&
2856         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2857       InitDecl = NewVD;
2858 
2859     if (InitDecl == NewVD) {
2860       // This is the initializing declaration. If it would inherit 'constinit',
2861       // that's ill-formed. (Note that we do not apply this to the attribute
2862       // form).
2863       if (OldConstInit && OldConstInit->isConstinit())
2864         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2865                                  /*AttrBeforeInit=*/true);
2866     } else if (NewConstInit) {
2867       // This is the first time we've been told that this declaration should
2868       // have a constant initializer. If we already saw the initializing
2869       // declaration, this is too late.
2870       if (InitDecl && InitDecl != NewVD) {
2871         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2872                                  /*AttrBeforeInit=*/false);
2873         NewVD->dropAttr<ConstInitAttr>();
2874       }
2875     }
2876   }
2877 
2878   // Attributes declared post-definition are currently ignored.
2879   checkNewAttributesAfterDef(*this, New, Old);
2880 
2881   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2882     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2883       if (!OldA->isEquivalent(NewA)) {
2884         // This redeclaration changes __asm__ label.
2885         Diag(New->getLocation(), diag::err_different_asm_label);
2886         Diag(OldA->getLocation(), diag::note_previous_declaration);
2887       }
2888     } else if (Old->isUsed()) {
2889       // This redeclaration adds an __asm__ label to a declaration that has
2890       // already been ODR-used.
2891       Diag(New->getLocation(), diag::err_late_asm_label_name)
2892         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2893     }
2894   }
2895 
2896   // Re-declaration cannot add abi_tag's.
2897   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2898     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2899       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2900         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2901                       NewTag) == OldAbiTagAttr->tags_end()) {
2902           Diag(NewAbiTagAttr->getLocation(),
2903                diag::err_new_abi_tag_on_redeclaration)
2904               << NewTag;
2905           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2906         }
2907       }
2908     } else {
2909       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2910       Diag(Old->getLocation(), diag::note_previous_declaration);
2911     }
2912   }
2913 
2914   // This redeclaration adds a section attribute.
2915   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2916     if (auto *VD = dyn_cast<VarDecl>(New)) {
2917       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2918         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2919         Diag(Old->getLocation(), diag::note_previous_declaration);
2920       }
2921     }
2922   }
2923 
2924   // Redeclaration adds code-seg attribute.
2925   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2926   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2927       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2928     Diag(New->getLocation(), diag::warn_mismatched_section)
2929          << 0 /*codeseg*/;
2930     Diag(Old->getLocation(), diag::note_previous_declaration);
2931   }
2932 
2933   if (!Old->hasAttrs())
2934     return;
2935 
2936   bool foundAny = New->hasAttrs();
2937 
2938   // Ensure that any moving of objects within the allocated map is done before
2939   // we process them.
2940   if (!foundAny) New->setAttrs(AttrVec());
2941 
2942   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2943     // Ignore deprecated/unavailable/availability attributes if requested.
2944     AvailabilityMergeKind LocalAMK = AMK_None;
2945     if (isa<DeprecatedAttr>(I) ||
2946         isa<UnavailableAttr>(I) ||
2947         isa<AvailabilityAttr>(I)) {
2948       switch (AMK) {
2949       case AMK_None:
2950         continue;
2951 
2952       case AMK_Redeclaration:
2953       case AMK_Override:
2954       case AMK_ProtocolImplementation:
2955         LocalAMK = AMK;
2956         break;
2957       }
2958     }
2959 
2960     // Already handled.
2961     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
2962       continue;
2963 
2964     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2965       foundAny = true;
2966   }
2967 
2968   if (mergeAlignedAttrs(*this, New, Old))
2969     foundAny = true;
2970 
2971   if (!foundAny) New->dropAttrs();
2972 }
2973 
2974 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2975 /// to the new one.
2976 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2977                                      const ParmVarDecl *oldDecl,
2978                                      Sema &S) {
2979   // C++11 [dcl.attr.depend]p2:
2980   //   The first declaration of a function shall specify the
2981   //   carries_dependency attribute for its declarator-id if any declaration
2982   //   of the function specifies the carries_dependency attribute.
2983   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2984   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2985     S.Diag(CDA->getLocation(),
2986            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2987     // Find the first declaration of the parameter.
2988     // FIXME: Should we build redeclaration chains for function parameters?
2989     const FunctionDecl *FirstFD =
2990       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2991     const ParmVarDecl *FirstVD =
2992       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2993     S.Diag(FirstVD->getLocation(),
2994            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2995   }
2996 
2997   if (!oldDecl->hasAttrs())
2998     return;
2999 
3000   bool foundAny = newDecl->hasAttrs();
3001 
3002   // Ensure that any moving of objects within the allocated map is
3003   // done before we process them.
3004   if (!foundAny) newDecl->setAttrs(AttrVec());
3005 
3006   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3007     if (!DeclHasAttr(newDecl, I)) {
3008       InheritableAttr *newAttr =
3009         cast<InheritableParamAttr>(I->clone(S.Context));
3010       newAttr->setInherited(true);
3011       newDecl->addAttr(newAttr);
3012       foundAny = true;
3013     }
3014   }
3015 
3016   if (!foundAny) newDecl->dropAttrs();
3017 }
3018 
3019 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3020                                 const ParmVarDecl *OldParam,
3021                                 Sema &S) {
3022   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3023     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3024       if (*Oldnullability != *Newnullability) {
3025         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3026           << DiagNullabilityKind(
3027                *Newnullability,
3028                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3029                 != 0))
3030           << DiagNullabilityKind(
3031                *Oldnullability,
3032                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3033                 != 0));
3034         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3035       }
3036     } else {
3037       QualType NewT = NewParam->getType();
3038       NewT = S.Context.getAttributedType(
3039                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3040                          NewT, NewT);
3041       NewParam->setType(NewT);
3042     }
3043   }
3044 }
3045 
3046 namespace {
3047 
3048 /// Used in MergeFunctionDecl to keep track of function parameters in
3049 /// C.
3050 struct GNUCompatibleParamWarning {
3051   ParmVarDecl *OldParm;
3052   ParmVarDecl *NewParm;
3053   QualType PromotedType;
3054 };
3055 
3056 } // end anonymous namespace
3057 
3058 // Determine whether the previous declaration was a definition, implicit
3059 // declaration, or a declaration.
3060 template <typename T>
3061 static std::pair<diag::kind, SourceLocation>
3062 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3063   diag::kind PrevDiag;
3064   SourceLocation OldLocation = Old->getLocation();
3065   if (Old->isThisDeclarationADefinition())
3066     PrevDiag = diag::note_previous_definition;
3067   else if (Old->isImplicit()) {
3068     PrevDiag = diag::note_previous_implicit_declaration;
3069     if (OldLocation.isInvalid())
3070       OldLocation = New->getLocation();
3071   } else
3072     PrevDiag = diag::note_previous_declaration;
3073   return std::make_pair(PrevDiag, OldLocation);
3074 }
3075 
3076 /// canRedefineFunction - checks if a function can be redefined. Currently,
3077 /// only extern inline functions can be redefined, and even then only in
3078 /// GNU89 mode.
3079 static bool canRedefineFunction(const FunctionDecl *FD,
3080                                 const LangOptions& LangOpts) {
3081   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3082           !LangOpts.CPlusPlus &&
3083           FD->isInlineSpecified() &&
3084           FD->getStorageClass() == SC_Extern);
3085 }
3086 
3087 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3088   const AttributedType *AT = T->getAs<AttributedType>();
3089   while (AT && !AT->isCallingConv())
3090     AT = AT->getModifiedType()->getAs<AttributedType>();
3091   return AT;
3092 }
3093 
3094 template <typename T>
3095 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3096   const DeclContext *DC = Old->getDeclContext();
3097   if (DC->isRecord())
3098     return false;
3099 
3100   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3101   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3102     return true;
3103   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3104     return true;
3105   return false;
3106 }
3107 
3108 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3109 static bool isExternC(VarTemplateDecl *) { return false; }
3110 
3111 /// Check whether a redeclaration of an entity introduced by a
3112 /// using-declaration is valid, given that we know it's not an overload
3113 /// (nor a hidden tag declaration).
3114 template<typename ExpectedDecl>
3115 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3116                                    ExpectedDecl *New) {
3117   // C++11 [basic.scope.declarative]p4:
3118   //   Given a set of declarations in a single declarative region, each of
3119   //   which specifies the same unqualified name,
3120   //   -- they shall all refer to the same entity, or all refer to functions
3121   //      and function templates; or
3122   //   -- exactly one declaration shall declare a class name or enumeration
3123   //      name that is not a typedef name and the other declarations shall all
3124   //      refer to the same variable or enumerator, or all refer to functions
3125   //      and function templates; in this case the class name or enumeration
3126   //      name is hidden (3.3.10).
3127 
3128   // C++11 [namespace.udecl]p14:
3129   //   If a function declaration in namespace scope or block scope has the
3130   //   same name and the same parameter-type-list as a function introduced
3131   //   by a using-declaration, and the declarations do not declare the same
3132   //   function, the program is ill-formed.
3133 
3134   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3135   if (Old &&
3136       !Old->getDeclContext()->getRedeclContext()->Equals(
3137           New->getDeclContext()->getRedeclContext()) &&
3138       !(isExternC(Old) && isExternC(New)))
3139     Old = nullptr;
3140 
3141   if (!Old) {
3142     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3143     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3144     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3145     return true;
3146   }
3147   return false;
3148 }
3149 
3150 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3151                                             const FunctionDecl *B) {
3152   assert(A->getNumParams() == B->getNumParams());
3153 
3154   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3155     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3156     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3157     if (AttrA == AttrB)
3158       return true;
3159     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3160            AttrA->isDynamic() == AttrB->isDynamic();
3161   };
3162 
3163   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3164 }
3165 
3166 /// If necessary, adjust the semantic declaration context for a qualified
3167 /// declaration to name the correct inline namespace within the qualifier.
3168 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3169                                                DeclaratorDecl *OldD) {
3170   // The only case where we need to update the DeclContext is when
3171   // redeclaration lookup for a qualified name finds a declaration
3172   // in an inline namespace within the context named by the qualifier:
3173   //
3174   //   inline namespace N { int f(); }
3175   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3176   //
3177   // For unqualified declarations, the semantic context *can* change
3178   // along the redeclaration chain (for local extern declarations,
3179   // extern "C" declarations, and friend declarations in particular).
3180   if (!NewD->getQualifier())
3181     return;
3182 
3183   // NewD is probably already in the right context.
3184   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3185   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3186   if (NamedDC->Equals(SemaDC))
3187     return;
3188 
3189   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3190           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3191          "unexpected context for redeclaration");
3192 
3193   auto *LexDC = NewD->getLexicalDeclContext();
3194   auto FixSemaDC = [=](NamedDecl *D) {
3195     if (!D)
3196       return;
3197     D->setDeclContext(SemaDC);
3198     D->setLexicalDeclContext(LexDC);
3199   };
3200 
3201   FixSemaDC(NewD);
3202   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3203     FixSemaDC(FD->getDescribedFunctionTemplate());
3204   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3205     FixSemaDC(VD->getDescribedVarTemplate());
3206 }
3207 
3208 /// MergeFunctionDecl - We just parsed a function 'New' from
3209 /// declarator D which has the same name and scope as a previous
3210 /// declaration 'Old'.  Figure out how to resolve this situation,
3211 /// merging decls or emitting diagnostics as appropriate.
3212 ///
3213 /// In C++, New and Old must be declarations that are not
3214 /// overloaded. Use IsOverload to determine whether New and Old are
3215 /// overloaded, and to select the Old declaration that New should be
3216 /// merged with.
3217 ///
3218 /// Returns true if there was an error, false otherwise.
3219 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3220                              Scope *S, bool MergeTypeWithOld) {
3221   // Verify the old decl was also a function.
3222   FunctionDecl *Old = OldD->getAsFunction();
3223   if (!Old) {
3224     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3225       if (New->getFriendObjectKind()) {
3226         Diag(New->getLocation(), diag::err_using_decl_friend);
3227         Diag(Shadow->getTargetDecl()->getLocation(),
3228              diag::note_using_decl_target);
3229         Diag(Shadow->getUsingDecl()->getLocation(),
3230              diag::note_using_decl) << 0;
3231         return true;
3232       }
3233 
3234       // Check whether the two declarations might declare the same function.
3235       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3236         return true;
3237       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3238     } else {
3239       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3240         << New->getDeclName();
3241       notePreviousDefinition(OldD, New->getLocation());
3242       return true;
3243     }
3244   }
3245 
3246   // If the old declaration was found in an inline namespace and the new
3247   // declaration was qualified, update the DeclContext to match.
3248   adjustDeclContextForDeclaratorDecl(New, Old);
3249 
3250   // If the old declaration is invalid, just give up here.
3251   if (Old->isInvalidDecl())
3252     return true;
3253 
3254   // Disallow redeclaration of some builtins.
3255   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3256     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3257     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3258         << Old << Old->getType();
3259     return true;
3260   }
3261 
3262   diag::kind PrevDiag;
3263   SourceLocation OldLocation;
3264   std::tie(PrevDiag, OldLocation) =
3265       getNoteDiagForInvalidRedeclaration(Old, New);
3266 
3267   // Don't complain about this if we're in GNU89 mode and the old function
3268   // is an extern inline function.
3269   // Don't complain about specializations. They are not supposed to have
3270   // storage classes.
3271   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3272       New->getStorageClass() == SC_Static &&
3273       Old->hasExternalFormalLinkage() &&
3274       !New->getTemplateSpecializationInfo() &&
3275       !canRedefineFunction(Old, getLangOpts())) {
3276     if (getLangOpts().MicrosoftExt) {
3277       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3278       Diag(OldLocation, PrevDiag);
3279     } else {
3280       Diag(New->getLocation(), diag::err_static_non_static) << New;
3281       Diag(OldLocation, PrevDiag);
3282       return true;
3283     }
3284   }
3285 
3286   if (New->hasAttr<InternalLinkageAttr>() &&
3287       !Old->hasAttr<InternalLinkageAttr>()) {
3288     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3289         << New->getDeclName();
3290     notePreviousDefinition(Old, New->getLocation());
3291     New->dropAttr<InternalLinkageAttr>();
3292   }
3293 
3294   if (CheckRedeclarationModuleOwnership(New, Old))
3295     return true;
3296 
3297   if (!getLangOpts().CPlusPlus) {
3298     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3299     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3300       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3301         << New << OldOvl;
3302 
3303       // Try our best to find a decl that actually has the overloadable
3304       // attribute for the note. In most cases (e.g. programs with only one
3305       // broken declaration/definition), this won't matter.
3306       //
3307       // FIXME: We could do this if we juggled some extra state in
3308       // OverloadableAttr, rather than just removing it.
3309       const Decl *DiagOld = Old;
3310       if (OldOvl) {
3311         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3312           const auto *A = D->getAttr<OverloadableAttr>();
3313           return A && !A->isImplicit();
3314         });
3315         // If we've implicitly added *all* of the overloadable attrs to this
3316         // chain, emitting a "previous redecl" note is pointless.
3317         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3318       }
3319 
3320       if (DiagOld)
3321         Diag(DiagOld->getLocation(),
3322              diag::note_attribute_overloadable_prev_overload)
3323           << OldOvl;
3324 
3325       if (OldOvl)
3326         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3327       else
3328         New->dropAttr<OverloadableAttr>();
3329     }
3330   }
3331 
3332   // If a function is first declared with a calling convention, but is later
3333   // declared or defined without one, all following decls assume the calling
3334   // convention of the first.
3335   //
3336   // It's OK if a function is first declared without a calling convention,
3337   // but is later declared or defined with the default calling convention.
3338   //
3339   // To test if either decl has an explicit calling convention, we look for
3340   // AttributedType sugar nodes on the type as written.  If they are missing or
3341   // were canonicalized away, we assume the calling convention was implicit.
3342   //
3343   // Note also that we DO NOT return at this point, because we still have
3344   // other tests to run.
3345   QualType OldQType = Context.getCanonicalType(Old->getType());
3346   QualType NewQType = Context.getCanonicalType(New->getType());
3347   const FunctionType *OldType = cast<FunctionType>(OldQType);
3348   const FunctionType *NewType = cast<FunctionType>(NewQType);
3349   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3350   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3351   bool RequiresAdjustment = false;
3352 
3353   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3354     FunctionDecl *First = Old->getFirstDecl();
3355     const FunctionType *FT =
3356         First->getType().getCanonicalType()->castAs<FunctionType>();
3357     FunctionType::ExtInfo FI = FT->getExtInfo();
3358     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3359     if (!NewCCExplicit) {
3360       // Inherit the CC from the previous declaration if it was specified
3361       // there but not here.
3362       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3363       RequiresAdjustment = true;
3364     } else if (Old->getBuiltinID()) {
3365       // Builtin attribute isn't propagated to the new one yet at this point,
3366       // so we check if the old one is a builtin.
3367 
3368       // Calling Conventions on a Builtin aren't really useful and setting a
3369       // default calling convention and cdecl'ing some builtin redeclarations is
3370       // common, so warn and ignore the calling convention on the redeclaration.
3371       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3372           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3373           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3374       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3375       RequiresAdjustment = true;
3376     } else {
3377       // Calling conventions aren't compatible, so complain.
3378       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3379       Diag(New->getLocation(), diag::err_cconv_change)
3380         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3381         << !FirstCCExplicit
3382         << (!FirstCCExplicit ? "" :
3383             FunctionType::getNameForCallConv(FI.getCC()));
3384 
3385       // Put the note on the first decl, since it is the one that matters.
3386       Diag(First->getLocation(), diag::note_previous_declaration);
3387       return true;
3388     }
3389   }
3390 
3391   // FIXME: diagnose the other way around?
3392   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3393     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3394     RequiresAdjustment = true;
3395   }
3396 
3397   // Merge regparm attribute.
3398   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3399       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3400     if (NewTypeInfo.getHasRegParm()) {
3401       Diag(New->getLocation(), diag::err_regparm_mismatch)
3402         << NewType->getRegParmType()
3403         << OldType->getRegParmType();
3404       Diag(OldLocation, diag::note_previous_declaration);
3405       return true;
3406     }
3407 
3408     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3409     RequiresAdjustment = true;
3410   }
3411 
3412   // Merge ns_returns_retained attribute.
3413   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3414     if (NewTypeInfo.getProducesResult()) {
3415       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3416           << "'ns_returns_retained'";
3417       Diag(OldLocation, diag::note_previous_declaration);
3418       return true;
3419     }
3420 
3421     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3422     RequiresAdjustment = true;
3423   }
3424 
3425   if (OldTypeInfo.getNoCallerSavedRegs() !=
3426       NewTypeInfo.getNoCallerSavedRegs()) {
3427     if (NewTypeInfo.getNoCallerSavedRegs()) {
3428       AnyX86NoCallerSavedRegistersAttr *Attr =
3429         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3430       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3431       Diag(OldLocation, diag::note_previous_declaration);
3432       return true;
3433     }
3434 
3435     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3436     RequiresAdjustment = true;
3437   }
3438 
3439   if (RequiresAdjustment) {
3440     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3441     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3442     New->setType(QualType(AdjustedType, 0));
3443     NewQType = Context.getCanonicalType(New->getType());
3444   }
3445 
3446   // If this redeclaration makes the function inline, we may need to add it to
3447   // UndefinedButUsed.
3448   if (!Old->isInlined() && New->isInlined() &&
3449       !New->hasAttr<GNUInlineAttr>() &&
3450       !getLangOpts().GNUInline &&
3451       Old->isUsed(false) &&
3452       !Old->isDefined() && !New->isThisDeclarationADefinition())
3453     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3454                                            SourceLocation()));
3455 
3456   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3457   // about it.
3458   if (New->hasAttr<GNUInlineAttr>() &&
3459       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3460     UndefinedButUsed.erase(Old->getCanonicalDecl());
3461   }
3462 
3463   // If pass_object_size params don't match up perfectly, this isn't a valid
3464   // redeclaration.
3465   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3466       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3467     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3468         << New->getDeclName();
3469     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3470     return true;
3471   }
3472 
3473   if (getLangOpts().CPlusPlus) {
3474     // C++1z [over.load]p2
3475     //   Certain function declarations cannot be overloaded:
3476     //     -- Function declarations that differ only in the return type,
3477     //        the exception specification, or both cannot be overloaded.
3478 
3479     // Check the exception specifications match. This may recompute the type of
3480     // both Old and New if it resolved exception specifications, so grab the
3481     // types again after this. Because this updates the type, we do this before
3482     // any of the other checks below, which may update the "de facto" NewQType
3483     // but do not necessarily update the type of New.
3484     if (CheckEquivalentExceptionSpec(Old, New))
3485       return true;
3486     OldQType = Context.getCanonicalType(Old->getType());
3487     NewQType = Context.getCanonicalType(New->getType());
3488 
3489     // Go back to the type source info to compare the declared return types,
3490     // per C++1y [dcl.type.auto]p13:
3491     //   Redeclarations or specializations of a function or function template
3492     //   with a declared return type that uses a placeholder type shall also
3493     //   use that placeholder, not a deduced type.
3494     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3495     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3496     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3497         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3498                                        OldDeclaredReturnType)) {
3499       QualType ResQT;
3500       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3501           OldDeclaredReturnType->isObjCObjectPointerType())
3502         // FIXME: This does the wrong thing for a deduced return type.
3503         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3504       if (ResQT.isNull()) {
3505         if (New->isCXXClassMember() && New->isOutOfLine())
3506           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3507               << New << New->getReturnTypeSourceRange();
3508         else
3509           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3510               << New->getReturnTypeSourceRange();
3511         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3512                                     << Old->getReturnTypeSourceRange();
3513         return true;
3514       }
3515       else
3516         NewQType = ResQT;
3517     }
3518 
3519     QualType OldReturnType = OldType->getReturnType();
3520     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3521     if (OldReturnType != NewReturnType) {
3522       // If this function has a deduced return type and has already been
3523       // defined, copy the deduced value from the old declaration.
3524       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3525       if (OldAT && OldAT->isDeduced()) {
3526         New->setType(
3527             SubstAutoType(New->getType(),
3528                           OldAT->isDependentType() ? Context.DependentTy
3529                                                    : OldAT->getDeducedType()));
3530         NewQType = Context.getCanonicalType(
3531             SubstAutoType(NewQType,
3532                           OldAT->isDependentType() ? Context.DependentTy
3533                                                    : OldAT->getDeducedType()));
3534       }
3535     }
3536 
3537     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3538     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3539     if (OldMethod && NewMethod) {
3540       // Preserve triviality.
3541       NewMethod->setTrivial(OldMethod->isTrivial());
3542 
3543       // MSVC allows explicit template specialization at class scope:
3544       // 2 CXXMethodDecls referring to the same function will be injected.
3545       // We don't want a redeclaration error.
3546       bool IsClassScopeExplicitSpecialization =
3547                               OldMethod->isFunctionTemplateSpecialization() &&
3548                               NewMethod->isFunctionTemplateSpecialization();
3549       bool isFriend = NewMethod->getFriendObjectKind();
3550 
3551       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3552           !IsClassScopeExplicitSpecialization) {
3553         //    -- Member function declarations with the same name and the
3554         //       same parameter types cannot be overloaded if any of them
3555         //       is a static member function declaration.
3556         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3557           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3558           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3559           return true;
3560         }
3561 
3562         // C++ [class.mem]p1:
3563         //   [...] A member shall not be declared twice in the
3564         //   member-specification, except that a nested class or member
3565         //   class template can be declared and then later defined.
3566         if (!inTemplateInstantiation()) {
3567           unsigned NewDiag;
3568           if (isa<CXXConstructorDecl>(OldMethod))
3569             NewDiag = diag::err_constructor_redeclared;
3570           else if (isa<CXXDestructorDecl>(NewMethod))
3571             NewDiag = diag::err_destructor_redeclared;
3572           else if (isa<CXXConversionDecl>(NewMethod))
3573             NewDiag = diag::err_conv_function_redeclared;
3574           else
3575             NewDiag = diag::err_member_redeclared;
3576 
3577           Diag(New->getLocation(), NewDiag);
3578         } else {
3579           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3580             << New << New->getType();
3581         }
3582         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3583         return true;
3584 
3585       // Complain if this is an explicit declaration of a special
3586       // member that was initially declared implicitly.
3587       //
3588       // As an exception, it's okay to befriend such methods in order
3589       // to permit the implicit constructor/destructor/operator calls.
3590       } else if (OldMethod->isImplicit()) {
3591         if (isFriend) {
3592           NewMethod->setImplicit();
3593         } else {
3594           Diag(NewMethod->getLocation(),
3595                diag::err_definition_of_implicitly_declared_member)
3596             << New << getSpecialMember(OldMethod);
3597           return true;
3598         }
3599       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3600         Diag(NewMethod->getLocation(),
3601              diag::err_definition_of_explicitly_defaulted_member)
3602           << getSpecialMember(OldMethod);
3603         return true;
3604       }
3605     }
3606 
3607     // C++11 [dcl.attr.noreturn]p1:
3608     //   The first declaration of a function shall specify the noreturn
3609     //   attribute if any declaration of that function specifies the noreturn
3610     //   attribute.
3611     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3612     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3613       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3614       Diag(Old->getFirstDecl()->getLocation(),
3615            diag::note_noreturn_missing_first_decl);
3616     }
3617 
3618     // C++11 [dcl.attr.depend]p2:
3619     //   The first declaration of a function shall specify the
3620     //   carries_dependency attribute for its declarator-id if any declaration
3621     //   of the function specifies the carries_dependency attribute.
3622     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3623     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3624       Diag(CDA->getLocation(),
3625            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3626       Diag(Old->getFirstDecl()->getLocation(),
3627            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3628     }
3629 
3630     // (C++98 8.3.5p3):
3631     //   All declarations for a function shall agree exactly in both the
3632     //   return type and the parameter-type-list.
3633     // We also want to respect all the extended bits except noreturn.
3634 
3635     // noreturn should now match unless the old type info didn't have it.
3636     QualType OldQTypeForComparison = OldQType;
3637     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3638       auto *OldType = OldQType->castAs<FunctionProtoType>();
3639       const FunctionType *OldTypeForComparison
3640         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3641       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3642       assert(OldQTypeForComparison.isCanonical());
3643     }
3644 
3645     if (haveIncompatibleLanguageLinkages(Old, New)) {
3646       // As a special case, retain the language linkage from previous
3647       // declarations of a friend function as an extension.
3648       //
3649       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3650       // and is useful because there's otherwise no way to specify language
3651       // linkage within class scope.
3652       //
3653       // Check cautiously as the friend object kind isn't yet complete.
3654       if (New->getFriendObjectKind() != Decl::FOK_None) {
3655         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3656         Diag(OldLocation, PrevDiag);
3657       } else {
3658         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3659         Diag(OldLocation, PrevDiag);
3660         return true;
3661       }
3662     }
3663 
3664     // If the function types are compatible, merge the declarations. Ignore the
3665     // exception specifier because it was already checked above in
3666     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3667     // about incompatible types under -fms-compatibility.
3668     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3669                                                          NewQType))
3670       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3671 
3672     // If the types are imprecise (due to dependent constructs in friends or
3673     // local extern declarations), it's OK if they differ. We'll check again
3674     // during instantiation.
3675     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3676       return false;
3677 
3678     // Fall through for conflicting redeclarations and redefinitions.
3679   }
3680 
3681   // C: Function types need to be compatible, not identical. This handles
3682   // duplicate function decls like "void f(int); void f(enum X);" properly.
3683   if (!getLangOpts().CPlusPlus &&
3684       Context.typesAreCompatible(OldQType, NewQType)) {
3685     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3686     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3687     const FunctionProtoType *OldProto = nullptr;
3688     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3689         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3690       // The old declaration provided a function prototype, but the
3691       // new declaration does not. Merge in the prototype.
3692       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3693       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3694       NewQType =
3695           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3696                                   OldProto->getExtProtoInfo());
3697       New->setType(NewQType);
3698       New->setHasInheritedPrototype();
3699 
3700       // Synthesize parameters with the same types.
3701       SmallVector<ParmVarDecl*, 16> Params;
3702       for (const auto &ParamType : OldProto->param_types()) {
3703         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3704                                                  SourceLocation(), nullptr,
3705                                                  ParamType, /*TInfo=*/nullptr,
3706                                                  SC_None, nullptr);
3707         Param->setScopeInfo(0, Params.size());
3708         Param->setImplicit();
3709         Params.push_back(Param);
3710       }
3711 
3712       New->setParams(Params);
3713     }
3714 
3715     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3716   }
3717 
3718   // Check if the function types are compatible when pointer size address
3719   // spaces are ignored.
3720   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3721     return false;
3722 
3723   // GNU C permits a K&R definition to follow a prototype declaration
3724   // if the declared types of the parameters in the K&R definition
3725   // match the types in the prototype declaration, even when the
3726   // promoted types of the parameters from the K&R definition differ
3727   // from the types in the prototype. GCC then keeps the types from
3728   // the prototype.
3729   //
3730   // If a variadic prototype is followed by a non-variadic K&R definition,
3731   // the K&R definition becomes variadic.  This is sort of an edge case, but
3732   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3733   // C99 6.9.1p8.
3734   if (!getLangOpts().CPlusPlus &&
3735       Old->hasPrototype() && !New->hasPrototype() &&
3736       New->getType()->getAs<FunctionProtoType>() &&
3737       Old->getNumParams() == New->getNumParams()) {
3738     SmallVector<QualType, 16> ArgTypes;
3739     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3740     const FunctionProtoType *OldProto
3741       = Old->getType()->getAs<FunctionProtoType>();
3742     const FunctionProtoType *NewProto
3743       = New->getType()->getAs<FunctionProtoType>();
3744 
3745     // Determine whether this is the GNU C extension.
3746     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3747                                                NewProto->getReturnType());
3748     bool LooseCompatible = !MergedReturn.isNull();
3749     for (unsigned Idx = 0, End = Old->getNumParams();
3750          LooseCompatible && Idx != End; ++Idx) {
3751       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3752       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3753       if (Context.typesAreCompatible(OldParm->getType(),
3754                                      NewProto->getParamType(Idx))) {
3755         ArgTypes.push_back(NewParm->getType());
3756       } else if (Context.typesAreCompatible(OldParm->getType(),
3757                                             NewParm->getType(),
3758                                             /*CompareUnqualified=*/true)) {
3759         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3760                                            NewProto->getParamType(Idx) };
3761         Warnings.push_back(Warn);
3762         ArgTypes.push_back(NewParm->getType());
3763       } else
3764         LooseCompatible = false;
3765     }
3766 
3767     if (LooseCompatible) {
3768       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3769         Diag(Warnings[Warn].NewParm->getLocation(),
3770              diag::ext_param_promoted_not_compatible_with_prototype)
3771           << Warnings[Warn].PromotedType
3772           << Warnings[Warn].OldParm->getType();
3773         if (Warnings[Warn].OldParm->getLocation().isValid())
3774           Diag(Warnings[Warn].OldParm->getLocation(),
3775                diag::note_previous_declaration);
3776       }
3777 
3778       if (MergeTypeWithOld)
3779         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3780                                              OldProto->getExtProtoInfo()));
3781       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3782     }
3783 
3784     // Fall through to diagnose conflicting types.
3785   }
3786 
3787   // A function that has already been declared has been redeclared or
3788   // defined with a different type; show an appropriate diagnostic.
3789 
3790   // If the previous declaration was an implicitly-generated builtin
3791   // declaration, then at the very least we should use a specialized note.
3792   unsigned BuiltinID;
3793   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3794     // If it's actually a library-defined builtin function like 'malloc'
3795     // or 'printf', just warn about the incompatible redeclaration.
3796     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3797       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3798       Diag(OldLocation, diag::note_previous_builtin_declaration)
3799         << Old << Old->getType();
3800       return false;
3801     }
3802 
3803     PrevDiag = diag::note_previous_builtin_declaration;
3804   }
3805 
3806   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3807   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3808   return true;
3809 }
3810 
3811 /// Completes the merge of two function declarations that are
3812 /// known to be compatible.
3813 ///
3814 /// This routine handles the merging of attributes and other
3815 /// properties of function declarations from the old declaration to
3816 /// the new declaration, once we know that New is in fact a
3817 /// redeclaration of Old.
3818 ///
3819 /// \returns false
3820 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3821                                         Scope *S, bool MergeTypeWithOld) {
3822   // Merge the attributes
3823   mergeDeclAttributes(New, Old);
3824 
3825   // Merge "pure" flag.
3826   if (Old->isPure())
3827     New->setPure();
3828 
3829   // Merge "used" flag.
3830   if (Old->getMostRecentDecl()->isUsed(false))
3831     New->setIsUsed();
3832 
3833   // Merge attributes from the parameters.  These can mismatch with K&R
3834   // declarations.
3835   if (New->getNumParams() == Old->getNumParams())
3836       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3837         ParmVarDecl *NewParam = New->getParamDecl(i);
3838         ParmVarDecl *OldParam = Old->getParamDecl(i);
3839         mergeParamDeclAttributes(NewParam, OldParam, *this);
3840         mergeParamDeclTypes(NewParam, OldParam, *this);
3841       }
3842 
3843   if (getLangOpts().CPlusPlus)
3844     return MergeCXXFunctionDecl(New, Old, S);
3845 
3846   // Merge the function types so the we get the composite types for the return
3847   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3848   // was visible.
3849   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3850   if (!Merged.isNull() && MergeTypeWithOld)
3851     New->setType(Merged);
3852 
3853   return false;
3854 }
3855 
3856 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3857                                 ObjCMethodDecl *oldMethod) {
3858   // Merge the attributes, including deprecated/unavailable
3859   AvailabilityMergeKind MergeKind =
3860     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3861       ? AMK_ProtocolImplementation
3862       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3863                                                        : AMK_Override;
3864 
3865   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3866 
3867   // Merge attributes from the parameters.
3868   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3869                                        oe = oldMethod->param_end();
3870   for (ObjCMethodDecl::param_iterator
3871          ni = newMethod->param_begin(), ne = newMethod->param_end();
3872        ni != ne && oi != oe; ++ni, ++oi)
3873     mergeParamDeclAttributes(*ni, *oi, *this);
3874 
3875   CheckObjCMethodOverride(newMethod, oldMethod);
3876 }
3877 
3878 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3879   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3880 
3881   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3882          ? diag::err_redefinition_different_type
3883          : diag::err_redeclaration_different_type)
3884     << New->getDeclName() << New->getType() << Old->getType();
3885 
3886   diag::kind PrevDiag;
3887   SourceLocation OldLocation;
3888   std::tie(PrevDiag, OldLocation)
3889     = getNoteDiagForInvalidRedeclaration(Old, New);
3890   S.Diag(OldLocation, PrevDiag);
3891   New->setInvalidDecl();
3892 }
3893 
3894 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3895 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3896 /// emitting diagnostics as appropriate.
3897 ///
3898 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3899 /// to here in AddInitializerToDecl. We can't check them before the initializer
3900 /// is attached.
3901 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3902                              bool MergeTypeWithOld) {
3903   if (New->isInvalidDecl() || Old->isInvalidDecl())
3904     return;
3905 
3906   QualType MergedT;
3907   if (getLangOpts().CPlusPlus) {
3908     if (New->getType()->isUndeducedType()) {
3909       // We don't know what the new type is until the initializer is attached.
3910       return;
3911     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3912       // These could still be something that needs exception specs checked.
3913       return MergeVarDeclExceptionSpecs(New, Old);
3914     }
3915     // C++ [basic.link]p10:
3916     //   [...] the types specified by all declarations referring to a given
3917     //   object or function shall be identical, except that declarations for an
3918     //   array object can specify array types that differ by the presence or
3919     //   absence of a major array bound (8.3.4).
3920     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3921       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3922       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3923 
3924       // We are merging a variable declaration New into Old. If it has an array
3925       // bound, and that bound differs from Old's bound, we should diagnose the
3926       // mismatch.
3927       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3928         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3929              PrevVD = PrevVD->getPreviousDecl()) {
3930           QualType PrevVDTy = PrevVD->getType();
3931           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3932             continue;
3933 
3934           if (!Context.hasSameType(New->getType(), PrevVDTy))
3935             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3936         }
3937       }
3938 
3939       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3940         if (Context.hasSameType(OldArray->getElementType(),
3941                                 NewArray->getElementType()))
3942           MergedT = New->getType();
3943       }
3944       // FIXME: Check visibility. New is hidden but has a complete type. If New
3945       // has no array bound, it should not inherit one from Old, if Old is not
3946       // visible.
3947       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3948         if (Context.hasSameType(OldArray->getElementType(),
3949                                 NewArray->getElementType()))
3950           MergedT = Old->getType();
3951       }
3952     }
3953     else if (New->getType()->isObjCObjectPointerType() &&
3954                Old->getType()->isObjCObjectPointerType()) {
3955       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3956                                               Old->getType());
3957     }
3958   } else {
3959     // C 6.2.7p2:
3960     //   All declarations that refer to the same object or function shall have
3961     //   compatible type.
3962     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3963   }
3964   if (MergedT.isNull()) {
3965     // It's OK if we couldn't merge types if either type is dependent, for a
3966     // block-scope variable. In other cases (static data members of class
3967     // templates, variable templates, ...), we require the types to be
3968     // equivalent.
3969     // FIXME: The C++ standard doesn't say anything about this.
3970     if ((New->getType()->isDependentType() ||
3971          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3972       // If the old type was dependent, we can't merge with it, so the new type
3973       // becomes dependent for now. We'll reproduce the original type when we
3974       // instantiate the TypeSourceInfo for the variable.
3975       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3976         New->setType(Context.DependentTy);
3977       return;
3978     }
3979     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3980   }
3981 
3982   // Don't actually update the type on the new declaration if the old
3983   // declaration was an extern declaration in a different scope.
3984   if (MergeTypeWithOld)
3985     New->setType(MergedT);
3986 }
3987 
3988 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3989                                   LookupResult &Previous) {
3990   // C11 6.2.7p4:
3991   //   For an identifier with internal or external linkage declared
3992   //   in a scope in which a prior declaration of that identifier is
3993   //   visible, if the prior declaration specifies internal or
3994   //   external linkage, the type of the identifier at the later
3995   //   declaration becomes the composite type.
3996   //
3997   // If the variable isn't visible, we do not merge with its type.
3998   if (Previous.isShadowed())
3999     return false;
4000 
4001   if (S.getLangOpts().CPlusPlus) {
4002     // C++11 [dcl.array]p3:
4003     //   If there is a preceding declaration of the entity in the same
4004     //   scope in which the bound was specified, an omitted array bound
4005     //   is taken to be the same as in that earlier declaration.
4006     return NewVD->isPreviousDeclInSameBlockScope() ||
4007            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4008             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4009   } else {
4010     // If the old declaration was function-local, don't merge with its
4011     // type unless we're in the same function.
4012     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4013            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4014   }
4015 }
4016 
4017 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4018 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4019 /// situation, merging decls or emitting diagnostics as appropriate.
4020 ///
4021 /// Tentative definition rules (C99 6.9.2p2) are checked by
4022 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4023 /// definitions here, since the initializer hasn't been attached.
4024 ///
4025 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4026   // If the new decl is already invalid, don't do any other checking.
4027   if (New->isInvalidDecl())
4028     return;
4029 
4030   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4031     return;
4032 
4033   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4034 
4035   // Verify the old decl was also a variable or variable template.
4036   VarDecl *Old = nullptr;
4037   VarTemplateDecl *OldTemplate = nullptr;
4038   if (Previous.isSingleResult()) {
4039     if (NewTemplate) {
4040       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4041       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4042 
4043       if (auto *Shadow =
4044               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4045         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4046           return New->setInvalidDecl();
4047     } else {
4048       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4049 
4050       if (auto *Shadow =
4051               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4052         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4053           return New->setInvalidDecl();
4054     }
4055   }
4056   if (!Old) {
4057     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4058         << New->getDeclName();
4059     notePreviousDefinition(Previous.getRepresentativeDecl(),
4060                            New->getLocation());
4061     return New->setInvalidDecl();
4062   }
4063 
4064   // If the old declaration was found in an inline namespace and the new
4065   // declaration was qualified, update the DeclContext to match.
4066   adjustDeclContextForDeclaratorDecl(New, Old);
4067 
4068   // Ensure the template parameters are compatible.
4069   if (NewTemplate &&
4070       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4071                                       OldTemplate->getTemplateParameters(),
4072                                       /*Complain=*/true, TPL_TemplateMatch))
4073     return New->setInvalidDecl();
4074 
4075   // C++ [class.mem]p1:
4076   //   A member shall not be declared twice in the member-specification [...]
4077   //
4078   // Here, we need only consider static data members.
4079   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4080     Diag(New->getLocation(), diag::err_duplicate_member)
4081       << New->getIdentifier();
4082     Diag(Old->getLocation(), diag::note_previous_declaration);
4083     New->setInvalidDecl();
4084   }
4085 
4086   mergeDeclAttributes(New, Old);
4087   // Warn if an already-declared variable is made a weak_import in a subsequent
4088   // declaration
4089   if (New->hasAttr<WeakImportAttr>() &&
4090       Old->getStorageClass() == SC_None &&
4091       !Old->hasAttr<WeakImportAttr>()) {
4092     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4093     notePreviousDefinition(Old, New->getLocation());
4094     // Remove weak_import attribute on new declaration.
4095     New->dropAttr<WeakImportAttr>();
4096   }
4097 
4098   if (New->hasAttr<InternalLinkageAttr>() &&
4099       !Old->hasAttr<InternalLinkageAttr>()) {
4100     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4101         << New->getDeclName();
4102     notePreviousDefinition(Old, New->getLocation());
4103     New->dropAttr<InternalLinkageAttr>();
4104   }
4105 
4106   // Merge the types.
4107   VarDecl *MostRecent = Old->getMostRecentDecl();
4108   if (MostRecent != Old) {
4109     MergeVarDeclTypes(New, MostRecent,
4110                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4111     if (New->isInvalidDecl())
4112       return;
4113   }
4114 
4115   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4116   if (New->isInvalidDecl())
4117     return;
4118 
4119   diag::kind PrevDiag;
4120   SourceLocation OldLocation;
4121   std::tie(PrevDiag, OldLocation) =
4122       getNoteDiagForInvalidRedeclaration(Old, New);
4123 
4124   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4125   if (New->getStorageClass() == SC_Static &&
4126       !New->isStaticDataMember() &&
4127       Old->hasExternalFormalLinkage()) {
4128     if (getLangOpts().MicrosoftExt) {
4129       Diag(New->getLocation(), diag::ext_static_non_static)
4130           << New->getDeclName();
4131       Diag(OldLocation, PrevDiag);
4132     } else {
4133       Diag(New->getLocation(), diag::err_static_non_static)
4134           << New->getDeclName();
4135       Diag(OldLocation, PrevDiag);
4136       return New->setInvalidDecl();
4137     }
4138   }
4139   // C99 6.2.2p4:
4140   //   For an identifier declared with the storage-class specifier
4141   //   extern in a scope in which a prior declaration of that
4142   //   identifier is visible,23) if the prior declaration specifies
4143   //   internal or external linkage, the linkage of the identifier at
4144   //   the later declaration is the same as the linkage specified at
4145   //   the prior declaration. If no prior declaration is visible, or
4146   //   if the prior declaration specifies no linkage, then the
4147   //   identifier has external linkage.
4148   if (New->hasExternalStorage() && Old->hasLinkage())
4149     /* Okay */;
4150   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4151            !New->isStaticDataMember() &&
4152            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4153     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4154     Diag(OldLocation, PrevDiag);
4155     return New->setInvalidDecl();
4156   }
4157 
4158   // Check if extern is followed by non-extern and vice-versa.
4159   if (New->hasExternalStorage() &&
4160       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4161     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4162     Diag(OldLocation, PrevDiag);
4163     return New->setInvalidDecl();
4164   }
4165   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4166       !New->hasExternalStorage()) {
4167     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4168     Diag(OldLocation, PrevDiag);
4169     return New->setInvalidDecl();
4170   }
4171 
4172   if (CheckRedeclarationModuleOwnership(New, Old))
4173     return;
4174 
4175   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4176 
4177   // FIXME: The test for external storage here seems wrong? We still
4178   // need to check for mismatches.
4179   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4180       // Don't complain about out-of-line definitions of static members.
4181       !(Old->getLexicalDeclContext()->isRecord() &&
4182         !New->getLexicalDeclContext()->isRecord())) {
4183     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4184     Diag(OldLocation, PrevDiag);
4185     return New->setInvalidDecl();
4186   }
4187 
4188   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4189     if (VarDecl *Def = Old->getDefinition()) {
4190       // C++1z [dcl.fcn.spec]p4:
4191       //   If the definition of a variable appears in a translation unit before
4192       //   its first declaration as inline, the program is ill-formed.
4193       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4194       Diag(Def->getLocation(), diag::note_previous_definition);
4195     }
4196   }
4197 
4198   // If this redeclaration makes the variable inline, we may need to add it to
4199   // UndefinedButUsed.
4200   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4201       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4202     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4203                                            SourceLocation()));
4204 
4205   if (New->getTLSKind() != Old->getTLSKind()) {
4206     if (!Old->getTLSKind()) {
4207       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4208       Diag(OldLocation, PrevDiag);
4209     } else if (!New->getTLSKind()) {
4210       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4211       Diag(OldLocation, PrevDiag);
4212     } else {
4213       // Do not allow redeclaration to change the variable between requiring
4214       // static and dynamic initialization.
4215       // FIXME: GCC allows this, but uses the TLS keyword on the first
4216       // declaration to determine the kind. Do we need to be compatible here?
4217       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4218         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4219       Diag(OldLocation, PrevDiag);
4220     }
4221   }
4222 
4223   // C++ doesn't have tentative definitions, so go right ahead and check here.
4224   if (getLangOpts().CPlusPlus &&
4225       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4226     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4227         Old->getCanonicalDecl()->isConstexpr()) {
4228       // This definition won't be a definition any more once it's been merged.
4229       Diag(New->getLocation(),
4230            diag::warn_deprecated_redundant_constexpr_static_def);
4231     } else if (VarDecl *Def = Old->getDefinition()) {
4232       if (checkVarDeclRedefinition(Def, New))
4233         return;
4234     }
4235   }
4236 
4237   if (haveIncompatibleLanguageLinkages(Old, New)) {
4238     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4239     Diag(OldLocation, PrevDiag);
4240     New->setInvalidDecl();
4241     return;
4242   }
4243 
4244   // Merge "used" flag.
4245   if (Old->getMostRecentDecl()->isUsed(false))
4246     New->setIsUsed();
4247 
4248   // Keep a chain of previous declarations.
4249   New->setPreviousDecl(Old);
4250   if (NewTemplate)
4251     NewTemplate->setPreviousDecl(OldTemplate);
4252 
4253   // Inherit access appropriately.
4254   New->setAccess(Old->getAccess());
4255   if (NewTemplate)
4256     NewTemplate->setAccess(New->getAccess());
4257 
4258   if (Old->isInline())
4259     New->setImplicitlyInline();
4260 }
4261 
4262 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4263   SourceManager &SrcMgr = getSourceManager();
4264   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4265   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4266   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4267   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4268   auto &HSI = PP.getHeaderSearchInfo();
4269   StringRef HdrFilename =
4270       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4271 
4272   auto noteFromModuleOrInclude = [&](Module *Mod,
4273                                      SourceLocation IncLoc) -> bool {
4274     // Redefinition errors with modules are common with non modular mapped
4275     // headers, example: a non-modular header H in module A that also gets
4276     // included directly in a TU. Pointing twice to the same header/definition
4277     // is confusing, try to get better diagnostics when modules is on.
4278     if (IncLoc.isValid()) {
4279       if (Mod) {
4280         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4281             << HdrFilename.str() << Mod->getFullModuleName();
4282         if (!Mod->DefinitionLoc.isInvalid())
4283           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4284               << Mod->getFullModuleName();
4285       } else {
4286         Diag(IncLoc, diag::note_redefinition_include_same_file)
4287             << HdrFilename.str();
4288       }
4289       return true;
4290     }
4291 
4292     return false;
4293   };
4294 
4295   // Is it the same file and same offset? Provide more information on why
4296   // this leads to a redefinition error.
4297   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4298     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4299     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4300     bool EmittedDiag =
4301         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4302     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4303 
4304     // If the header has no guards, emit a note suggesting one.
4305     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4306       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4307 
4308     if (EmittedDiag)
4309       return;
4310   }
4311 
4312   // Redefinition coming from different files or couldn't do better above.
4313   if (Old->getLocation().isValid())
4314     Diag(Old->getLocation(), diag::note_previous_definition);
4315 }
4316 
4317 /// We've just determined that \p Old and \p New both appear to be definitions
4318 /// of the same variable. Either diagnose or fix the problem.
4319 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4320   if (!hasVisibleDefinition(Old) &&
4321       (New->getFormalLinkage() == InternalLinkage ||
4322        New->isInline() ||
4323        New->getDescribedVarTemplate() ||
4324        New->getNumTemplateParameterLists() ||
4325        New->getDeclContext()->isDependentContext())) {
4326     // The previous definition is hidden, and multiple definitions are
4327     // permitted (in separate TUs). Demote this to a declaration.
4328     New->demoteThisDefinitionToDeclaration();
4329 
4330     // Make the canonical definition visible.
4331     if (auto *OldTD = Old->getDescribedVarTemplate())
4332       makeMergedDefinitionVisible(OldTD);
4333     makeMergedDefinitionVisible(Old);
4334     return false;
4335   } else {
4336     Diag(New->getLocation(), diag::err_redefinition) << New;
4337     notePreviousDefinition(Old, New->getLocation());
4338     New->setInvalidDecl();
4339     return true;
4340   }
4341 }
4342 
4343 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4344 /// no declarator (e.g. "struct foo;") is parsed.
4345 Decl *
4346 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4347                                  RecordDecl *&AnonRecord) {
4348   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4349                                     AnonRecord);
4350 }
4351 
4352 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4353 // disambiguate entities defined in different scopes.
4354 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4355 // compatibility.
4356 // We will pick our mangling number depending on which version of MSVC is being
4357 // targeted.
4358 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4359   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4360              ? S->getMSCurManglingNumber()
4361              : S->getMSLastManglingNumber();
4362 }
4363 
4364 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4365   if (!Context.getLangOpts().CPlusPlus)
4366     return;
4367 
4368   if (isa<CXXRecordDecl>(Tag->getParent())) {
4369     // If this tag is the direct child of a class, number it if
4370     // it is anonymous.
4371     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4372       return;
4373     MangleNumberingContext &MCtx =
4374         Context.getManglingNumberContext(Tag->getParent());
4375     Context.setManglingNumber(
4376         Tag, MCtx.getManglingNumber(
4377                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4378     return;
4379   }
4380 
4381   // If this tag isn't a direct child of a class, number it if it is local.
4382   MangleNumberingContext *MCtx;
4383   Decl *ManglingContextDecl;
4384   std::tie(MCtx, ManglingContextDecl) =
4385       getCurrentMangleNumberContext(Tag->getDeclContext());
4386   if (MCtx) {
4387     Context.setManglingNumber(
4388         Tag, MCtx->getManglingNumber(
4389                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4390   }
4391 }
4392 
4393 namespace {
4394 struct NonCLikeKind {
4395   enum {
4396     None,
4397     BaseClass,
4398     DefaultMemberInit,
4399     Lambda,
4400     Friend,
4401     OtherMember,
4402     Invalid,
4403   } Kind = None;
4404   SourceRange Range;
4405 
4406   explicit operator bool() { return Kind != None; }
4407 };
4408 }
4409 
4410 /// Determine whether a class is C-like, according to the rules of C++
4411 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4412 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4413   if (RD->isInvalidDecl())
4414     return {NonCLikeKind::Invalid, {}};
4415 
4416   // C++ [dcl.typedef]p9: [P1766R1]
4417   //   An unnamed class with a typedef name for linkage purposes shall not
4418   //
4419   //    -- have any base classes
4420   if (RD->getNumBases())
4421     return {NonCLikeKind::BaseClass,
4422             SourceRange(RD->bases_begin()->getBeginLoc(),
4423                         RD->bases_end()[-1].getEndLoc())};
4424   bool Invalid = false;
4425   for (Decl *D : RD->decls()) {
4426     // Don't complain about things we already diagnosed.
4427     if (D->isInvalidDecl()) {
4428       Invalid = true;
4429       continue;
4430     }
4431 
4432     //  -- have any [...] default member initializers
4433     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4434       if (FD->hasInClassInitializer()) {
4435         auto *Init = FD->getInClassInitializer();
4436         return {NonCLikeKind::DefaultMemberInit,
4437                 Init ? Init->getSourceRange() : D->getSourceRange()};
4438       }
4439       continue;
4440     }
4441 
4442     // FIXME: We don't allow friend declarations. This violates the wording of
4443     // P1766, but not the intent.
4444     if (isa<FriendDecl>(D))
4445       return {NonCLikeKind::Friend, D->getSourceRange()};
4446 
4447     //  -- declare any members other than non-static data members, member
4448     //     enumerations, or member classes,
4449     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4450         isa<EnumDecl>(D))
4451       continue;
4452     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4453     if (!MemberRD) {
4454       if (D->isImplicit())
4455         continue;
4456       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4457     }
4458 
4459     //  -- contain a lambda-expression,
4460     if (MemberRD->isLambda())
4461       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4462 
4463     //  and all member classes shall also satisfy these requirements
4464     //  (recursively).
4465     if (MemberRD->isThisDeclarationADefinition()) {
4466       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4467         return Kind;
4468     }
4469   }
4470 
4471   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4472 }
4473 
4474 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4475                                         TypedefNameDecl *NewTD) {
4476   if (TagFromDeclSpec->isInvalidDecl())
4477     return;
4478 
4479   // Do nothing if the tag already has a name for linkage purposes.
4480   if (TagFromDeclSpec->hasNameForLinkage())
4481     return;
4482 
4483   // A well-formed anonymous tag must always be a TUK_Definition.
4484   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4485 
4486   // The type must match the tag exactly;  no qualifiers allowed.
4487   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4488                            Context.getTagDeclType(TagFromDeclSpec))) {
4489     if (getLangOpts().CPlusPlus)
4490       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4491     return;
4492   }
4493 
4494   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4495   //   An unnamed class with a typedef name for linkage purposes shall [be
4496   //   C-like].
4497   //
4498   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4499   // shouldn't happen, but there are constructs that the language rule doesn't
4500   // disallow for which we can't reasonably avoid computing linkage early.
4501   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4502   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4503                              : NonCLikeKind();
4504   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4505   if (NonCLike || ChangesLinkage) {
4506     if (NonCLike.Kind == NonCLikeKind::Invalid)
4507       return;
4508 
4509     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4510     if (ChangesLinkage) {
4511       // If the linkage changes, we can't accept this as an extension.
4512       if (NonCLike.Kind == NonCLikeKind::None)
4513         DiagID = diag::err_typedef_changes_linkage;
4514       else
4515         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4516     }
4517 
4518     SourceLocation FixitLoc =
4519         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4520     llvm::SmallString<40> TextToInsert;
4521     TextToInsert += ' ';
4522     TextToInsert += NewTD->getIdentifier()->getName();
4523 
4524     Diag(FixitLoc, DiagID)
4525       << isa<TypeAliasDecl>(NewTD)
4526       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4527     if (NonCLike.Kind != NonCLikeKind::None) {
4528       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4529         << NonCLike.Kind - 1 << NonCLike.Range;
4530     }
4531     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4532       << NewTD << isa<TypeAliasDecl>(NewTD);
4533 
4534     if (ChangesLinkage)
4535       return;
4536   }
4537 
4538   // Otherwise, set this as the anon-decl typedef for the tag.
4539   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4540 }
4541 
4542 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4543   switch (T) {
4544   case DeclSpec::TST_class:
4545     return 0;
4546   case DeclSpec::TST_struct:
4547     return 1;
4548   case DeclSpec::TST_interface:
4549     return 2;
4550   case DeclSpec::TST_union:
4551     return 3;
4552   case DeclSpec::TST_enum:
4553     return 4;
4554   default:
4555     llvm_unreachable("unexpected type specifier");
4556   }
4557 }
4558 
4559 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4560 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4561 /// parameters to cope with template friend declarations.
4562 Decl *
4563 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4564                                  MultiTemplateParamsArg TemplateParams,
4565                                  bool IsExplicitInstantiation,
4566                                  RecordDecl *&AnonRecord) {
4567   Decl *TagD = nullptr;
4568   TagDecl *Tag = nullptr;
4569   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4570       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4571       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4572       DS.getTypeSpecType() == DeclSpec::TST_union ||
4573       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4574     TagD = DS.getRepAsDecl();
4575 
4576     if (!TagD) // We probably had an error
4577       return nullptr;
4578 
4579     // Note that the above type specs guarantee that the
4580     // type rep is a Decl, whereas in many of the others
4581     // it's a Type.
4582     if (isa<TagDecl>(TagD))
4583       Tag = cast<TagDecl>(TagD);
4584     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4585       Tag = CTD->getTemplatedDecl();
4586   }
4587 
4588   if (Tag) {
4589     handleTagNumbering(Tag, S);
4590     Tag->setFreeStanding();
4591     if (Tag->isInvalidDecl())
4592       return Tag;
4593   }
4594 
4595   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4596     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4597     // or incomplete types shall not be restrict-qualified."
4598     if (TypeQuals & DeclSpec::TQ_restrict)
4599       Diag(DS.getRestrictSpecLoc(),
4600            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4601            << DS.getSourceRange();
4602   }
4603 
4604   if (DS.isInlineSpecified())
4605     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4606         << getLangOpts().CPlusPlus17;
4607 
4608   if (DS.hasConstexprSpecifier()) {
4609     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4610     // and definitions of functions and variables.
4611     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4612     // the declaration of a function or function template
4613     if (Tag)
4614       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4615           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4616           << static_cast<int>(DS.getConstexprSpecifier());
4617     else
4618       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4619           << static_cast<int>(DS.getConstexprSpecifier());
4620     // Don't emit warnings after this error.
4621     return TagD;
4622   }
4623 
4624   DiagnoseFunctionSpecifiers(DS);
4625 
4626   if (DS.isFriendSpecified()) {
4627     // If we're dealing with a decl but not a TagDecl, assume that
4628     // whatever routines created it handled the friendship aspect.
4629     if (TagD && !Tag)
4630       return nullptr;
4631     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4632   }
4633 
4634   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4635   bool IsExplicitSpecialization =
4636     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4637   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4638       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4639       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4640     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4641     // nested-name-specifier unless it is an explicit instantiation
4642     // or an explicit specialization.
4643     //
4644     // FIXME: We allow class template partial specializations here too, per the
4645     // obvious intent of DR1819.
4646     //
4647     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4648     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4649         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4650     return nullptr;
4651   }
4652 
4653   // Track whether this decl-specifier declares anything.
4654   bool DeclaresAnything = true;
4655 
4656   // Handle anonymous struct definitions.
4657   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4658     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4659         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4660       if (getLangOpts().CPlusPlus ||
4661           Record->getDeclContext()->isRecord()) {
4662         // If CurContext is a DeclContext that can contain statements,
4663         // RecursiveASTVisitor won't visit the decls that
4664         // BuildAnonymousStructOrUnion() will put into CurContext.
4665         // Also store them here so that they can be part of the
4666         // DeclStmt that gets created in this case.
4667         // FIXME: Also return the IndirectFieldDecls created by
4668         // BuildAnonymousStructOr union, for the same reason?
4669         if (CurContext->isFunctionOrMethod())
4670           AnonRecord = Record;
4671         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4672                                            Context.getPrintingPolicy());
4673       }
4674 
4675       DeclaresAnything = false;
4676     }
4677   }
4678 
4679   // C11 6.7.2.1p2:
4680   //   A struct-declaration that does not declare an anonymous structure or
4681   //   anonymous union shall contain a struct-declarator-list.
4682   //
4683   // This rule also existed in C89 and C99; the grammar for struct-declaration
4684   // did not permit a struct-declaration without a struct-declarator-list.
4685   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4686       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4687     // Check for Microsoft C extension: anonymous struct/union member.
4688     // Handle 2 kinds of anonymous struct/union:
4689     //   struct STRUCT;
4690     //   union UNION;
4691     // and
4692     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4693     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4694     if ((Tag && Tag->getDeclName()) ||
4695         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4696       RecordDecl *Record = nullptr;
4697       if (Tag)
4698         Record = dyn_cast<RecordDecl>(Tag);
4699       else if (const RecordType *RT =
4700                    DS.getRepAsType().get()->getAsStructureType())
4701         Record = RT->getDecl();
4702       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4703         Record = UT->getDecl();
4704 
4705       if (Record && getLangOpts().MicrosoftExt) {
4706         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4707             << Record->isUnion() << DS.getSourceRange();
4708         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4709       }
4710 
4711       DeclaresAnything = false;
4712     }
4713   }
4714 
4715   // Skip all the checks below if we have a type error.
4716   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4717       (TagD && TagD->isInvalidDecl()))
4718     return TagD;
4719 
4720   if (getLangOpts().CPlusPlus &&
4721       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4722     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4723       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4724           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4725         DeclaresAnything = false;
4726 
4727   if (!DS.isMissingDeclaratorOk()) {
4728     // Customize diagnostic for a typedef missing a name.
4729     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4730       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4731           << DS.getSourceRange();
4732     else
4733       DeclaresAnything = false;
4734   }
4735 
4736   if (DS.isModulePrivateSpecified() &&
4737       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4738     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4739       << Tag->getTagKind()
4740       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4741 
4742   ActOnDocumentableDecl(TagD);
4743 
4744   // C 6.7/2:
4745   //   A declaration [...] shall declare at least a declarator [...], a tag,
4746   //   or the members of an enumeration.
4747   // C++ [dcl.dcl]p3:
4748   //   [If there are no declarators], and except for the declaration of an
4749   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4750   //   names into the program, or shall redeclare a name introduced by a
4751   //   previous declaration.
4752   if (!DeclaresAnything) {
4753     // In C, we allow this as a (popular) extension / bug. Don't bother
4754     // producing further diagnostics for redundant qualifiers after this.
4755     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4756                                ? diag::err_no_declarators
4757                                : diag::ext_no_declarators)
4758         << DS.getSourceRange();
4759     return TagD;
4760   }
4761 
4762   // C++ [dcl.stc]p1:
4763   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4764   //   init-declarator-list of the declaration shall not be empty.
4765   // C++ [dcl.fct.spec]p1:
4766   //   If a cv-qualifier appears in a decl-specifier-seq, the
4767   //   init-declarator-list of the declaration shall not be empty.
4768   //
4769   // Spurious qualifiers here appear to be valid in C.
4770   unsigned DiagID = diag::warn_standalone_specifier;
4771   if (getLangOpts().CPlusPlus)
4772     DiagID = diag::ext_standalone_specifier;
4773 
4774   // Note that a linkage-specification sets a storage class, but
4775   // 'extern "C" struct foo;' is actually valid and not theoretically
4776   // useless.
4777   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4778     if (SCS == DeclSpec::SCS_mutable)
4779       // Since mutable is not a viable storage class specifier in C, there is
4780       // no reason to treat it as an extension. Instead, diagnose as an error.
4781       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4782     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4783       Diag(DS.getStorageClassSpecLoc(), DiagID)
4784         << DeclSpec::getSpecifierName(SCS);
4785   }
4786 
4787   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4788     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4789       << DeclSpec::getSpecifierName(TSCS);
4790   if (DS.getTypeQualifiers()) {
4791     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4792       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4793     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4794       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4795     // Restrict is covered above.
4796     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4797       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4798     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4799       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4800   }
4801 
4802   // Warn about ignored type attributes, for example:
4803   // __attribute__((aligned)) struct A;
4804   // Attributes should be placed after tag to apply to type declaration.
4805   if (!DS.getAttributes().empty()) {
4806     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4807     if (TypeSpecType == DeclSpec::TST_class ||
4808         TypeSpecType == DeclSpec::TST_struct ||
4809         TypeSpecType == DeclSpec::TST_interface ||
4810         TypeSpecType == DeclSpec::TST_union ||
4811         TypeSpecType == DeclSpec::TST_enum) {
4812       for (const ParsedAttr &AL : DS.getAttributes())
4813         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4814             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4815     }
4816   }
4817 
4818   return TagD;
4819 }
4820 
4821 /// We are trying to inject an anonymous member into the given scope;
4822 /// check if there's an existing declaration that can't be overloaded.
4823 ///
4824 /// \return true if this is a forbidden redeclaration
4825 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4826                                          Scope *S,
4827                                          DeclContext *Owner,
4828                                          DeclarationName Name,
4829                                          SourceLocation NameLoc,
4830                                          bool IsUnion) {
4831   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4832                  Sema::ForVisibleRedeclaration);
4833   if (!SemaRef.LookupName(R, S)) return false;
4834 
4835   // Pick a representative declaration.
4836   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4837   assert(PrevDecl && "Expected a non-null Decl");
4838 
4839   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4840     return false;
4841 
4842   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4843     << IsUnion << Name;
4844   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4845 
4846   return true;
4847 }
4848 
4849 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4850 /// anonymous struct or union AnonRecord into the owning context Owner
4851 /// and scope S. This routine will be invoked just after we realize
4852 /// that an unnamed union or struct is actually an anonymous union or
4853 /// struct, e.g.,
4854 ///
4855 /// @code
4856 /// union {
4857 ///   int i;
4858 ///   float f;
4859 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4860 ///    // f into the surrounding scope.x
4861 /// @endcode
4862 ///
4863 /// This routine is recursive, injecting the names of nested anonymous
4864 /// structs/unions into the owning context and scope as well.
4865 static bool
4866 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4867                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4868                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4869   bool Invalid = false;
4870 
4871   // Look every FieldDecl and IndirectFieldDecl with a name.
4872   for (auto *D : AnonRecord->decls()) {
4873     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4874         cast<NamedDecl>(D)->getDeclName()) {
4875       ValueDecl *VD = cast<ValueDecl>(D);
4876       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4877                                        VD->getLocation(),
4878                                        AnonRecord->isUnion())) {
4879         // C++ [class.union]p2:
4880         //   The names of the members of an anonymous union shall be
4881         //   distinct from the names of any other entity in the
4882         //   scope in which the anonymous union is declared.
4883         Invalid = true;
4884       } else {
4885         // C++ [class.union]p2:
4886         //   For the purpose of name lookup, after the anonymous union
4887         //   definition, the members of the anonymous union are
4888         //   considered to have been defined in the scope in which the
4889         //   anonymous union is declared.
4890         unsigned OldChainingSize = Chaining.size();
4891         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4892           Chaining.append(IF->chain_begin(), IF->chain_end());
4893         else
4894           Chaining.push_back(VD);
4895 
4896         assert(Chaining.size() >= 2);
4897         NamedDecl **NamedChain =
4898           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4899         for (unsigned i = 0; i < Chaining.size(); i++)
4900           NamedChain[i] = Chaining[i];
4901 
4902         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4903             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4904             VD->getType(), {NamedChain, Chaining.size()});
4905 
4906         for (const auto *Attr : VD->attrs())
4907           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4908 
4909         IndirectField->setAccess(AS);
4910         IndirectField->setImplicit();
4911         SemaRef.PushOnScopeChains(IndirectField, S);
4912 
4913         // That includes picking up the appropriate access specifier.
4914         if (AS != AS_none) IndirectField->setAccess(AS);
4915 
4916         Chaining.resize(OldChainingSize);
4917       }
4918     }
4919   }
4920 
4921   return Invalid;
4922 }
4923 
4924 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4925 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4926 /// illegal input values are mapped to SC_None.
4927 static StorageClass
4928 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4929   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4930   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4931          "Parser allowed 'typedef' as storage class VarDecl.");
4932   switch (StorageClassSpec) {
4933   case DeclSpec::SCS_unspecified:    return SC_None;
4934   case DeclSpec::SCS_extern:
4935     if (DS.isExternInLinkageSpec())
4936       return SC_None;
4937     return SC_Extern;
4938   case DeclSpec::SCS_static:         return SC_Static;
4939   case DeclSpec::SCS_auto:           return SC_Auto;
4940   case DeclSpec::SCS_register:       return SC_Register;
4941   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4942     // Illegal SCSs map to None: error reporting is up to the caller.
4943   case DeclSpec::SCS_mutable:        // Fall through.
4944   case DeclSpec::SCS_typedef:        return SC_None;
4945   }
4946   llvm_unreachable("unknown storage class specifier");
4947 }
4948 
4949 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4950   assert(Record->hasInClassInitializer());
4951 
4952   for (const auto *I : Record->decls()) {
4953     const auto *FD = dyn_cast<FieldDecl>(I);
4954     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4955       FD = IFD->getAnonField();
4956     if (FD && FD->hasInClassInitializer())
4957       return FD->getLocation();
4958   }
4959 
4960   llvm_unreachable("couldn't find in-class initializer");
4961 }
4962 
4963 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4964                                       SourceLocation DefaultInitLoc) {
4965   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4966     return;
4967 
4968   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4969   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4970 }
4971 
4972 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4973                                       CXXRecordDecl *AnonUnion) {
4974   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4975     return;
4976 
4977   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4978 }
4979 
4980 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4981 /// anonymous structure or union. Anonymous unions are a C++ feature
4982 /// (C++ [class.union]) and a C11 feature; anonymous structures
4983 /// are a C11 feature and GNU C++ extension.
4984 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4985                                         AccessSpecifier AS,
4986                                         RecordDecl *Record,
4987                                         const PrintingPolicy &Policy) {
4988   DeclContext *Owner = Record->getDeclContext();
4989 
4990   // Diagnose whether this anonymous struct/union is an extension.
4991   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4992     Diag(Record->getLocation(), diag::ext_anonymous_union);
4993   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4994     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4995   else if (!Record->isUnion() && !getLangOpts().C11)
4996     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4997 
4998   // C and C++ require different kinds of checks for anonymous
4999   // structs/unions.
5000   bool Invalid = false;
5001   if (getLangOpts().CPlusPlus) {
5002     const char *PrevSpec = nullptr;
5003     if (Record->isUnion()) {
5004       // C++ [class.union]p6:
5005       // C++17 [class.union.anon]p2:
5006       //   Anonymous unions declared in a named namespace or in the
5007       //   global namespace shall be declared static.
5008       unsigned DiagID;
5009       DeclContext *OwnerScope = Owner->getRedeclContext();
5010       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5011           (OwnerScope->isTranslationUnit() ||
5012            (OwnerScope->isNamespace() &&
5013             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5014         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5015           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5016 
5017         // Recover by adding 'static'.
5018         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5019                                PrevSpec, DiagID, Policy);
5020       }
5021       // C++ [class.union]p6:
5022       //   A storage class is not allowed in a declaration of an
5023       //   anonymous union in a class scope.
5024       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5025                isa<RecordDecl>(Owner)) {
5026         Diag(DS.getStorageClassSpecLoc(),
5027              diag::err_anonymous_union_with_storage_spec)
5028           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5029 
5030         // Recover by removing the storage specifier.
5031         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5032                                SourceLocation(),
5033                                PrevSpec, DiagID, Context.getPrintingPolicy());
5034       }
5035     }
5036 
5037     // Ignore const/volatile/restrict qualifiers.
5038     if (DS.getTypeQualifiers()) {
5039       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5040         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5041           << Record->isUnion() << "const"
5042           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5043       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5044         Diag(DS.getVolatileSpecLoc(),
5045              diag::ext_anonymous_struct_union_qualified)
5046           << Record->isUnion() << "volatile"
5047           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5048       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5049         Diag(DS.getRestrictSpecLoc(),
5050              diag::ext_anonymous_struct_union_qualified)
5051           << Record->isUnion() << "restrict"
5052           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5053       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5054         Diag(DS.getAtomicSpecLoc(),
5055              diag::ext_anonymous_struct_union_qualified)
5056           << Record->isUnion() << "_Atomic"
5057           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5058       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5059         Diag(DS.getUnalignedSpecLoc(),
5060              diag::ext_anonymous_struct_union_qualified)
5061           << Record->isUnion() << "__unaligned"
5062           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5063 
5064       DS.ClearTypeQualifiers();
5065     }
5066 
5067     // C++ [class.union]p2:
5068     //   The member-specification of an anonymous union shall only
5069     //   define non-static data members. [Note: nested types and
5070     //   functions cannot be declared within an anonymous union. ]
5071     for (auto *Mem : Record->decls()) {
5072       // Ignore invalid declarations; we already diagnosed them.
5073       if (Mem->isInvalidDecl())
5074         continue;
5075 
5076       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5077         // C++ [class.union]p3:
5078         //   An anonymous union shall not have private or protected
5079         //   members (clause 11).
5080         assert(FD->getAccess() != AS_none);
5081         if (FD->getAccess() != AS_public) {
5082           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5083             << Record->isUnion() << (FD->getAccess() == AS_protected);
5084           Invalid = true;
5085         }
5086 
5087         // C++ [class.union]p1
5088         //   An object of a class with a non-trivial constructor, a non-trivial
5089         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5090         //   assignment operator cannot be a member of a union, nor can an
5091         //   array of such objects.
5092         if (CheckNontrivialField(FD))
5093           Invalid = true;
5094       } else if (Mem->isImplicit()) {
5095         // Any implicit members are fine.
5096       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5097         // This is a type that showed up in an
5098         // elaborated-type-specifier inside the anonymous struct or
5099         // union, but which actually declares a type outside of the
5100         // anonymous struct or union. It's okay.
5101       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5102         if (!MemRecord->isAnonymousStructOrUnion() &&
5103             MemRecord->getDeclName()) {
5104           // Visual C++ allows type definition in anonymous struct or union.
5105           if (getLangOpts().MicrosoftExt)
5106             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5107               << Record->isUnion();
5108           else {
5109             // This is a nested type declaration.
5110             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5111               << Record->isUnion();
5112             Invalid = true;
5113           }
5114         } else {
5115           // This is an anonymous type definition within another anonymous type.
5116           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5117           // not part of standard C++.
5118           Diag(MemRecord->getLocation(),
5119                diag::ext_anonymous_record_with_anonymous_type)
5120             << Record->isUnion();
5121         }
5122       } else if (isa<AccessSpecDecl>(Mem)) {
5123         // Any access specifier is fine.
5124       } else if (isa<StaticAssertDecl>(Mem)) {
5125         // In C++1z, static_assert declarations are also fine.
5126       } else {
5127         // We have something that isn't a non-static data
5128         // member. Complain about it.
5129         unsigned DK = diag::err_anonymous_record_bad_member;
5130         if (isa<TypeDecl>(Mem))
5131           DK = diag::err_anonymous_record_with_type;
5132         else if (isa<FunctionDecl>(Mem))
5133           DK = diag::err_anonymous_record_with_function;
5134         else if (isa<VarDecl>(Mem))
5135           DK = diag::err_anonymous_record_with_static;
5136 
5137         // Visual C++ allows type definition in anonymous struct or union.
5138         if (getLangOpts().MicrosoftExt &&
5139             DK == diag::err_anonymous_record_with_type)
5140           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5141             << Record->isUnion();
5142         else {
5143           Diag(Mem->getLocation(), DK) << Record->isUnion();
5144           Invalid = true;
5145         }
5146       }
5147     }
5148 
5149     // C++11 [class.union]p8 (DR1460):
5150     //   At most one variant member of a union may have a
5151     //   brace-or-equal-initializer.
5152     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5153         Owner->isRecord())
5154       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5155                                 cast<CXXRecordDecl>(Record));
5156   }
5157 
5158   if (!Record->isUnion() && !Owner->isRecord()) {
5159     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5160       << getLangOpts().CPlusPlus;
5161     Invalid = true;
5162   }
5163 
5164   // C++ [dcl.dcl]p3:
5165   //   [If there are no declarators], and except for the declaration of an
5166   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5167   //   names into the program
5168   // C++ [class.mem]p2:
5169   //   each such member-declaration shall either declare at least one member
5170   //   name of the class or declare at least one unnamed bit-field
5171   //
5172   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5173   if (getLangOpts().CPlusPlus && Record->field_empty())
5174     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5175 
5176   // Mock up a declarator.
5177   Declarator Dc(DS, DeclaratorContext::Member);
5178   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5179   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5180 
5181   // Create a declaration for this anonymous struct/union.
5182   NamedDecl *Anon = nullptr;
5183   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5184     Anon = FieldDecl::Create(
5185         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5186         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5187         /*BitWidth=*/nullptr, /*Mutable=*/false,
5188         /*InitStyle=*/ICIS_NoInit);
5189     Anon->setAccess(AS);
5190     ProcessDeclAttributes(S, Anon, Dc);
5191 
5192     if (getLangOpts().CPlusPlus)
5193       FieldCollector->Add(cast<FieldDecl>(Anon));
5194   } else {
5195     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5196     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5197     if (SCSpec == DeclSpec::SCS_mutable) {
5198       // mutable can only appear on non-static class members, so it's always
5199       // an error here
5200       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5201       Invalid = true;
5202       SC = SC_None;
5203     }
5204 
5205     assert(DS.getAttributes().empty() && "No attribute expected");
5206     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5207                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5208                            Context.getTypeDeclType(Record), TInfo, SC);
5209 
5210     // Default-initialize the implicit variable. This initialization will be
5211     // trivial in almost all cases, except if a union member has an in-class
5212     // initializer:
5213     //   union { int n = 0; };
5214     ActOnUninitializedDecl(Anon);
5215   }
5216   Anon->setImplicit();
5217 
5218   // Mark this as an anonymous struct/union type.
5219   Record->setAnonymousStructOrUnion(true);
5220 
5221   // Add the anonymous struct/union object to the current
5222   // context. We'll be referencing this object when we refer to one of
5223   // its members.
5224   Owner->addDecl(Anon);
5225 
5226   // Inject the members of the anonymous struct/union into the owning
5227   // context and into the identifier resolver chain for name lookup
5228   // purposes.
5229   SmallVector<NamedDecl*, 2> Chain;
5230   Chain.push_back(Anon);
5231 
5232   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5233     Invalid = true;
5234 
5235   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5236     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5237       MangleNumberingContext *MCtx;
5238       Decl *ManglingContextDecl;
5239       std::tie(MCtx, ManglingContextDecl) =
5240           getCurrentMangleNumberContext(NewVD->getDeclContext());
5241       if (MCtx) {
5242         Context.setManglingNumber(
5243             NewVD, MCtx->getManglingNumber(
5244                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5245         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5246       }
5247     }
5248   }
5249 
5250   if (Invalid)
5251     Anon->setInvalidDecl();
5252 
5253   return Anon;
5254 }
5255 
5256 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5257 /// Microsoft C anonymous structure.
5258 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5259 /// Example:
5260 ///
5261 /// struct A { int a; };
5262 /// struct B { struct A; int b; };
5263 ///
5264 /// void foo() {
5265 ///   B var;
5266 ///   var.a = 3;
5267 /// }
5268 ///
5269 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5270                                            RecordDecl *Record) {
5271   assert(Record && "expected a record!");
5272 
5273   // Mock up a declarator.
5274   Declarator Dc(DS, DeclaratorContext::TypeName);
5275   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5276   assert(TInfo && "couldn't build declarator info for anonymous struct");
5277 
5278   auto *ParentDecl = cast<RecordDecl>(CurContext);
5279   QualType RecTy = Context.getTypeDeclType(Record);
5280 
5281   // Create a declaration for this anonymous struct.
5282   NamedDecl *Anon =
5283       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5284                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5285                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5286                         /*InitStyle=*/ICIS_NoInit);
5287   Anon->setImplicit();
5288 
5289   // Add the anonymous struct object to the current context.
5290   CurContext->addDecl(Anon);
5291 
5292   // Inject the members of the anonymous struct into the current
5293   // context and into the identifier resolver chain for name lookup
5294   // purposes.
5295   SmallVector<NamedDecl*, 2> Chain;
5296   Chain.push_back(Anon);
5297 
5298   RecordDecl *RecordDef = Record->getDefinition();
5299   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5300                                diag::err_field_incomplete_or_sizeless) ||
5301       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5302                                           AS_none, Chain)) {
5303     Anon->setInvalidDecl();
5304     ParentDecl->setInvalidDecl();
5305   }
5306 
5307   return Anon;
5308 }
5309 
5310 /// GetNameForDeclarator - Determine the full declaration name for the
5311 /// given Declarator.
5312 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5313   return GetNameFromUnqualifiedId(D.getName());
5314 }
5315 
5316 /// Retrieves the declaration name from a parsed unqualified-id.
5317 DeclarationNameInfo
5318 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5319   DeclarationNameInfo NameInfo;
5320   NameInfo.setLoc(Name.StartLocation);
5321 
5322   switch (Name.getKind()) {
5323 
5324   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5325   case UnqualifiedIdKind::IK_Identifier:
5326     NameInfo.setName(Name.Identifier);
5327     return NameInfo;
5328 
5329   case UnqualifiedIdKind::IK_DeductionGuideName: {
5330     // C++ [temp.deduct.guide]p3:
5331     //   The simple-template-id shall name a class template specialization.
5332     //   The template-name shall be the same identifier as the template-name
5333     //   of the simple-template-id.
5334     // These together intend to imply that the template-name shall name a
5335     // class template.
5336     // FIXME: template<typename T> struct X {};
5337     //        template<typename T> using Y = X<T>;
5338     //        Y(int) -> Y<int>;
5339     //   satisfies these rules but does not name a class template.
5340     TemplateName TN = Name.TemplateName.get().get();
5341     auto *Template = TN.getAsTemplateDecl();
5342     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5343       Diag(Name.StartLocation,
5344            diag::err_deduction_guide_name_not_class_template)
5345         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5346       if (Template)
5347         Diag(Template->getLocation(), diag::note_template_decl_here);
5348       return DeclarationNameInfo();
5349     }
5350 
5351     NameInfo.setName(
5352         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5353     return NameInfo;
5354   }
5355 
5356   case UnqualifiedIdKind::IK_OperatorFunctionId:
5357     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5358                                            Name.OperatorFunctionId.Operator));
5359     NameInfo.setCXXOperatorNameRange(SourceRange(
5360         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5361     return NameInfo;
5362 
5363   case UnqualifiedIdKind::IK_LiteralOperatorId:
5364     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5365                                                            Name.Identifier));
5366     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5367     return NameInfo;
5368 
5369   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5370     TypeSourceInfo *TInfo;
5371     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5372     if (Ty.isNull())
5373       return DeclarationNameInfo();
5374     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5375                                                Context.getCanonicalType(Ty)));
5376     NameInfo.setNamedTypeInfo(TInfo);
5377     return NameInfo;
5378   }
5379 
5380   case UnqualifiedIdKind::IK_ConstructorName: {
5381     TypeSourceInfo *TInfo;
5382     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5383     if (Ty.isNull())
5384       return DeclarationNameInfo();
5385     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5386                                               Context.getCanonicalType(Ty)));
5387     NameInfo.setNamedTypeInfo(TInfo);
5388     return NameInfo;
5389   }
5390 
5391   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5392     // In well-formed code, we can only have a constructor
5393     // template-id that refers to the current context, so go there
5394     // to find the actual type being constructed.
5395     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5396     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5397       return DeclarationNameInfo();
5398 
5399     // Determine the type of the class being constructed.
5400     QualType CurClassType = Context.getTypeDeclType(CurClass);
5401 
5402     // FIXME: Check two things: that the template-id names the same type as
5403     // CurClassType, and that the template-id does not occur when the name
5404     // was qualified.
5405 
5406     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5407                                     Context.getCanonicalType(CurClassType)));
5408     // FIXME: should we retrieve TypeSourceInfo?
5409     NameInfo.setNamedTypeInfo(nullptr);
5410     return NameInfo;
5411   }
5412 
5413   case UnqualifiedIdKind::IK_DestructorName: {
5414     TypeSourceInfo *TInfo;
5415     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5416     if (Ty.isNull())
5417       return DeclarationNameInfo();
5418     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5419                                               Context.getCanonicalType(Ty)));
5420     NameInfo.setNamedTypeInfo(TInfo);
5421     return NameInfo;
5422   }
5423 
5424   case UnqualifiedIdKind::IK_TemplateId: {
5425     TemplateName TName = Name.TemplateId->Template.get();
5426     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5427     return Context.getNameForTemplate(TName, TNameLoc);
5428   }
5429 
5430   } // switch (Name.getKind())
5431 
5432   llvm_unreachable("Unknown name kind");
5433 }
5434 
5435 static QualType getCoreType(QualType Ty) {
5436   do {
5437     if (Ty->isPointerType() || Ty->isReferenceType())
5438       Ty = Ty->getPointeeType();
5439     else if (Ty->isArrayType())
5440       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5441     else
5442       return Ty.withoutLocalFastQualifiers();
5443   } while (true);
5444 }
5445 
5446 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5447 /// and Definition have "nearly" matching parameters. This heuristic is
5448 /// used to improve diagnostics in the case where an out-of-line function
5449 /// definition doesn't match any declaration within the class or namespace.
5450 /// Also sets Params to the list of indices to the parameters that differ
5451 /// between the declaration and the definition. If hasSimilarParameters
5452 /// returns true and Params is empty, then all of the parameters match.
5453 static bool hasSimilarParameters(ASTContext &Context,
5454                                      FunctionDecl *Declaration,
5455                                      FunctionDecl *Definition,
5456                                      SmallVectorImpl<unsigned> &Params) {
5457   Params.clear();
5458   if (Declaration->param_size() != Definition->param_size())
5459     return false;
5460   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5461     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5462     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5463 
5464     // The parameter types are identical
5465     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5466       continue;
5467 
5468     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5469     QualType DefParamBaseTy = getCoreType(DefParamTy);
5470     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5471     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5472 
5473     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5474         (DeclTyName && DeclTyName == DefTyName))
5475       Params.push_back(Idx);
5476     else  // The two parameters aren't even close
5477       return false;
5478   }
5479 
5480   return true;
5481 }
5482 
5483 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5484 /// declarator needs to be rebuilt in the current instantiation.
5485 /// Any bits of declarator which appear before the name are valid for
5486 /// consideration here.  That's specifically the type in the decl spec
5487 /// and the base type in any member-pointer chunks.
5488 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5489                                                     DeclarationName Name) {
5490   // The types we specifically need to rebuild are:
5491   //   - typenames, typeofs, and decltypes
5492   //   - types which will become injected class names
5493   // Of course, we also need to rebuild any type referencing such a
5494   // type.  It's safest to just say "dependent", but we call out a
5495   // few cases here.
5496 
5497   DeclSpec &DS = D.getMutableDeclSpec();
5498   switch (DS.getTypeSpecType()) {
5499   case DeclSpec::TST_typename:
5500   case DeclSpec::TST_typeofType:
5501   case DeclSpec::TST_underlyingType:
5502   case DeclSpec::TST_atomic: {
5503     // Grab the type from the parser.
5504     TypeSourceInfo *TSI = nullptr;
5505     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5506     if (T.isNull() || !T->isInstantiationDependentType()) break;
5507 
5508     // Make sure there's a type source info.  This isn't really much
5509     // of a waste; most dependent types should have type source info
5510     // attached already.
5511     if (!TSI)
5512       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5513 
5514     // Rebuild the type in the current instantiation.
5515     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5516     if (!TSI) return true;
5517 
5518     // Store the new type back in the decl spec.
5519     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5520     DS.UpdateTypeRep(LocType);
5521     break;
5522   }
5523 
5524   case DeclSpec::TST_decltype:
5525   case DeclSpec::TST_typeofExpr: {
5526     Expr *E = DS.getRepAsExpr();
5527     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5528     if (Result.isInvalid()) return true;
5529     DS.UpdateExprRep(Result.get());
5530     break;
5531   }
5532 
5533   default:
5534     // Nothing to do for these decl specs.
5535     break;
5536   }
5537 
5538   // It doesn't matter what order we do this in.
5539   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5540     DeclaratorChunk &Chunk = D.getTypeObject(I);
5541 
5542     // The only type information in the declarator which can come
5543     // before the declaration name is the base type of a member
5544     // pointer.
5545     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5546       continue;
5547 
5548     // Rebuild the scope specifier in-place.
5549     CXXScopeSpec &SS = Chunk.Mem.Scope();
5550     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5551       return true;
5552   }
5553 
5554   return false;
5555 }
5556 
5557 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5558   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5559   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5560 
5561   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5562       Dcl && Dcl->getDeclContext()->isFileContext())
5563     Dcl->setTopLevelDeclInObjCContainer();
5564 
5565   if (getLangOpts().OpenCL)
5566     setCurrentOpenCLExtensionForDecl(Dcl);
5567 
5568   return Dcl;
5569 }
5570 
5571 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5572 ///   If T is the name of a class, then each of the following shall have a
5573 ///   name different from T:
5574 ///     - every static data member of class T;
5575 ///     - every member function of class T
5576 ///     - every member of class T that is itself a type;
5577 /// \returns true if the declaration name violates these rules.
5578 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5579                                    DeclarationNameInfo NameInfo) {
5580   DeclarationName Name = NameInfo.getName();
5581 
5582   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5583   while (Record && Record->isAnonymousStructOrUnion())
5584     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5585   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5586     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5587     return true;
5588   }
5589 
5590   return false;
5591 }
5592 
5593 /// Diagnose a declaration whose declarator-id has the given
5594 /// nested-name-specifier.
5595 ///
5596 /// \param SS The nested-name-specifier of the declarator-id.
5597 ///
5598 /// \param DC The declaration context to which the nested-name-specifier
5599 /// resolves.
5600 ///
5601 /// \param Name The name of the entity being declared.
5602 ///
5603 /// \param Loc The location of the name of the entity being declared.
5604 ///
5605 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5606 /// we're declaring an explicit / partial specialization / instantiation.
5607 ///
5608 /// \returns true if we cannot safely recover from this error, false otherwise.
5609 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5610                                         DeclarationName Name,
5611                                         SourceLocation Loc, bool IsTemplateId) {
5612   DeclContext *Cur = CurContext;
5613   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5614     Cur = Cur->getParent();
5615 
5616   // If the user provided a superfluous scope specifier that refers back to the
5617   // class in which the entity is already declared, diagnose and ignore it.
5618   //
5619   // class X {
5620   //   void X::f();
5621   // };
5622   //
5623   // Note, it was once ill-formed to give redundant qualification in all
5624   // contexts, but that rule was removed by DR482.
5625   if (Cur->Equals(DC)) {
5626     if (Cur->isRecord()) {
5627       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5628                                       : diag::err_member_extra_qualification)
5629         << Name << FixItHint::CreateRemoval(SS.getRange());
5630       SS.clear();
5631     } else {
5632       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5633     }
5634     return false;
5635   }
5636 
5637   // Check whether the qualifying scope encloses the scope of the original
5638   // declaration. For a template-id, we perform the checks in
5639   // CheckTemplateSpecializationScope.
5640   if (!Cur->Encloses(DC) && !IsTemplateId) {
5641     if (Cur->isRecord())
5642       Diag(Loc, diag::err_member_qualification)
5643         << Name << SS.getRange();
5644     else if (isa<TranslationUnitDecl>(DC))
5645       Diag(Loc, diag::err_invalid_declarator_global_scope)
5646         << Name << SS.getRange();
5647     else if (isa<FunctionDecl>(Cur))
5648       Diag(Loc, diag::err_invalid_declarator_in_function)
5649         << Name << SS.getRange();
5650     else if (isa<BlockDecl>(Cur))
5651       Diag(Loc, diag::err_invalid_declarator_in_block)
5652         << Name << SS.getRange();
5653     else
5654       Diag(Loc, diag::err_invalid_declarator_scope)
5655       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5656 
5657     return true;
5658   }
5659 
5660   if (Cur->isRecord()) {
5661     // Cannot qualify members within a class.
5662     Diag(Loc, diag::err_member_qualification)
5663       << Name << SS.getRange();
5664     SS.clear();
5665 
5666     // C++ constructors and destructors with incorrect scopes can break
5667     // our AST invariants by having the wrong underlying types. If
5668     // that's the case, then drop this declaration entirely.
5669     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5670          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5671         !Context.hasSameType(Name.getCXXNameType(),
5672                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5673       return true;
5674 
5675     return false;
5676   }
5677 
5678   // C++11 [dcl.meaning]p1:
5679   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5680   //   not begin with a decltype-specifer"
5681   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5682   while (SpecLoc.getPrefix())
5683     SpecLoc = SpecLoc.getPrefix();
5684   if (dyn_cast_or_null<DecltypeType>(
5685         SpecLoc.getNestedNameSpecifier()->getAsType()))
5686     Diag(Loc, diag::err_decltype_in_declarator)
5687       << SpecLoc.getTypeLoc().getSourceRange();
5688 
5689   return false;
5690 }
5691 
5692 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5693                                   MultiTemplateParamsArg TemplateParamLists) {
5694   // TODO: consider using NameInfo for diagnostic.
5695   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5696   DeclarationName Name = NameInfo.getName();
5697 
5698   // All of these full declarators require an identifier.  If it doesn't have
5699   // one, the ParsedFreeStandingDeclSpec action should be used.
5700   if (D.isDecompositionDeclarator()) {
5701     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5702   } else if (!Name) {
5703     if (!D.isInvalidType())  // Reject this if we think it is valid.
5704       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5705           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5706     return nullptr;
5707   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5708     return nullptr;
5709 
5710   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5711   // we find one that is.
5712   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5713          (S->getFlags() & Scope::TemplateParamScope) != 0)
5714     S = S->getParent();
5715 
5716   DeclContext *DC = CurContext;
5717   if (D.getCXXScopeSpec().isInvalid())
5718     D.setInvalidType();
5719   else if (D.getCXXScopeSpec().isSet()) {
5720     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5721                                         UPPC_DeclarationQualifier))
5722       return nullptr;
5723 
5724     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5725     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5726     if (!DC || isa<EnumDecl>(DC)) {
5727       // If we could not compute the declaration context, it's because the
5728       // declaration context is dependent but does not refer to a class,
5729       // class template, or class template partial specialization. Complain
5730       // and return early, to avoid the coming semantic disaster.
5731       Diag(D.getIdentifierLoc(),
5732            diag::err_template_qualified_declarator_no_match)
5733         << D.getCXXScopeSpec().getScopeRep()
5734         << D.getCXXScopeSpec().getRange();
5735       return nullptr;
5736     }
5737     bool IsDependentContext = DC->isDependentContext();
5738 
5739     if (!IsDependentContext &&
5740         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5741       return nullptr;
5742 
5743     // If a class is incomplete, do not parse entities inside it.
5744     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5745       Diag(D.getIdentifierLoc(),
5746            diag::err_member_def_undefined_record)
5747         << Name << DC << D.getCXXScopeSpec().getRange();
5748       return nullptr;
5749     }
5750     if (!D.getDeclSpec().isFriendSpecified()) {
5751       if (diagnoseQualifiedDeclaration(
5752               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5753               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5754         if (DC->isRecord())
5755           return nullptr;
5756 
5757         D.setInvalidType();
5758       }
5759     }
5760 
5761     // Check whether we need to rebuild the type of the given
5762     // declaration in the current instantiation.
5763     if (EnteringContext && IsDependentContext &&
5764         TemplateParamLists.size() != 0) {
5765       ContextRAII SavedContext(*this, DC);
5766       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5767         D.setInvalidType();
5768     }
5769   }
5770 
5771   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5772   QualType R = TInfo->getType();
5773 
5774   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5775                                       UPPC_DeclarationType))
5776     D.setInvalidType();
5777 
5778   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5779                         forRedeclarationInCurContext());
5780 
5781   // See if this is a redefinition of a variable in the same scope.
5782   if (!D.getCXXScopeSpec().isSet()) {
5783     bool IsLinkageLookup = false;
5784     bool CreateBuiltins = false;
5785 
5786     // If the declaration we're planning to build will be a function
5787     // or object with linkage, then look for another declaration with
5788     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5789     //
5790     // If the declaration we're planning to build will be declared with
5791     // external linkage in the translation unit, create any builtin with
5792     // the same name.
5793     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5794       /* Do nothing*/;
5795     else if (CurContext->isFunctionOrMethod() &&
5796              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5797               R->isFunctionType())) {
5798       IsLinkageLookup = true;
5799       CreateBuiltins =
5800           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5801     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5802                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5803       CreateBuiltins = true;
5804 
5805     if (IsLinkageLookup) {
5806       Previous.clear(LookupRedeclarationWithLinkage);
5807       Previous.setRedeclarationKind(ForExternalRedeclaration);
5808     }
5809 
5810     LookupName(Previous, S, CreateBuiltins);
5811   } else { // Something like "int foo::x;"
5812     LookupQualifiedName(Previous, DC);
5813 
5814     // C++ [dcl.meaning]p1:
5815     //   When the declarator-id is qualified, the declaration shall refer to a
5816     //  previously declared member of the class or namespace to which the
5817     //  qualifier refers (or, in the case of a namespace, of an element of the
5818     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5819     //  thereof; [...]
5820     //
5821     // Note that we already checked the context above, and that we do not have
5822     // enough information to make sure that Previous contains the declaration
5823     // we want to match. For example, given:
5824     //
5825     //   class X {
5826     //     void f();
5827     //     void f(float);
5828     //   };
5829     //
5830     //   void X::f(int) { } // ill-formed
5831     //
5832     // In this case, Previous will point to the overload set
5833     // containing the two f's declared in X, but neither of them
5834     // matches.
5835 
5836     // C++ [dcl.meaning]p1:
5837     //   [...] the member shall not merely have been introduced by a
5838     //   using-declaration in the scope of the class or namespace nominated by
5839     //   the nested-name-specifier of the declarator-id.
5840     RemoveUsingDecls(Previous);
5841   }
5842 
5843   if (Previous.isSingleResult() &&
5844       Previous.getFoundDecl()->isTemplateParameter()) {
5845     // Maybe we will complain about the shadowed template parameter.
5846     if (!D.isInvalidType())
5847       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5848                                       Previous.getFoundDecl());
5849 
5850     // Just pretend that we didn't see the previous declaration.
5851     Previous.clear();
5852   }
5853 
5854   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5855     // Forget that the previous declaration is the injected-class-name.
5856     Previous.clear();
5857 
5858   // In C++, the previous declaration we find might be a tag type
5859   // (class or enum). In this case, the new declaration will hide the
5860   // tag type. Note that this applies to functions, function templates, and
5861   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5862   if (Previous.isSingleTagDecl() &&
5863       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5864       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5865     Previous.clear();
5866 
5867   // Check that there are no default arguments other than in the parameters
5868   // of a function declaration (C++ only).
5869   if (getLangOpts().CPlusPlus)
5870     CheckExtraCXXDefaultArguments(D);
5871 
5872   NamedDecl *New;
5873 
5874   bool AddToScope = true;
5875   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5876     if (TemplateParamLists.size()) {
5877       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5878       return nullptr;
5879     }
5880 
5881     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5882   } else if (R->isFunctionType()) {
5883     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5884                                   TemplateParamLists,
5885                                   AddToScope);
5886   } else {
5887     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5888                                   AddToScope);
5889   }
5890 
5891   if (!New)
5892     return nullptr;
5893 
5894   // If this has an identifier and is not a function template specialization,
5895   // add it to the scope stack.
5896   if (New->getDeclName() && AddToScope)
5897     PushOnScopeChains(New, S);
5898 
5899   if (isInOpenMPDeclareTargetContext())
5900     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5901 
5902   return New;
5903 }
5904 
5905 /// Helper method to turn variable array types into constant array
5906 /// types in certain situations which would otherwise be errors (for
5907 /// GCC compatibility).
5908 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5909                                                     ASTContext &Context,
5910                                                     bool &SizeIsNegative,
5911                                                     llvm::APSInt &Oversized) {
5912   // This method tries to turn a variable array into a constant
5913   // array even when the size isn't an ICE.  This is necessary
5914   // for compatibility with code that depends on gcc's buggy
5915   // constant expression folding, like struct {char x[(int)(char*)2];}
5916   SizeIsNegative = false;
5917   Oversized = 0;
5918 
5919   if (T->isDependentType())
5920     return QualType();
5921 
5922   QualifierCollector Qs;
5923   const Type *Ty = Qs.strip(T);
5924 
5925   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5926     QualType Pointee = PTy->getPointeeType();
5927     QualType FixedType =
5928         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5929                                             Oversized);
5930     if (FixedType.isNull()) return FixedType;
5931     FixedType = Context.getPointerType(FixedType);
5932     return Qs.apply(Context, FixedType);
5933   }
5934   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5935     QualType Inner = PTy->getInnerType();
5936     QualType FixedType =
5937         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5938                                             Oversized);
5939     if (FixedType.isNull()) return FixedType;
5940     FixedType = Context.getParenType(FixedType);
5941     return Qs.apply(Context, FixedType);
5942   }
5943 
5944   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5945   if (!VLATy)
5946     return QualType();
5947 
5948   QualType ElemTy = VLATy->getElementType();
5949   if (ElemTy->isVariablyModifiedType()) {
5950     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5951                                                  SizeIsNegative, Oversized);
5952     if (ElemTy.isNull())
5953       return QualType();
5954   }
5955 
5956   Expr::EvalResult Result;
5957   if (!VLATy->getSizeExpr() ||
5958       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5959     return QualType();
5960 
5961   llvm::APSInt Res = Result.Val.getInt();
5962 
5963   // Check whether the array size is negative.
5964   if (Res.isSigned() && Res.isNegative()) {
5965     SizeIsNegative = true;
5966     return QualType();
5967   }
5968 
5969   // Check whether the array is too large to be addressed.
5970   unsigned ActiveSizeBits =
5971       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5972        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5973           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5974           : Res.getActiveBits();
5975   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5976     Oversized = Res;
5977     return QualType();
5978   }
5979 
5980   QualType FoldedArrayType = Context.getConstantArrayType(
5981       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5982   return Qs.apply(Context, FoldedArrayType);
5983 }
5984 
5985 static void
5986 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5987   SrcTL = SrcTL.getUnqualifiedLoc();
5988   DstTL = DstTL.getUnqualifiedLoc();
5989   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5990     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5991     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5992                                       DstPTL.getPointeeLoc());
5993     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5994     return;
5995   }
5996   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5997     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5998     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5999                                       DstPTL.getInnerLoc());
6000     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6001     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6002     return;
6003   }
6004   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6005   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6006   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6007   TypeLoc DstElemTL = DstATL.getElementLoc();
6008   if (VariableArrayTypeLoc SrcElemATL =
6009           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6010     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6011     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6012   } else {
6013     DstElemTL.initializeFullCopy(SrcElemTL);
6014   }
6015   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6016   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6017   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6018 }
6019 
6020 /// Helper method to turn variable array types into constant array
6021 /// types in certain situations which would otherwise be errors (for
6022 /// GCC compatibility).
6023 static TypeSourceInfo*
6024 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6025                                               ASTContext &Context,
6026                                               bool &SizeIsNegative,
6027                                               llvm::APSInt &Oversized) {
6028   QualType FixedTy
6029     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6030                                           SizeIsNegative, Oversized);
6031   if (FixedTy.isNull())
6032     return nullptr;
6033   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6034   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6035                                     FixedTInfo->getTypeLoc());
6036   return FixedTInfo;
6037 }
6038 
6039 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6040 /// true if we were successful.
6041 static bool tryToFixVariablyModifiedVarType(Sema &S, TypeSourceInfo *&TInfo,
6042                                             QualType &T, SourceLocation Loc,
6043                                             unsigned FailedFoldDiagID) {
6044   bool SizeIsNegative;
6045   llvm::APSInt Oversized;
6046   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6047       TInfo, S.Context, SizeIsNegative, Oversized);
6048   if (FixedTInfo) {
6049     S.Diag(Loc, diag::ext_vla_folded_to_constant);
6050     TInfo = FixedTInfo;
6051     T = FixedTInfo->getType();
6052     return true;
6053   }
6054 
6055   if (SizeIsNegative)
6056     S.Diag(Loc, diag::err_typecheck_negative_array_size);
6057   else if (Oversized.getBoolValue())
6058     S.Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6059   else if (FailedFoldDiagID)
6060     S.Diag(Loc, FailedFoldDiagID);
6061   return false;
6062 }
6063 
6064 /// Register the given locally-scoped extern "C" declaration so
6065 /// that it can be found later for redeclarations. We include any extern "C"
6066 /// declaration that is not visible in the translation unit here, not just
6067 /// function-scope declarations.
6068 void
6069 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6070   if (!getLangOpts().CPlusPlus &&
6071       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6072     // Don't need to track declarations in the TU in C.
6073     return;
6074 
6075   // Note that we have a locally-scoped external with this name.
6076   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6077 }
6078 
6079 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6080   // FIXME: We can have multiple results via __attribute__((overloadable)).
6081   auto Result = Context.getExternCContextDecl()->lookup(Name);
6082   return Result.empty() ? nullptr : *Result.begin();
6083 }
6084 
6085 /// Diagnose function specifiers on a declaration of an identifier that
6086 /// does not identify a function.
6087 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6088   // FIXME: We should probably indicate the identifier in question to avoid
6089   // confusion for constructs like "virtual int a(), b;"
6090   if (DS.isVirtualSpecified())
6091     Diag(DS.getVirtualSpecLoc(),
6092          diag::err_virtual_non_function);
6093 
6094   if (DS.hasExplicitSpecifier())
6095     Diag(DS.getExplicitSpecLoc(),
6096          diag::err_explicit_non_function);
6097 
6098   if (DS.isNoreturnSpecified())
6099     Diag(DS.getNoreturnSpecLoc(),
6100          diag::err_noreturn_non_function);
6101 }
6102 
6103 NamedDecl*
6104 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6105                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6106   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6107   if (D.getCXXScopeSpec().isSet()) {
6108     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6109       << D.getCXXScopeSpec().getRange();
6110     D.setInvalidType();
6111     // Pretend we didn't see the scope specifier.
6112     DC = CurContext;
6113     Previous.clear();
6114   }
6115 
6116   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6117 
6118   if (D.getDeclSpec().isInlineSpecified())
6119     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6120         << getLangOpts().CPlusPlus17;
6121   if (D.getDeclSpec().hasConstexprSpecifier())
6122     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6123         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6124 
6125   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6126     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6127       Diag(D.getName().StartLocation,
6128            diag::err_deduction_guide_invalid_specifier)
6129           << "typedef";
6130     else
6131       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6132           << D.getName().getSourceRange();
6133     return nullptr;
6134   }
6135 
6136   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6137   if (!NewTD) return nullptr;
6138 
6139   // Handle attributes prior to checking for duplicates in MergeVarDecl
6140   ProcessDeclAttributes(S, NewTD, D);
6141 
6142   CheckTypedefForVariablyModifiedType(S, NewTD);
6143 
6144   bool Redeclaration = D.isRedeclaration();
6145   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6146   D.setRedeclaration(Redeclaration);
6147   return ND;
6148 }
6149 
6150 void
6151 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6152   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6153   // then it shall have block scope.
6154   // Note that variably modified types must be fixed before merging the decl so
6155   // that redeclarations will match.
6156   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6157   QualType T = TInfo->getType();
6158   if (T->isVariablyModifiedType()) {
6159     setFunctionHasBranchProtectedScope();
6160 
6161     if (S->getFnParent() == nullptr) {
6162       bool SizeIsNegative;
6163       llvm::APSInt Oversized;
6164       TypeSourceInfo *FixedTInfo =
6165         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6166                                                       SizeIsNegative,
6167                                                       Oversized);
6168       if (FixedTInfo) {
6169         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6170         NewTD->setTypeSourceInfo(FixedTInfo);
6171       } else {
6172         if (SizeIsNegative)
6173           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6174         else if (T->isVariableArrayType())
6175           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6176         else if (Oversized.getBoolValue())
6177           Diag(NewTD->getLocation(), diag::err_array_too_large)
6178             << Oversized.toString(10);
6179         else
6180           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6181         NewTD->setInvalidDecl();
6182       }
6183     }
6184   }
6185 }
6186 
6187 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6188 /// declares a typedef-name, either using the 'typedef' type specifier or via
6189 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6190 NamedDecl*
6191 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6192                            LookupResult &Previous, bool &Redeclaration) {
6193 
6194   // Find the shadowed declaration before filtering for scope.
6195   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6196 
6197   // Merge the decl with the existing one if appropriate. If the decl is
6198   // in an outer scope, it isn't the same thing.
6199   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6200                        /*AllowInlineNamespace*/false);
6201   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6202   if (!Previous.empty()) {
6203     Redeclaration = true;
6204     MergeTypedefNameDecl(S, NewTD, Previous);
6205   } else {
6206     inferGslPointerAttribute(NewTD);
6207   }
6208 
6209   if (ShadowedDecl && !Redeclaration)
6210     CheckShadow(NewTD, ShadowedDecl, Previous);
6211 
6212   // If this is the C FILE type, notify the AST context.
6213   if (IdentifierInfo *II = NewTD->getIdentifier())
6214     if (!NewTD->isInvalidDecl() &&
6215         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6216       if (II->isStr("FILE"))
6217         Context.setFILEDecl(NewTD);
6218       else if (II->isStr("jmp_buf"))
6219         Context.setjmp_bufDecl(NewTD);
6220       else if (II->isStr("sigjmp_buf"))
6221         Context.setsigjmp_bufDecl(NewTD);
6222       else if (II->isStr("ucontext_t"))
6223         Context.setucontext_tDecl(NewTD);
6224     }
6225 
6226   return NewTD;
6227 }
6228 
6229 /// Determines whether the given declaration is an out-of-scope
6230 /// previous declaration.
6231 ///
6232 /// This routine should be invoked when name lookup has found a
6233 /// previous declaration (PrevDecl) that is not in the scope where a
6234 /// new declaration by the same name is being introduced. If the new
6235 /// declaration occurs in a local scope, previous declarations with
6236 /// linkage may still be considered previous declarations (C99
6237 /// 6.2.2p4-5, C++ [basic.link]p6).
6238 ///
6239 /// \param PrevDecl the previous declaration found by name
6240 /// lookup
6241 ///
6242 /// \param DC the context in which the new declaration is being
6243 /// declared.
6244 ///
6245 /// \returns true if PrevDecl is an out-of-scope previous declaration
6246 /// for a new delcaration with the same name.
6247 static bool
6248 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6249                                 ASTContext &Context) {
6250   if (!PrevDecl)
6251     return false;
6252 
6253   if (!PrevDecl->hasLinkage())
6254     return false;
6255 
6256   if (Context.getLangOpts().CPlusPlus) {
6257     // C++ [basic.link]p6:
6258     //   If there is a visible declaration of an entity with linkage
6259     //   having the same name and type, ignoring entities declared
6260     //   outside the innermost enclosing namespace scope, the block
6261     //   scope declaration declares that same entity and receives the
6262     //   linkage of the previous declaration.
6263     DeclContext *OuterContext = DC->getRedeclContext();
6264     if (!OuterContext->isFunctionOrMethod())
6265       // This rule only applies to block-scope declarations.
6266       return false;
6267 
6268     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6269     if (PrevOuterContext->isRecord())
6270       // We found a member function: ignore it.
6271       return false;
6272 
6273     // Find the innermost enclosing namespace for the new and
6274     // previous declarations.
6275     OuterContext = OuterContext->getEnclosingNamespaceContext();
6276     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6277 
6278     // The previous declaration is in a different namespace, so it
6279     // isn't the same function.
6280     if (!OuterContext->Equals(PrevOuterContext))
6281       return false;
6282   }
6283 
6284   return true;
6285 }
6286 
6287 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6288   CXXScopeSpec &SS = D.getCXXScopeSpec();
6289   if (!SS.isSet()) return;
6290   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6291 }
6292 
6293 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6294   QualType type = decl->getType();
6295   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6296   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6297     // Various kinds of declaration aren't allowed to be __autoreleasing.
6298     unsigned kind = -1U;
6299     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6300       if (var->hasAttr<BlocksAttr>())
6301         kind = 0; // __block
6302       else if (!var->hasLocalStorage())
6303         kind = 1; // global
6304     } else if (isa<ObjCIvarDecl>(decl)) {
6305       kind = 3; // ivar
6306     } else if (isa<FieldDecl>(decl)) {
6307       kind = 2; // field
6308     }
6309 
6310     if (kind != -1U) {
6311       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6312         << kind;
6313     }
6314   } else if (lifetime == Qualifiers::OCL_None) {
6315     // Try to infer lifetime.
6316     if (!type->isObjCLifetimeType())
6317       return false;
6318 
6319     lifetime = type->getObjCARCImplicitLifetime();
6320     type = Context.getLifetimeQualifiedType(type, lifetime);
6321     decl->setType(type);
6322   }
6323 
6324   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6325     // Thread-local variables cannot have lifetime.
6326     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6327         var->getTLSKind()) {
6328       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6329         << var->getType();
6330       return true;
6331     }
6332   }
6333 
6334   return false;
6335 }
6336 
6337 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6338   if (Decl->getType().hasAddressSpace())
6339     return;
6340   if (Decl->getType()->isDependentType())
6341     return;
6342   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6343     QualType Type = Var->getType();
6344     if (Type->isSamplerT() || Type->isVoidType())
6345       return;
6346     LangAS ImplAS = LangAS::opencl_private;
6347     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6348         Var->hasGlobalStorage())
6349       ImplAS = LangAS::opencl_global;
6350     // If the original type from a decayed type is an array type and that array
6351     // type has no address space yet, deduce it now.
6352     if (auto DT = dyn_cast<DecayedType>(Type)) {
6353       auto OrigTy = DT->getOriginalType();
6354       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6355         // Add the address space to the original array type and then propagate
6356         // that to the element type through `getAsArrayType`.
6357         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6358         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6359         // Re-generate the decayed type.
6360         Type = Context.getDecayedType(OrigTy);
6361       }
6362     }
6363     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6364     // Apply any qualifiers (including address space) from the array type to
6365     // the element type. This implements C99 6.7.3p8: "If the specification of
6366     // an array type includes any type qualifiers, the element type is so
6367     // qualified, not the array type."
6368     if (Type->isArrayType())
6369       Type = QualType(Context.getAsArrayType(Type), 0);
6370     Decl->setType(Type);
6371   }
6372 }
6373 
6374 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6375   // Ensure that an auto decl is deduced otherwise the checks below might cache
6376   // the wrong linkage.
6377   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6378 
6379   // 'weak' only applies to declarations with external linkage.
6380   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6381     if (!ND.isExternallyVisible()) {
6382       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6383       ND.dropAttr<WeakAttr>();
6384     }
6385   }
6386   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6387     if (ND.isExternallyVisible()) {
6388       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6389       ND.dropAttr<WeakRefAttr>();
6390       ND.dropAttr<AliasAttr>();
6391     }
6392   }
6393 
6394   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6395     if (VD->hasInit()) {
6396       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6397         assert(VD->isThisDeclarationADefinition() &&
6398                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6399         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6400         VD->dropAttr<AliasAttr>();
6401       }
6402     }
6403   }
6404 
6405   // 'selectany' only applies to externally visible variable declarations.
6406   // It does not apply to functions.
6407   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6408     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6409       S.Diag(Attr->getLocation(),
6410              diag::err_attribute_selectany_non_extern_data);
6411       ND.dropAttr<SelectAnyAttr>();
6412     }
6413   }
6414 
6415   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6416     auto *VD = dyn_cast<VarDecl>(&ND);
6417     bool IsAnonymousNS = false;
6418     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6419     if (VD) {
6420       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6421       while (NS && !IsAnonymousNS) {
6422         IsAnonymousNS = NS->isAnonymousNamespace();
6423         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6424       }
6425     }
6426     // dll attributes require external linkage. Static locals may have external
6427     // linkage but still cannot be explicitly imported or exported.
6428     // In Microsoft mode, a variable defined in anonymous namespace must have
6429     // external linkage in order to be exported.
6430     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6431     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6432         (!AnonNSInMicrosoftMode &&
6433          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6434       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6435         << &ND << Attr;
6436       ND.setInvalidDecl();
6437     }
6438   }
6439 
6440   // Check the attributes on the function type, if any.
6441   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6442     // Don't declare this variable in the second operand of the for-statement;
6443     // GCC miscompiles that by ending its lifetime before evaluating the
6444     // third operand. See gcc.gnu.org/PR86769.
6445     AttributedTypeLoc ATL;
6446     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6447          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6448          TL = ATL.getModifiedLoc()) {
6449       // The [[lifetimebound]] attribute can be applied to the implicit object
6450       // parameter of a non-static member function (other than a ctor or dtor)
6451       // by applying it to the function type.
6452       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6453         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6454         if (!MD || MD->isStatic()) {
6455           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6456               << !MD << A->getRange();
6457         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6458           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6459               << isa<CXXDestructorDecl>(MD) << A->getRange();
6460         }
6461       }
6462     }
6463   }
6464 }
6465 
6466 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6467                                            NamedDecl *NewDecl,
6468                                            bool IsSpecialization,
6469                                            bool IsDefinition) {
6470   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6471     return;
6472 
6473   bool IsTemplate = false;
6474   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6475     OldDecl = OldTD->getTemplatedDecl();
6476     IsTemplate = true;
6477     if (!IsSpecialization)
6478       IsDefinition = false;
6479   }
6480   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6481     NewDecl = NewTD->getTemplatedDecl();
6482     IsTemplate = true;
6483   }
6484 
6485   if (!OldDecl || !NewDecl)
6486     return;
6487 
6488   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6489   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6490   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6491   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6492 
6493   // dllimport and dllexport are inheritable attributes so we have to exclude
6494   // inherited attribute instances.
6495   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6496                     (NewExportAttr && !NewExportAttr->isInherited());
6497 
6498   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6499   // the only exception being explicit specializations.
6500   // Implicitly generated declarations are also excluded for now because there
6501   // is no other way to switch these to use dllimport or dllexport.
6502   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6503 
6504   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6505     // Allow with a warning for free functions and global variables.
6506     bool JustWarn = false;
6507     if (!OldDecl->isCXXClassMember()) {
6508       auto *VD = dyn_cast<VarDecl>(OldDecl);
6509       if (VD && !VD->getDescribedVarTemplate())
6510         JustWarn = true;
6511       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6512       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6513         JustWarn = true;
6514     }
6515 
6516     // We cannot change a declaration that's been used because IR has already
6517     // been emitted. Dllimported functions will still work though (modulo
6518     // address equality) as they can use the thunk.
6519     if (OldDecl->isUsed())
6520       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6521         JustWarn = false;
6522 
6523     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6524                                : diag::err_attribute_dll_redeclaration;
6525     S.Diag(NewDecl->getLocation(), DiagID)
6526         << NewDecl
6527         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6528     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6529     if (!JustWarn) {
6530       NewDecl->setInvalidDecl();
6531       return;
6532     }
6533   }
6534 
6535   // A redeclaration is not allowed to drop a dllimport attribute, the only
6536   // exceptions being inline function definitions (except for function
6537   // templates), local extern declarations, qualified friend declarations or
6538   // special MSVC extension: in the last case, the declaration is treated as if
6539   // it were marked dllexport.
6540   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6541   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6542   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6543     // Ignore static data because out-of-line definitions are diagnosed
6544     // separately.
6545     IsStaticDataMember = VD->isStaticDataMember();
6546     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6547                    VarDecl::DeclarationOnly;
6548   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6549     IsInline = FD->isInlined();
6550     IsQualifiedFriend = FD->getQualifier() &&
6551                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6552   }
6553 
6554   if (OldImportAttr && !HasNewAttr &&
6555       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6556       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6557     if (IsMicrosoftABI && IsDefinition) {
6558       S.Diag(NewDecl->getLocation(),
6559              diag::warn_redeclaration_without_import_attribute)
6560           << NewDecl;
6561       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6562       NewDecl->dropAttr<DLLImportAttr>();
6563       NewDecl->addAttr(
6564           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6565     } else {
6566       S.Diag(NewDecl->getLocation(),
6567              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6568           << NewDecl << OldImportAttr;
6569       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6570       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6571       OldDecl->dropAttr<DLLImportAttr>();
6572       NewDecl->dropAttr<DLLImportAttr>();
6573     }
6574   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6575     // In MinGW, seeing a function declared inline drops the dllimport
6576     // attribute.
6577     OldDecl->dropAttr<DLLImportAttr>();
6578     NewDecl->dropAttr<DLLImportAttr>();
6579     S.Diag(NewDecl->getLocation(),
6580            diag::warn_dllimport_dropped_from_inline_function)
6581         << NewDecl << OldImportAttr;
6582   }
6583 
6584   // A specialization of a class template member function is processed here
6585   // since it's a redeclaration. If the parent class is dllexport, the
6586   // specialization inherits that attribute. This doesn't happen automatically
6587   // since the parent class isn't instantiated until later.
6588   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6589     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6590         !NewImportAttr && !NewExportAttr) {
6591       if (const DLLExportAttr *ParentExportAttr =
6592               MD->getParent()->getAttr<DLLExportAttr>()) {
6593         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6594         NewAttr->setInherited(true);
6595         NewDecl->addAttr(NewAttr);
6596       }
6597     }
6598   }
6599 }
6600 
6601 /// Given that we are within the definition of the given function,
6602 /// will that definition behave like C99's 'inline', where the
6603 /// definition is discarded except for optimization purposes?
6604 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6605   // Try to avoid calling GetGVALinkageForFunction.
6606 
6607   // All cases of this require the 'inline' keyword.
6608   if (!FD->isInlined()) return false;
6609 
6610   // This is only possible in C++ with the gnu_inline attribute.
6611   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6612     return false;
6613 
6614   // Okay, go ahead and call the relatively-more-expensive function.
6615   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6616 }
6617 
6618 /// Determine whether a variable is extern "C" prior to attaching
6619 /// an initializer. We can't just call isExternC() here, because that
6620 /// will also compute and cache whether the declaration is externally
6621 /// visible, which might change when we attach the initializer.
6622 ///
6623 /// This can only be used if the declaration is known to not be a
6624 /// redeclaration of an internal linkage declaration.
6625 ///
6626 /// For instance:
6627 ///
6628 ///   auto x = []{};
6629 ///
6630 /// Attaching the initializer here makes this declaration not externally
6631 /// visible, because its type has internal linkage.
6632 ///
6633 /// FIXME: This is a hack.
6634 template<typename T>
6635 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6636   if (S.getLangOpts().CPlusPlus) {
6637     // In C++, the overloadable attribute negates the effects of extern "C".
6638     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6639       return false;
6640 
6641     // So do CUDA's host/device attributes.
6642     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6643                                  D->template hasAttr<CUDAHostAttr>()))
6644       return false;
6645   }
6646   return D->isExternC();
6647 }
6648 
6649 static bool shouldConsiderLinkage(const VarDecl *VD) {
6650   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6651   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6652       isa<OMPDeclareMapperDecl>(DC))
6653     return VD->hasExternalStorage();
6654   if (DC->isFileContext())
6655     return true;
6656   if (DC->isRecord())
6657     return false;
6658   if (isa<RequiresExprBodyDecl>(DC))
6659     return false;
6660   llvm_unreachable("Unexpected context");
6661 }
6662 
6663 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6664   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6665   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6666       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6667     return true;
6668   if (DC->isRecord())
6669     return false;
6670   llvm_unreachable("Unexpected context");
6671 }
6672 
6673 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6674                           ParsedAttr::Kind Kind) {
6675   // Check decl attributes on the DeclSpec.
6676   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6677     return true;
6678 
6679   // Walk the declarator structure, checking decl attributes that were in a type
6680   // position to the decl itself.
6681   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6682     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6683       return true;
6684   }
6685 
6686   // Finally, check attributes on the decl itself.
6687   return PD.getAttributes().hasAttribute(Kind);
6688 }
6689 
6690 /// Adjust the \c DeclContext for a function or variable that might be a
6691 /// function-local external declaration.
6692 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6693   if (!DC->isFunctionOrMethod())
6694     return false;
6695 
6696   // If this is a local extern function or variable declared within a function
6697   // template, don't add it into the enclosing namespace scope until it is
6698   // instantiated; it might have a dependent type right now.
6699   if (DC->isDependentContext())
6700     return true;
6701 
6702   // C++11 [basic.link]p7:
6703   //   When a block scope declaration of an entity with linkage is not found to
6704   //   refer to some other declaration, then that entity is a member of the
6705   //   innermost enclosing namespace.
6706   //
6707   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6708   // semantically-enclosing namespace, not a lexically-enclosing one.
6709   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6710     DC = DC->getParent();
6711   return true;
6712 }
6713 
6714 /// Returns true if given declaration has external C language linkage.
6715 static bool isDeclExternC(const Decl *D) {
6716   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6717     return FD->isExternC();
6718   if (const auto *VD = dyn_cast<VarDecl>(D))
6719     return VD->isExternC();
6720 
6721   llvm_unreachable("Unknown type of decl!");
6722 }
6723 /// Returns true if there hasn't been any invalid type diagnosed.
6724 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6725                                 DeclContext *DC, QualType R) {
6726   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6727   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6728   // argument.
6729   if (R->isImageType() || R->isPipeType()) {
6730     Se.Diag(D.getIdentifierLoc(),
6731             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6732         << R;
6733     D.setInvalidType();
6734     return false;
6735   }
6736 
6737   // OpenCL v1.2 s6.9.r:
6738   // The event type cannot be used to declare a program scope variable.
6739   // OpenCL v2.0 s6.9.q:
6740   // The clk_event_t and reserve_id_t types cannot be declared in program
6741   // scope.
6742   if (NULL == S->getParent()) {
6743     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6744       Se.Diag(D.getIdentifierLoc(),
6745               diag::err_invalid_type_for_program_scope_var)
6746           << R;
6747       D.setInvalidType();
6748       return false;
6749     }
6750   }
6751 
6752   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6753   if (!Se.getOpenCLOptions().isEnabled("__cl_clang_function_pointers")) {
6754     QualType NR = R.getCanonicalType();
6755     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6756            NR->isReferenceType()) {
6757       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6758           NR->isFunctionReferenceType()) {
6759         Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer)
6760             << NR->isReferenceType();
6761         D.setInvalidType();
6762         return false;
6763       }
6764       NR = NR->getPointeeType();
6765     }
6766   }
6767 
6768   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6769     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6770     // half array type (unless the cl_khr_fp16 extension is enabled).
6771     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6772       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6773       D.setInvalidType();
6774       return false;
6775     }
6776   }
6777 
6778   // OpenCL v1.2 s6.9.r:
6779   // The event type cannot be used with the __local, __constant and __global
6780   // address space qualifiers.
6781   if (R->isEventT()) {
6782     if (R.getAddressSpace() != LangAS::opencl_private) {
6783       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6784       D.setInvalidType();
6785       return false;
6786     }
6787   }
6788 
6789   // C++ for OpenCL does not allow the thread_local storage qualifier.
6790   // OpenCL C does not support thread_local either, and
6791   // also reject all other thread storage class specifiers.
6792   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6793   if (TSC != TSCS_unspecified) {
6794     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6795     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6796             diag::err_opencl_unknown_type_specifier)
6797         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6798         << DeclSpec::getSpecifierName(TSC) << 1;
6799     D.setInvalidType();
6800     return false;
6801   }
6802 
6803   if (R->isSamplerT()) {
6804     // OpenCL v1.2 s6.9.b p4:
6805     // The sampler type cannot be used with the __local and __global address
6806     // space qualifiers.
6807     if (R.getAddressSpace() == LangAS::opencl_local ||
6808         R.getAddressSpace() == LangAS::opencl_global) {
6809       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6810       D.setInvalidType();
6811     }
6812 
6813     // OpenCL v1.2 s6.12.14.1:
6814     // A global sampler must be declared with either the constant address
6815     // space qualifier or with the const qualifier.
6816     if (DC->isTranslationUnit() &&
6817         !(R.getAddressSpace() == LangAS::opencl_constant ||
6818           R.isConstQualified())) {
6819       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6820       D.setInvalidType();
6821     }
6822     if (D.isInvalidType())
6823       return false;
6824   }
6825   return true;
6826 }
6827 
6828 NamedDecl *Sema::ActOnVariableDeclarator(
6829     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6830     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6831     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6832   QualType R = TInfo->getType();
6833   DeclarationName Name = GetNameForDeclarator(D).getName();
6834 
6835   IdentifierInfo *II = Name.getAsIdentifierInfo();
6836 
6837   if (D.isDecompositionDeclarator()) {
6838     // Take the name of the first declarator as our name for diagnostic
6839     // purposes.
6840     auto &Decomp = D.getDecompositionDeclarator();
6841     if (!Decomp.bindings().empty()) {
6842       II = Decomp.bindings()[0].Name;
6843       Name = II;
6844     }
6845   } else if (!II) {
6846     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6847     return nullptr;
6848   }
6849 
6850 
6851   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6852   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6853 
6854   // dllimport globals without explicit storage class are treated as extern. We
6855   // have to change the storage class this early to get the right DeclContext.
6856   if (SC == SC_None && !DC->isRecord() &&
6857       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6858       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6859     SC = SC_Extern;
6860 
6861   DeclContext *OriginalDC = DC;
6862   bool IsLocalExternDecl = SC == SC_Extern &&
6863                            adjustContextForLocalExternDecl(DC);
6864 
6865   if (SCSpec == DeclSpec::SCS_mutable) {
6866     // mutable can only appear on non-static class members, so it's always
6867     // an error here
6868     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6869     D.setInvalidType();
6870     SC = SC_None;
6871   }
6872 
6873   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6874       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6875                               D.getDeclSpec().getStorageClassSpecLoc())) {
6876     // In C++11, the 'register' storage class specifier is deprecated.
6877     // Suppress the warning in system macros, it's used in macros in some
6878     // popular C system headers, such as in glibc's htonl() macro.
6879     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6880          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6881                                    : diag::warn_deprecated_register)
6882       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6883   }
6884 
6885   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6886 
6887   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6888     // C99 6.9p2: The storage-class specifiers auto and register shall not
6889     // appear in the declaration specifiers in an external declaration.
6890     // Global Register+Asm is a GNU extension we support.
6891     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6892       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6893       D.setInvalidType();
6894     }
6895   }
6896 
6897   // If this variable has a variable-modified type and an initializer, try to
6898   // fold to a constant-sized type. This is otherwise invalid.
6899   if (D.hasInitializer() && R->isVariablyModifiedType())
6900     tryToFixVariablyModifiedVarType(*this, TInfo, R, D.getIdentifierLoc(),
6901                                     /*DiagID=*/0);
6902 
6903   bool IsMemberSpecialization = false;
6904   bool IsVariableTemplateSpecialization = false;
6905   bool IsPartialSpecialization = false;
6906   bool IsVariableTemplate = false;
6907   VarDecl *NewVD = nullptr;
6908   VarTemplateDecl *NewTemplate = nullptr;
6909   TemplateParameterList *TemplateParams = nullptr;
6910   if (!getLangOpts().CPlusPlus) {
6911     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6912                             II, R, TInfo, SC);
6913 
6914     if (R->getContainedDeducedType())
6915       ParsingInitForAutoVars.insert(NewVD);
6916 
6917     if (D.isInvalidType())
6918       NewVD->setInvalidDecl();
6919 
6920     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6921         NewVD->hasLocalStorage())
6922       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6923                             NTCUC_AutoVar, NTCUK_Destruct);
6924   } else {
6925     bool Invalid = false;
6926 
6927     if (DC->isRecord() && !CurContext->isRecord()) {
6928       // This is an out-of-line definition of a static data member.
6929       switch (SC) {
6930       case SC_None:
6931         break;
6932       case SC_Static:
6933         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6934              diag::err_static_out_of_line)
6935           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6936         break;
6937       case SC_Auto:
6938       case SC_Register:
6939       case SC_Extern:
6940         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6941         // to names of variables declared in a block or to function parameters.
6942         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6943         // of class members
6944 
6945         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6946              diag::err_storage_class_for_static_member)
6947           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6948         break;
6949       case SC_PrivateExtern:
6950         llvm_unreachable("C storage class in c++!");
6951       }
6952     }
6953 
6954     if (SC == SC_Static && CurContext->isRecord()) {
6955       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6956         // Walk up the enclosing DeclContexts to check for any that are
6957         // incompatible with static data members.
6958         const DeclContext *FunctionOrMethod = nullptr;
6959         const CXXRecordDecl *AnonStruct = nullptr;
6960         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6961           if (Ctxt->isFunctionOrMethod()) {
6962             FunctionOrMethod = Ctxt;
6963             break;
6964           }
6965           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6966           if (ParentDecl && !ParentDecl->getDeclName()) {
6967             AnonStruct = ParentDecl;
6968             break;
6969           }
6970         }
6971         if (FunctionOrMethod) {
6972           // C++ [class.static.data]p5: A local class shall not have static data
6973           // members.
6974           Diag(D.getIdentifierLoc(),
6975                diag::err_static_data_member_not_allowed_in_local_class)
6976             << Name << RD->getDeclName() << RD->getTagKind();
6977         } else if (AnonStruct) {
6978           // C++ [class.static.data]p4: Unnamed classes and classes contained
6979           // directly or indirectly within unnamed classes shall not contain
6980           // static data members.
6981           Diag(D.getIdentifierLoc(),
6982                diag::err_static_data_member_not_allowed_in_anon_struct)
6983             << Name << AnonStruct->getTagKind();
6984           Invalid = true;
6985         } else if (RD->isUnion()) {
6986           // C++98 [class.union]p1: If a union contains a static data member,
6987           // the program is ill-formed. C++11 drops this restriction.
6988           Diag(D.getIdentifierLoc(),
6989                getLangOpts().CPlusPlus11
6990                  ? diag::warn_cxx98_compat_static_data_member_in_union
6991                  : diag::ext_static_data_member_in_union) << Name;
6992         }
6993       }
6994     }
6995 
6996     // Match up the template parameter lists with the scope specifier, then
6997     // determine whether we have a template or a template specialization.
6998     bool InvalidScope = false;
6999     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7000         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7001         D.getCXXScopeSpec(),
7002         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7003             ? D.getName().TemplateId
7004             : nullptr,
7005         TemplateParamLists,
7006         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7007     Invalid |= InvalidScope;
7008 
7009     if (TemplateParams) {
7010       if (!TemplateParams->size() &&
7011           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7012         // There is an extraneous 'template<>' for this variable. Complain
7013         // about it, but allow the declaration of the variable.
7014         Diag(TemplateParams->getTemplateLoc(),
7015              diag::err_template_variable_noparams)
7016           << II
7017           << SourceRange(TemplateParams->getTemplateLoc(),
7018                          TemplateParams->getRAngleLoc());
7019         TemplateParams = nullptr;
7020       } else {
7021         // Check that we can declare a template here.
7022         if (CheckTemplateDeclScope(S, TemplateParams))
7023           return nullptr;
7024 
7025         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7026           // This is an explicit specialization or a partial specialization.
7027           IsVariableTemplateSpecialization = true;
7028           IsPartialSpecialization = TemplateParams->size() > 0;
7029         } else { // if (TemplateParams->size() > 0)
7030           // This is a template declaration.
7031           IsVariableTemplate = true;
7032 
7033           // Only C++1y supports variable templates (N3651).
7034           Diag(D.getIdentifierLoc(),
7035                getLangOpts().CPlusPlus14
7036                    ? diag::warn_cxx11_compat_variable_template
7037                    : diag::ext_variable_template);
7038         }
7039       }
7040     } else {
7041       // Check that we can declare a member specialization here.
7042       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7043           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7044         return nullptr;
7045       assert((Invalid ||
7046               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7047              "should have a 'template<>' for this decl");
7048     }
7049 
7050     if (IsVariableTemplateSpecialization) {
7051       SourceLocation TemplateKWLoc =
7052           TemplateParamLists.size() > 0
7053               ? TemplateParamLists[0]->getTemplateLoc()
7054               : SourceLocation();
7055       DeclResult Res = ActOnVarTemplateSpecialization(
7056           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7057           IsPartialSpecialization);
7058       if (Res.isInvalid())
7059         return nullptr;
7060       NewVD = cast<VarDecl>(Res.get());
7061       AddToScope = false;
7062     } else if (D.isDecompositionDeclarator()) {
7063       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7064                                         D.getIdentifierLoc(), R, TInfo, SC,
7065                                         Bindings);
7066     } else
7067       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7068                               D.getIdentifierLoc(), II, R, TInfo, SC);
7069 
7070     // If this is supposed to be a variable template, create it as such.
7071     if (IsVariableTemplate) {
7072       NewTemplate =
7073           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7074                                   TemplateParams, NewVD);
7075       NewVD->setDescribedVarTemplate(NewTemplate);
7076     }
7077 
7078     // If this decl has an auto type in need of deduction, make a note of the
7079     // Decl so we can diagnose uses of it in its own initializer.
7080     if (R->getContainedDeducedType())
7081       ParsingInitForAutoVars.insert(NewVD);
7082 
7083     if (D.isInvalidType() || Invalid) {
7084       NewVD->setInvalidDecl();
7085       if (NewTemplate)
7086         NewTemplate->setInvalidDecl();
7087     }
7088 
7089     SetNestedNameSpecifier(*this, NewVD, D);
7090 
7091     // If we have any template parameter lists that don't directly belong to
7092     // the variable (matching the scope specifier), store them.
7093     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7094     if (TemplateParamLists.size() > VDTemplateParamLists)
7095       NewVD->setTemplateParameterListsInfo(
7096           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7097   }
7098 
7099   if (D.getDeclSpec().isInlineSpecified()) {
7100     if (!getLangOpts().CPlusPlus) {
7101       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7102           << 0;
7103     } else if (CurContext->isFunctionOrMethod()) {
7104       // 'inline' is not allowed on block scope variable declaration.
7105       Diag(D.getDeclSpec().getInlineSpecLoc(),
7106            diag::err_inline_declaration_block_scope) << Name
7107         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7108     } else {
7109       Diag(D.getDeclSpec().getInlineSpecLoc(),
7110            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7111                                      : diag::ext_inline_variable);
7112       NewVD->setInlineSpecified();
7113     }
7114   }
7115 
7116   // Set the lexical context. If the declarator has a C++ scope specifier, the
7117   // lexical context will be different from the semantic context.
7118   NewVD->setLexicalDeclContext(CurContext);
7119   if (NewTemplate)
7120     NewTemplate->setLexicalDeclContext(CurContext);
7121 
7122   if (IsLocalExternDecl) {
7123     if (D.isDecompositionDeclarator())
7124       for (auto *B : Bindings)
7125         B->setLocalExternDecl();
7126     else
7127       NewVD->setLocalExternDecl();
7128   }
7129 
7130   bool EmitTLSUnsupportedError = false;
7131   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7132     // C++11 [dcl.stc]p4:
7133     //   When thread_local is applied to a variable of block scope the
7134     //   storage-class-specifier static is implied if it does not appear
7135     //   explicitly.
7136     // Core issue: 'static' is not implied if the variable is declared
7137     //   'extern'.
7138     if (NewVD->hasLocalStorage() &&
7139         (SCSpec != DeclSpec::SCS_unspecified ||
7140          TSCS != DeclSpec::TSCS_thread_local ||
7141          !DC->isFunctionOrMethod()))
7142       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7143            diag::err_thread_non_global)
7144         << DeclSpec::getSpecifierName(TSCS);
7145     else if (!Context.getTargetInfo().isTLSSupported()) {
7146       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7147           getLangOpts().SYCLIsDevice) {
7148         // Postpone error emission until we've collected attributes required to
7149         // figure out whether it's a host or device variable and whether the
7150         // error should be ignored.
7151         EmitTLSUnsupportedError = true;
7152         // We still need to mark the variable as TLS so it shows up in AST with
7153         // proper storage class for other tools to use even if we're not going
7154         // to emit any code for it.
7155         NewVD->setTSCSpec(TSCS);
7156       } else
7157         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7158              diag::err_thread_unsupported);
7159     } else
7160       NewVD->setTSCSpec(TSCS);
7161   }
7162 
7163   switch (D.getDeclSpec().getConstexprSpecifier()) {
7164   case ConstexprSpecKind::Unspecified:
7165     break;
7166 
7167   case ConstexprSpecKind::Consteval:
7168     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7169          diag::err_constexpr_wrong_decl_kind)
7170         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7171     LLVM_FALLTHROUGH;
7172 
7173   case ConstexprSpecKind::Constexpr:
7174     NewVD->setConstexpr(true);
7175     MaybeAddCUDAConstantAttr(NewVD);
7176     // C++1z [dcl.spec.constexpr]p1:
7177     //   A static data member declared with the constexpr specifier is
7178     //   implicitly an inline variable.
7179     if (NewVD->isStaticDataMember() &&
7180         (getLangOpts().CPlusPlus17 ||
7181          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7182       NewVD->setImplicitlyInline();
7183     break;
7184 
7185   case ConstexprSpecKind::Constinit:
7186     if (!NewVD->hasGlobalStorage())
7187       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7188            diag::err_constinit_local_variable);
7189     else
7190       NewVD->addAttr(ConstInitAttr::Create(
7191           Context, D.getDeclSpec().getConstexprSpecLoc(),
7192           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7193     break;
7194   }
7195 
7196   // C99 6.7.4p3
7197   //   An inline definition of a function with external linkage shall
7198   //   not contain a definition of a modifiable object with static or
7199   //   thread storage duration...
7200   // We only apply this when the function is required to be defined
7201   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7202   // that a local variable with thread storage duration still has to
7203   // be marked 'static'.  Also note that it's possible to get these
7204   // semantics in C++ using __attribute__((gnu_inline)).
7205   if (SC == SC_Static && S->getFnParent() != nullptr &&
7206       !NewVD->getType().isConstQualified()) {
7207     FunctionDecl *CurFD = getCurFunctionDecl();
7208     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7209       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7210            diag::warn_static_local_in_extern_inline);
7211       MaybeSuggestAddingStaticToDecl(CurFD);
7212     }
7213   }
7214 
7215   if (D.getDeclSpec().isModulePrivateSpecified()) {
7216     if (IsVariableTemplateSpecialization)
7217       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7218           << (IsPartialSpecialization ? 1 : 0)
7219           << FixItHint::CreateRemoval(
7220                  D.getDeclSpec().getModulePrivateSpecLoc());
7221     else if (IsMemberSpecialization)
7222       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7223         << 2
7224         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7225     else if (NewVD->hasLocalStorage())
7226       Diag(NewVD->getLocation(), diag::err_module_private_local)
7227           << 0 << NewVD
7228           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7229           << FixItHint::CreateRemoval(
7230                  D.getDeclSpec().getModulePrivateSpecLoc());
7231     else {
7232       NewVD->setModulePrivate();
7233       if (NewTemplate)
7234         NewTemplate->setModulePrivate();
7235       for (auto *B : Bindings)
7236         B->setModulePrivate();
7237     }
7238   }
7239 
7240   if (getLangOpts().OpenCL) {
7241 
7242     deduceOpenCLAddressSpace(NewVD);
7243 
7244     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7245   }
7246 
7247   // Handle attributes prior to checking for duplicates in MergeVarDecl
7248   ProcessDeclAttributes(S, NewVD, D);
7249 
7250   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7251       getLangOpts().SYCLIsDevice) {
7252     if (EmitTLSUnsupportedError &&
7253         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7254          (getLangOpts().OpenMPIsDevice &&
7255           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7256       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7257            diag::err_thread_unsupported);
7258 
7259     if (EmitTLSUnsupportedError &&
7260         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7261       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7262     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7263     // storage [duration]."
7264     if (SC == SC_None && S->getFnParent() != nullptr &&
7265         (NewVD->hasAttr<CUDASharedAttr>() ||
7266          NewVD->hasAttr<CUDAConstantAttr>())) {
7267       NewVD->setStorageClass(SC_Static);
7268     }
7269   }
7270 
7271   // Ensure that dllimport globals without explicit storage class are treated as
7272   // extern. The storage class is set above using parsed attributes. Now we can
7273   // check the VarDecl itself.
7274   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7275          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7276          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7277 
7278   // In auto-retain/release, infer strong retension for variables of
7279   // retainable type.
7280   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7281     NewVD->setInvalidDecl();
7282 
7283   // Handle GNU asm-label extension (encoded as an attribute).
7284   if (Expr *E = (Expr*)D.getAsmLabel()) {
7285     // The parser guarantees this is a string.
7286     StringLiteral *SE = cast<StringLiteral>(E);
7287     StringRef Label = SE->getString();
7288     if (S->getFnParent() != nullptr) {
7289       switch (SC) {
7290       case SC_None:
7291       case SC_Auto:
7292         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7293         break;
7294       case SC_Register:
7295         // Local Named register
7296         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7297             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7298           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7299         break;
7300       case SC_Static:
7301       case SC_Extern:
7302       case SC_PrivateExtern:
7303         break;
7304       }
7305     } else if (SC == SC_Register) {
7306       // Global Named register
7307       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7308         const auto &TI = Context.getTargetInfo();
7309         bool HasSizeMismatch;
7310 
7311         if (!TI.isValidGCCRegisterName(Label))
7312           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7313         else if (!TI.validateGlobalRegisterVariable(Label,
7314                                                     Context.getTypeSize(R),
7315                                                     HasSizeMismatch))
7316           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7317         else if (HasSizeMismatch)
7318           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7319       }
7320 
7321       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7322         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7323         NewVD->setInvalidDecl(true);
7324       }
7325     }
7326 
7327     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7328                                         /*IsLiteralLabel=*/true,
7329                                         SE->getStrTokenLoc(0)));
7330   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7331     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7332       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7333     if (I != ExtnameUndeclaredIdentifiers.end()) {
7334       if (isDeclExternC(NewVD)) {
7335         NewVD->addAttr(I->second);
7336         ExtnameUndeclaredIdentifiers.erase(I);
7337       } else
7338         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7339             << /*Variable*/1 << NewVD;
7340     }
7341   }
7342 
7343   // Find the shadowed declaration before filtering for scope.
7344   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7345                                 ? getShadowedDeclaration(NewVD, Previous)
7346                                 : nullptr;
7347 
7348   // Don't consider existing declarations that are in a different
7349   // scope and are out-of-semantic-context declarations (if the new
7350   // declaration has linkage).
7351   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7352                        D.getCXXScopeSpec().isNotEmpty() ||
7353                        IsMemberSpecialization ||
7354                        IsVariableTemplateSpecialization);
7355 
7356   // Check whether the previous declaration is in the same block scope. This
7357   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7358   if (getLangOpts().CPlusPlus &&
7359       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7360     NewVD->setPreviousDeclInSameBlockScope(
7361         Previous.isSingleResult() && !Previous.isShadowed() &&
7362         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7363 
7364   if (!getLangOpts().CPlusPlus) {
7365     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7366   } else {
7367     // If this is an explicit specialization of a static data member, check it.
7368     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7369         CheckMemberSpecialization(NewVD, Previous))
7370       NewVD->setInvalidDecl();
7371 
7372     // Merge the decl with the existing one if appropriate.
7373     if (!Previous.empty()) {
7374       if (Previous.isSingleResult() &&
7375           isa<FieldDecl>(Previous.getFoundDecl()) &&
7376           D.getCXXScopeSpec().isSet()) {
7377         // The user tried to define a non-static data member
7378         // out-of-line (C++ [dcl.meaning]p1).
7379         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7380           << D.getCXXScopeSpec().getRange();
7381         Previous.clear();
7382         NewVD->setInvalidDecl();
7383       }
7384     } else if (D.getCXXScopeSpec().isSet()) {
7385       // No previous declaration in the qualifying scope.
7386       Diag(D.getIdentifierLoc(), diag::err_no_member)
7387         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7388         << D.getCXXScopeSpec().getRange();
7389       NewVD->setInvalidDecl();
7390     }
7391 
7392     if (!IsVariableTemplateSpecialization)
7393       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7394 
7395     if (NewTemplate) {
7396       VarTemplateDecl *PrevVarTemplate =
7397           NewVD->getPreviousDecl()
7398               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7399               : nullptr;
7400 
7401       // Check the template parameter list of this declaration, possibly
7402       // merging in the template parameter list from the previous variable
7403       // template declaration.
7404       if (CheckTemplateParameterList(
7405               TemplateParams,
7406               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7407                               : nullptr,
7408               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7409                DC->isDependentContext())
7410                   ? TPC_ClassTemplateMember
7411                   : TPC_VarTemplate))
7412         NewVD->setInvalidDecl();
7413 
7414       // If we are providing an explicit specialization of a static variable
7415       // template, make a note of that.
7416       if (PrevVarTemplate &&
7417           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7418         PrevVarTemplate->setMemberSpecialization();
7419     }
7420   }
7421 
7422   // Diagnose shadowed variables iff this isn't a redeclaration.
7423   if (ShadowedDecl && !D.isRedeclaration())
7424     CheckShadow(NewVD, ShadowedDecl, Previous);
7425 
7426   ProcessPragmaWeak(S, NewVD);
7427 
7428   // If this is the first declaration of an extern C variable, update
7429   // the map of such variables.
7430   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7431       isIncompleteDeclExternC(*this, NewVD))
7432     RegisterLocallyScopedExternCDecl(NewVD, S);
7433 
7434   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7435     MangleNumberingContext *MCtx;
7436     Decl *ManglingContextDecl;
7437     std::tie(MCtx, ManglingContextDecl) =
7438         getCurrentMangleNumberContext(NewVD->getDeclContext());
7439     if (MCtx) {
7440       Context.setManglingNumber(
7441           NewVD, MCtx->getManglingNumber(
7442                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7443       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7444     }
7445   }
7446 
7447   // Special handling of variable named 'main'.
7448   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7449       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7450       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7451 
7452     // C++ [basic.start.main]p3
7453     // A program that declares a variable main at global scope is ill-formed.
7454     if (getLangOpts().CPlusPlus)
7455       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7456 
7457     // In C, and external-linkage variable named main results in undefined
7458     // behavior.
7459     else if (NewVD->hasExternalFormalLinkage())
7460       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7461   }
7462 
7463   if (D.isRedeclaration() && !Previous.empty()) {
7464     NamedDecl *Prev = Previous.getRepresentativeDecl();
7465     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7466                                    D.isFunctionDefinition());
7467   }
7468 
7469   if (NewTemplate) {
7470     if (NewVD->isInvalidDecl())
7471       NewTemplate->setInvalidDecl();
7472     ActOnDocumentableDecl(NewTemplate);
7473     return NewTemplate;
7474   }
7475 
7476   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7477     CompleteMemberSpecialization(NewVD, Previous);
7478 
7479   return NewVD;
7480 }
7481 
7482 /// Enum describing the %select options in diag::warn_decl_shadow.
7483 enum ShadowedDeclKind {
7484   SDK_Local,
7485   SDK_Global,
7486   SDK_StaticMember,
7487   SDK_Field,
7488   SDK_Typedef,
7489   SDK_Using,
7490   SDK_StructuredBinding
7491 };
7492 
7493 /// Determine what kind of declaration we're shadowing.
7494 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7495                                                 const DeclContext *OldDC) {
7496   if (isa<TypeAliasDecl>(ShadowedDecl))
7497     return SDK_Using;
7498   else if (isa<TypedefDecl>(ShadowedDecl))
7499     return SDK_Typedef;
7500   else if (isa<BindingDecl>(ShadowedDecl))
7501     return SDK_StructuredBinding;
7502   else if (isa<RecordDecl>(OldDC))
7503     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7504 
7505   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7506 }
7507 
7508 /// Return the location of the capture if the given lambda captures the given
7509 /// variable \p VD, or an invalid source location otherwise.
7510 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7511                                          const VarDecl *VD) {
7512   for (const Capture &Capture : LSI->Captures) {
7513     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7514       return Capture.getLocation();
7515   }
7516   return SourceLocation();
7517 }
7518 
7519 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7520                                      const LookupResult &R) {
7521   // Only diagnose if we're shadowing an unambiguous field or variable.
7522   if (R.getResultKind() != LookupResult::Found)
7523     return false;
7524 
7525   // Return false if warning is ignored.
7526   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7527 }
7528 
7529 /// Return the declaration shadowed by the given variable \p D, or null
7530 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7531 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7532                                         const LookupResult &R) {
7533   if (!shouldWarnIfShadowedDecl(Diags, R))
7534     return nullptr;
7535 
7536   // Don't diagnose declarations at file scope.
7537   if (D->hasGlobalStorage())
7538     return nullptr;
7539 
7540   NamedDecl *ShadowedDecl = R.getFoundDecl();
7541   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7542                                                             : nullptr;
7543 }
7544 
7545 /// Return the declaration shadowed by the given typedef \p D, or null
7546 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7547 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7548                                         const LookupResult &R) {
7549   // Don't warn if typedef declaration is part of a class
7550   if (D->getDeclContext()->isRecord())
7551     return nullptr;
7552 
7553   if (!shouldWarnIfShadowedDecl(Diags, R))
7554     return nullptr;
7555 
7556   NamedDecl *ShadowedDecl = R.getFoundDecl();
7557   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7558 }
7559 
7560 /// Return the declaration shadowed by the given variable \p D, or null
7561 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7562 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7563                                         const LookupResult &R) {
7564   if (!shouldWarnIfShadowedDecl(Diags, R))
7565     return nullptr;
7566 
7567   NamedDecl *ShadowedDecl = R.getFoundDecl();
7568   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7569                                                             : nullptr;
7570 }
7571 
7572 /// Diagnose variable or built-in function shadowing.  Implements
7573 /// -Wshadow.
7574 ///
7575 /// This method is called whenever a VarDecl is added to a "useful"
7576 /// scope.
7577 ///
7578 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7579 /// \param R the lookup of the name
7580 ///
7581 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7582                        const LookupResult &R) {
7583   DeclContext *NewDC = D->getDeclContext();
7584 
7585   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7586     // Fields are not shadowed by variables in C++ static methods.
7587     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7588       if (MD->isStatic())
7589         return;
7590 
7591     // Fields shadowed by constructor parameters are a special case. Usually
7592     // the constructor initializes the field with the parameter.
7593     if (isa<CXXConstructorDecl>(NewDC))
7594       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7595         // Remember that this was shadowed so we can either warn about its
7596         // modification or its existence depending on warning settings.
7597         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7598         return;
7599       }
7600   }
7601 
7602   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7603     if (shadowedVar->isExternC()) {
7604       // For shadowing external vars, make sure that we point to the global
7605       // declaration, not a locally scoped extern declaration.
7606       for (auto I : shadowedVar->redecls())
7607         if (I->isFileVarDecl()) {
7608           ShadowedDecl = I;
7609           break;
7610         }
7611     }
7612 
7613   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7614 
7615   unsigned WarningDiag = diag::warn_decl_shadow;
7616   SourceLocation CaptureLoc;
7617   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7618       isa<CXXMethodDecl>(NewDC)) {
7619     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7620       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7621         if (RD->getLambdaCaptureDefault() == LCD_None) {
7622           // Try to avoid warnings for lambdas with an explicit capture list.
7623           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7624           // Warn only when the lambda captures the shadowed decl explicitly.
7625           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7626           if (CaptureLoc.isInvalid())
7627             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7628         } else {
7629           // Remember that this was shadowed so we can avoid the warning if the
7630           // shadowed decl isn't captured and the warning settings allow it.
7631           cast<LambdaScopeInfo>(getCurFunction())
7632               ->ShadowingDecls.push_back(
7633                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7634           return;
7635         }
7636       }
7637 
7638       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7639         // A variable can't shadow a local variable in an enclosing scope, if
7640         // they are separated by a non-capturing declaration context.
7641         for (DeclContext *ParentDC = NewDC;
7642              ParentDC && !ParentDC->Equals(OldDC);
7643              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7644           // Only block literals, captured statements, and lambda expressions
7645           // can capture; other scopes don't.
7646           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7647               !isLambdaCallOperator(ParentDC)) {
7648             return;
7649           }
7650         }
7651       }
7652     }
7653   }
7654 
7655   // Only warn about certain kinds of shadowing for class members.
7656   if (NewDC && NewDC->isRecord()) {
7657     // In particular, don't warn about shadowing non-class members.
7658     if (!OldDC->isRecord())
7659       return;
7660 
7661     // TODO: should we warn about static data members shadowing
7662     // static data members from base classes?
7663 
7664     // TODO: don't diagnose for inaccessible shadowed members.
7665     // This is hard to do perfectly because we might friend the
7666     // shadowing context, but that's just a false negative.
7667   }
7668 
7669 
7670   DeclarationName Name = R.getLookupName();
7671 
7672   // Emit warning and note.
7673   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7674     return;
7675   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7676   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7677   if (!CaptureLoc.isInvalid())
7678     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7679         << Name << /*explicitly*/ 1;
7680   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7681 }
7682 
7683 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7684 /// when these variables are captured by the lambda.
7685 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7686   for (const auto &Shadow : LSI->ShadowingDecls) {
7687     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7688     // Try to avoid the warning when the shadowed decl isn't captured.
7689     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7690     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7691     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7692                                        ? diag::warn_decl_shadow_uncaptured_local
7693                                        : diag::warn_decl_shadow)
7694         << Shadow.VD->getDeclName()
7695         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7696     if (!CaptureLoc.isInvalid())
7697       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7698           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7699     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7700   }
7701 }
7702 
7703 /// Check -Wshadow without the advantage of a previous lookup.
7704 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7705   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7706     return;
7707 
7708   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7709                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7710   LookupName(R, S);
7711   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7712     CheckShadow(D, ShadowedDecl, R);
7713 }
7714 
7715 /// Check if 'E', which is an expression that is about to be modified, refers
7716 /// to a constructor parameter that shadows a field.
7717 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7718   // Quickly ignore expressions that can't be shadowing ctor parameters.
7719   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7720     return;
7721   E = E->IgnoreParenImpCasts();
7722   auto *DRE = dyn_cast<DeclRefExpr>(E);
7723   if (!DRE)
7724     return;
7725   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7726   auto I = ShadowingDecls.find(D);
7727   if (I == ShadowingDecls.end())
7728     return;
7729   const NamedDecl *ShadowedDecl = I->second;
7730   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7731   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7732   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7733   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7734 
7735   // Avoid issuing multiple warnings about the same decl.
7736   ShadowingDecls.erase(I);
7737 }
7738 
7739 /// Check for conflict between this global or extern "C" declaration and
7740 /// previous global or extern "C" declarations. This is only used in C++.
7741 template<typename T>
7742 static bool checkGlobalOrExternCConflict(
7743     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7744   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7745   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7746 
7747   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7748     // The common case: this global doesn't conflict with any extern "C"
7749     // declaration.
7750     return false;
7751   }
7752 
7753   if (Prev) {
7754     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7755       // Both the old and new declarations have C language linkage. This is a
7756       // redeclaration.
7757       Previous.clear();
7758       Previous.addDecl(Prev);
7759       return true;
7760     }
7761 
7762     // This is a global, non-extern "C" declaration, and there is a previous
7763     // non-global extern "C" declaration. Diagnose if this is a variable
7764     // declaration.
7765     if (!isa<VarDecl>(ND))
7766       return false;
7767   } else {
7768     // The declaration is extern "C". Check for any declaration in the
7769     // translation unit which might conflict.
7770     if (IsGlobal) {
7771       // We have already performed the lookup into the translation unit.
7772       IsGlobal = false;
7773       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7774            I != E; ++I) {
7775         if (isa<VarDecl>(*I)) {
7776           Prev = *I;
7777           break;
7778         }
7779       }
7780     } else {
7781       DeclContext::lookup_result R =
7782           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7783       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7784            I != E; ++I) {
7785         if (isa<VarDecl>(*I)) {
7786           Prev = *I;
7787           break;
7788         }
7789         // FIXME: If we have any other entity with this name in global scope,
7790         // the declaration is ill-formed, but that is a defect: it breaks the
7791         // 'stat' hack, for instance. Only variables can have mangled name
7792         // clashes with extern "C" declarations, so only they deserve a
7793         // diagnostic.
7794       }
7795     }
7796 
7797     if (!Prev)
7798       return false;
7799   }
7800 
7801   // Use the first declaration's location to ensure we point at something which
7802   // is lexically inside an extern "C" linkage-spec.
7803   assert(Prev && "should have found a previous declaration to diagnose");
7804   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7805     Prev = FD->getFirstDecl();
7806   else
7807     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7808 
7809   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7810     << IsGlobal << ND;
7811   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7812     << IsGlobal;
7813   return false;
7814 }
7815 
7816 /// Apply special rules for handling extern "C" declarations. Returns \c true
7817 /// if we have found that this is a redeclaration of some prior entity.
7818 ///
7819 /// Per C++ [dcl.link]p6:
7820 ///   Two declarations [for a function or variable] with C language linkage
7821 ///   with the same name that appear in different scopes refer to the same
7822 ///   [entity]. An entity with C language linkage shall not be declared with
7823 ///   the same name as an entity in global scope.
7824 template<typename T>
7825 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7826                                                   LookupResult &Previous) {
7827   if (!S.getLangOpts().CPlusPlus) {
7828     // In C, when declaring a global variable, look for a corresponding 'extern'
7829     // variable declared in function scope. We don't need this in C++, because
7830     // we find local extern decls in the surrounding file-scope DeclContext.
7831     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7832       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7833         Previous.clear();
7834         Previous.addDecl(Prev);
7835         return true;
7836       }
7837     }
7838     return false;
7839   }
7840 
7841   // A declaration in the translation unit can conflict with an extern "C"
7842   // declaration.
7843   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7844     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7845 
7846   // An extern "C" declaration can conflict with a declaration in the
7847   // translation unit or can be a redeclaration of an extern "C" declaration
7848   // in another scope.
7849   if (isIncompleteDeclExternC(S,ND))
7850     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7851 
7852   // Neither global nor extern "C": nothing to do.
7853   return false;
7854 }
7855 
7856 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7857   // If the decl is already known invalid, don't check it.
7858   if (NewVD->isInvalidDecl())
7859     return;
7860 
7861   QualType T = NewVD->getType();
7862 
7863   // Defer checking an 'auto' type until its initializer is attached.
7864   if (T->isUndeducedType())
7865     return;
7866 
7867   if (NewVD->hasAttrs())
7868     CheckAlignasUnderalignment(NewVD);
7869 
7870   if (T->isObjCObjectType()) {
7871     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7872       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7873     T = Context.getObjCObjectPointerType(T);
7874     NewVD->setType(T);
7875   }
7876 
7877   // Emit an error if an address space was applied to decl with local storage.
7878   // This includes arrays of objects with address space qualifiers, but not
7879   // automatic variables that point to other address spaces.
7880   // ISO/IEC TR 18037 S5.1.2
7881   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7882       T.getAddressSpace() != LangAS::Default) {
7883     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7884     NewVD->setInvalidDecl();
7885     return;
7886   }
7887 
7888   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7889   // scope.
7890   if (getLangOpts().OpenCLVersion == 120 &&
7891       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7892       NewVD->isStaticLocal()) {
7893     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7894     NewVD->setInvalidDecl();
7895     return;
7896   }
7897 
7898   if (getLangOpts().OpenCL) {
7899     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7900     if (NewVD->hasAttr<BlocksAttr>()) {
7901       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7902       return;
7903     }
7904 
7905     if (T->isBlockPointerType()) {
7906       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7907       // can't use 'extern' storage class.
7908       if (!T.isConstQualified()) {
7909         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7910             << 0 /*const*/;
7911         NewVD->setInvalidDecl();
7912         return;
7913       }
7914       if (NewVD->hasExternalStorage()) {
7915         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7916         NewVD->setInvalidDecl();
7917         return;
7918       }
7919     }
7920     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7921     // __constant address space.
7922     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7923     // variables inside a function can also be declared in the global
7924     // address space.
7925     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7926     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7927     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7928         NewVD->hasExternalStorage()) {
7929       if (!T->isSamplerT() &&
7930           !T->isDependentType() &&
7931           !(T.getAddressSpace() == LangAS::opencl_constant ||
7932             (T.getAddressSpace() == LangAS::opencl_global &&
7933              (getLangOpts().OpenCLVersion == 200 ||
7934               getLangOpts().OpenCLCPlusPlus)))) {
7935         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7936         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7937           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7938               << Scope << "global or constant";
7939         else
7940           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7941               << Scope << "constant";
7942         NewVD->setInvalidDecl();
7943         return;
7944       }
7945     } else {
7946       if (T.getAddressSpace() == LangAS::opencl_global) {
7947         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7948             << 1 /*is any function*/ << "global";
7949         NewVD->setInvalidDecl();
7950         return;
7951       }
7952       if (T.getAddressSpace() == LangAS::opencl_constant ||
7953           T.getAddressSpace() == LangAS::opencl_local) {
7954         FunctionDecl *FD = getCurFunctionDecl();
7955         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7956         // in functions.
7957         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7958           if (T.getAddressSpace() == LangAS::opencl_constant)
7959             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7960                 << 0 /*non-kernel only*/ << "constant";
7961           else
7962             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7963                 << 0 /*non-kernel only*/ << "local";
7964           NewVD->setInvalidDecl();
7965           return;
7966         }
7967         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7968         // in the outermost scope of a kernel function.
7969         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7970           if (!getCurScope()->isFunctionScope()) {
7971             if (T.getAddressSpace() == LangAS::opencl_constant)
7972               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7973                   << "constant";
7974             else
7975               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7976                   << "local";
7977             NewVD->setInvalidDecl();
7978             return;
7979           }
7980         }
7981       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7982                  // If we are parsing a template we didn't deduce an addr
7983                  // space yet.
7984                  T.getAddressSpace() != LangAS::Default) {
7985         // Do not allow other address spaces on automatic variable.
7986         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7987         NewVD->setInvalidDecl();
7988         return;
7989       }
7990     }
7991   }
7992 
7993   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7994       && !NewVD->hasAttr<BlocksAttr>()) {
7995     if (getLangOpts().getGC() != LangOptions::NonGC)
7996       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7997     else {
7998       assert(!getLangOpts().ObjCAutoRefCount);
7999       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8000     }
8001   }
8002 
8003   bool isVM = T->isVariablyModifiedType();
8004   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8005       NewVD->hasAttr<BlocksAttr>())
8006     setFunctionHasBranchProtectedScope();
8007 
8008   if ((isVM && NewVD->hasLinkage()) ||
8009       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8010     bool SizeIsNegative;
8011     llvm::APSInt Oversized;
8012     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8013         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8014     QualType FixedT;
8015     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8016       FixedT = FixedTInfo->getType();
8017     else if (FixedTInfo) {
8018       // Type and type-as-written are canonically different. We need to fix up
8019       // both types separately.
8020       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8021                                                    Oversized);
8022     }
8023     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8024       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8025       // FIXME: This won't give the correct result for
8026       // int a[10][n];
8027       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8028 
8029       if (NewVD->isFileVarDecl())
8030         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8031         << SizeRange;
8032       else if (NewVD->isStaticLocal())
8033         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8034         << SizeRange;
8035       else
8036         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8037         << SizeRange;
8038       NewVD->setInvalidDecl();
8039       return;
8040     }
8041 
8042     if (!FixedTInfo) {
8043       if (NewVD->isFileVarDecl())
8044         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8045       else
8046         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8047       NewVD->setInvalidDecl();
8048       return;
8049     }
8050 
8051     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8052     NewVD->setType(FixedT);
8053     NewVD->setTypeSourceInfo(FixedTInfo);
8054   }
8055 
8056   if (T->isVoidType()) {
8057     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8058     //                    of objects and functions.
8059     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8060       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8061         << T;
8062       NewVD->setInvalidDecl();
8063       return;
8064     }
8065   }
8066 
8067   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8068     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8069     NewVD->setInvalidDecl();
8070     return;
8071   }
8072 
8073   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8074     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8075     NewVD->setInvalidDecl();
8076     return;
8077   }
8078 
8079   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8080     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8081     NewVD->setInvalidDecl();
8082     return;
8083   }
8084 
8085   if (NewVD->isConstexpr() && !T->isDependentType() &&
8086       RequireLiteralType(NewVD->getLocation(), T,
8087                          diag::err_constexpr_var_non_literal)) {
8088     NewVD->setInvalidDecl();
8089     return;
8090   }
8091 
8092   // PPC MMA non-pointer types are not allowed as non-local variable types.
8093   if (Context.getTargetInfo().getTriple().isPPC64() &&
8094       !NewVD->isLocalVarDecl() &&
8095       CheckPPCMMAType(T, NewVD->getLocation())) {
8096     NewVD->setInvalidDecl();
8097     return;
8098   }
8099 }
8100 
8101 /// Perform semantic checking on a newly-created variable
8102 /// declaration.
8103 ///
8104 /// This routine performs all of the type-checking required for a
8105 /// variable declaration once it has been built. It is used both to
8106 /// check variables after they have been parsed and their declarators
8107 /// have been translated into a declaration, and to check variables
8108 /// that have been instantiated from a template.
8109 ///
8110 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8111 ///
8112 /// Returns true if the variable declaration is a redeclaration.
8113 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8114   CheckVariableDeclarationType(NewVD);
8115 
8116   // If the decl is already known invalid, don't check it.
8117   if (NewVD->isInvalidDecl())
8118     return false;
8119 
8120   // If we did not find anything by this name, look for a non-visible
8121   // extern "C" declaration with the same name.
8122   if (Previous.empty() &&
8123       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8124     Previous.setShadowed();
8125 
8126   if (!Previous.empty()) {
8127     MergeVarDecl(NewVD, Previous);
8128     return true;
8129   }
8130   return false;
8131 }
8132 
8133 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8134 /// and if so, check that it's a valid override and remember it.
8135 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8136   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8137 
8138   // Look for methods in base classes that this method might override.
8139   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8140                      /*DetectVirtual=*/false);
8141   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8142     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8143     DeclarationName Name = MD->getDeclName();
8144 
8145     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8146       // We really want to find the base class destructor here.
8147       QualType T = Context.getTypeDeclType(BaseRecord);
8148       CanQualType CT = Context.getCanonicalType(T);
8149       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8150     }
8151 
8152     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8153       CXXMethodDecl *BaseMD =
8154           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8155       if (!BaseMD || !BaseMD->isVirtual() ||
8156           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8157                      /*ConsiderCudaAttrs=*/true,
8158                      // C++2a [class.virtual]p2 does not consider requires
8159                      // clauses when overriding.
8160                      /*ConsiderRequiresClauses=*/false))
8161         continue;
8162 
8163       if (Overridden.insert(BaseMD).second) {
8164         MD->addOverriddenMethod(BaseMD);
8165         CheckOverridingFunctionReturnType(MD, BaseMD);
8166         CheckOverridingFunctionAttributes(MD, BaseMD);
8167         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8168         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8169       }
8170 
8171       // A method can only override one function from each base class. We
8172       // don't track indirectly overridden methods from bases of bases.
8173       return true;
8174     }
8175 
8176     return false;
8177   };
8178 
8179   DC->lookupInBases(VisitBase, Paths);
8180   return !Overridden.empty();
8181 }
8182 
8183 namespace {
8184   // Struct for holding all of the extra arguments needed by
8185   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8186   struct ActOnFDArgs {
8187     Scope *S;
8188     Declarator &D;
8189     MultiTemplateParamsArg TemplateParamLists;
8190     bool AddToScope;
8191   };
8192 } // end anonymous namespace
8193 
8194 namespace {
8195 
8196 // Callback to only accept typo corrections that have a non-zero edit distance.
8197 // Also only accept corrections that have the same parent decl.
8198 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8199  public:
8200   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8201                             CXXRecordDecl *Parent)
8202       : Context(Context), OriginalFD(TypoFD),
8203         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8204 
8205   bool ValidateCandidate(const TypoCorrection &candidate) override {
8206     if (candidate.getEditDistance() == 0)
8207       return false;
8208 
8209     SmallVector<unsigned, 1> MismatchedParams;
8210     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8211                                           CDeclEnd = candidate.end();
8212          CDecl != CDeclEnd; ++CDecl) {
8213       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8214 
8215       if (FD && !FD->hasBody() &&
8216           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8217         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8218           CXXRecordDecl *Parent = MD->getParent();
8219           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8220             return true;
8221         } else if (!ExpectedParent) {
8222           return true;
8223         }
8224       }
8225     }
8226 
8227     return false;
8228   }
8229 
8230   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8231     return std::make_unique<DifferentNameValidatorCCC>(*this);
8232   }
8233 
8234  private:
8235   ASTContext &Context;
8236   FunctionDecl *OriginalFD;
8237   CXXRecordDecl *ExpectedParent;
8238 };
8239 
8240 } // end anonymous namespace
8241 
8242 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8243   TypoCorrectedFunctionDefinitions.insert(F);
8244 }
8245 
8246 /// Generate diagnostics for an invalid function redeclaration.
8247 ///
8248 /// This routine handles generating the diagnostic messages for an invalid
8249 /// function redeclaration, including finding possible similar declarations
8250 /// or performing typo correction if there are no previous declarations with
8251 /// the same name.
8252 ///
8253 /// Returns a NamedDecl iff typo correction was performed and substituting in
8254 /// the new declaration name does not cause new errors.
8255 static NamedDecl *DiagnoseInvalidRedeclaration(
8256     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8257     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8258   DeclarationName Name = NewFD->getDeclName();
8259   DeclContext *NewDC = NewFD->getDeclContext();
8260   SmallVector<unsigned, 1> MismatchedParams;
8261   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8262   TypoCorrection Correction;
8263   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8264   unsigned DiagMsg =
8265     IsLocalFriend ? diag::err_no_matching_local_friend :
8266     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8267     diag::err_member_decl_does_not_match;
8268   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8269                     IsLocalFriend ? Sema::LookupLocalFriendName
8270                                   : Sema::LookupOrdinaryName,
8271                     Sema::ForVisibleRedeclaration);
8272 
8273   NewFD->setInvalidDecl();
8274   if (IsLocalFriend)
8275     SemaRef.LookupName(Prev, S);
8276   else
8277     SemaRef.LookupQualifiedName(Prev, NewDC);
8278   assert(!Prev.isAmbiguous() &&
8279          "Cannot have an ambiguity in previous-declaration lookup");
8280   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8281   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8282                                 MD ? MD->getParent() : nullptr);
8283   if (!Prev.empty()) {
8284     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8285          Func != FuncEnd; ++Func) {
8286       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8287       if (FD &&
8288           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8289         // Add 1 to the index so that 0 can mean the mismatch didn't
8290         // involve a parameter
8291         unsigned ParamNum =
8292             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8293         NearMatches.push_back(std::make_pair(FD, ParamNum));
8294       }
8295     }
8296   // If the qualified name lookup yielded nothing, try typo correction
8297   } else if ((Correction = SemaRef.CorrectTypo(
8298                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8299                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8300                   IsLocalFriend ? nullptr : NewDC))) {
8301     // Set up everything for the call to ActOnFunctionDeclarator
8302     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8303                               ExtraArgs.D.getIdentifierLoc());
8304     Previous.clear();
8305     Previous.setLookupName(Correction.getCorrection());
8306     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8307                                     CDeclEnd = Correction.end();
8308          CDecl != CDeclEnd; ++CDecl) {
8309       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8310       if (FD && !FD->hasBody() &&
8311           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8312         Previous.addDecl(FD);
8313       }
8314     }
8315     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8316 
8317     NamedDecl *Result;
8318     // Retry building the function declaration with the new previous
8319     // declarations, and with errors suppressed.
8320     {
8321       // Trap errors.
8322       Sema::SFINAETrap Trap(SemaRef);
8323 
8324       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8325       // pieces need to verify the typo-corrected C++ declaration and hopefully
8326       // eliminate the need for the parameter pack ExtraArgs.
8327       Result = SemaRef.ActOnFunctionDeclarator(
8328           ExtraArgs.S, ExtraArgs.D,
8329           Correction.getCorrectionDecl()->getDeclContext(),
8330           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8331           ExtraArgs.AddToScope);
8332 
8333       if (Trap.hasErrorOccurred())
8334         Result = nullptr;
8335     }
8336 
8337     if (Result) {
8338       // Determine which correction we picked.
8339       Decl *Canonical = Result->getCanonicalDecl();
8340       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8341            I != E; ++I)
8342         if ((*I)->getCanonicalDecl() == Canonical)
8343           Correction.setCorrectionDecl(*I);
8344 
8345       // Let Sema know about the correction.
8346       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8347       SemaRef.diagnoseTypo(
8348           Correction,
8349           SemaRef.PDiag(IsLocalFriend
8350                           ? diag::err_no_matching_local_friend_suggest
8351                           : diag::err_member_decl_does_not_match_suggest)
8352             << Name << NewDC << IsDefinition);
8353       return Result;
8354     }
8355 
8356     // Pretend the typo correction never occurred
8357     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8358                               ExtraArgs.D.getIdentifierLoc());
8359     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8360     Previous.clear();
8361     Previous.setLookupName(Name);
8362   }
8363 
8364   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8365       << Name << NewDC << IsDefinition << NewFD->getLocation();
8366 
8367   bool NewFDisConst = false;
8368   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8369     NewFDisConst = NewMD->isConst();
8370 
8371   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8372        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8373        NearMatch != NearMatchEnd; ++NearMatch) {
8374     FunctionDecl *FD = NearMatch->first;
8375     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8376     bool FDisConst = MD && MD->isConst();
8377     bool IsMember = MD || !IsLocalFriend;
8378 
8379     // FIXME: These notes are poorly worded for the local friend case.
8380     if (unsigned Idx = NearMatch->second) {
8381       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8382       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8383       if (Loc.isInvalid()) Loc = FD->getLocation();
8384       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8385                                  : diag::note_local_decl_close_param_match)
8386         << Idx << FDParam->getType()
8387         << NewFD->getParamDecl(Idx - 1)->getType();
8388     } else if (FDisConst != NewFDisConst) {
8389       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8390           << NewFDisConst << FD->getSourceRange().getEnd();
8391     } else
8392       SemaRef.Diag(FD->getLocation(),
8393                    IsMember ? diag::note_member_def_close_match
8394                             : diag::note_local_decl_close_match);
8395   }
8396   return nullptr;
8397 }
8398 
8399 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8400   switch (D.getDeclSpec().getStorageClassSpec()) {
8401   default: llvm_unreachable("Unknown storage class!");
8402   case DeclSpec::SCS_auto:
8403   case DeclSpec::SCS_register:
8404   case DeclSpec::SCS_mutable:
8405     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8406                  diag::err_typecheck_sclass_func);
8407     D.getMutableDeclSpec().ClearStorageClassSpecs();
8408     D.setInvalidType();
8409     break;
8410   case DeclSpec::SCS_unspecified: break;
8411   case DeclSpec::SCS_extern:
8412     if (D.getDeclSpec().isExternInLinkageSpec())
8413       return SC_None;
8414     return SC_Extern;
8415   case DeclSpec::SCS_static: {
8416     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8417       // C99 6.7.1p5:
8418       //   The declaration of an identifier for a function that has
8419       //   block scope shall have no explicit storage-class specifier
8420       //   other than extern
8421       // See also (C++ [dcl.stc]p4).
8422       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8423                    diag::err_static_block_func);
8424       break;
8425     } else
8426       return SC_Static;
8427   }
8428   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8429   }
8430 
8431   // No explicit storage class has already been returned
8432   return SC_None;
8433 }
8434 
8435 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8436                                            DeclContext *DC, QualType &R,
8437                                            TypeSourceInfo *TInfo,
8438                                            StorageClass SC,
8439                                            bool &IsVirtualOkay) {
8440   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8441   DeclarationName Name = NameInfo.getName();
8442 
8443   FunctionDecl *NewFD = nullptr;
8444   bool isInline = D.getDeclSpec().isInlineSpecified();
8445 
8446   if (!SemaRef.getLangOpts().CPlusPlus) {
8447     // Determine whether the function was written with a
8448     // prototype. This true when:
8449     //   - there is a prototype in the declarator, or
8450     //   - the type R of the function is some kind of typedef or other non-
8451     //     attributed reference to a type name (which eventually refers to a
8452     //     function type).
8453     bool HasPrototype =
8454       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8455       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8456 
8457     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8458                                  R, TInfo, SC, isInline, HasPrototype,
8459                                  ConstexprSpecKind::Unspecified,
8460                                  /*TrailingRequiresClause=*/nullptr);
8461     if (D.isInvalidType())
8462       NewFD->setInvalidDecl();
8463 
8464     return NewFD;
8465   }
8466 
8467   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8468 
8469   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8470   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8471     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8472                  diag::err_constexpr_wrong_decl_kind)
8473         << static_cast<int>(ConstexprKind);
8474     ConstexprKind = ConstexprSpecKind::Unspecified;
8475     D.getMutableDeclSpec().ClearConstexprSpec();
8476   }
8477   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8478 
8479   // Check that the return type is not an abstract class type.
8480   // For record types, this is done by the AbstractClassUsageDiagnoser once
8481   // the class has been completely parsed.
8482   if (!DC->isRecord() &&
8483       SemaRef.RequireNonAbstractType(
8484           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8485           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8486     D.setInvalidType();
8487 
8488   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8489     // This is a C++ constructor declaration.
8490     assert(DC->isRecord() &&
8491            "Constructors can only be declared in a member context");
8492 
8493     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8494     return CXXConstructorDecl::Create(
8495         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8496         TInfo, ExplicitSpecifier, isInline,
8497         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8498         TrailingRequiresClause);
8499 
8500   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8501     // This is a C++ destructor declaration.
8502     if (DC->isRecord()) {
8503       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8504       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8505       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8506           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8507           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8508           TrailingRequiresClause);
8509 
8510       // If the destructor needs an implicit exception specification, set it
8511       // now. FIXME: It'd be nice to be able to create the right type to start
8512       // with, but the type needs to reference the destructor declaration.
8513       if (SemaRef.getLangOpts().CPlusPlus11)
8514         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8515 
8516       IsVirtualOkay = true;
8517       return NewDD;
8518 
8519     } else {
8520       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8521       D.setInvalidType();
8522 
8523       // Create a FunctionDecl to satisfy the function definition parsing
8524       // code path.
8525       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8526                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8527                                   isInline,
8528                                   /*hasPrototype=*/true, ConstexprKind,
8529                                   TrailingRequiresClause);
8530     }
8531 
8532   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8533     if (!DC->isRecord()) {
8534       SemaRef.Diag(D.getIdentifierLoc(),
8535            diag::err_conv_function_not_member);
8536       return nullptr;
8537     }
8538 
8539     SemaRef.CheckConversionDeclarator(D, R, SC);
8540     if (D.isInvalidType())
8541       return nullptr;
8542 
8543     IsVirtualOkay = true;
8544     return CXXConversionDecl::Create(
8545         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8546         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8547         TrailingRequiresClause);
8548 
8549   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8550     if (TrailingRequiresClause)
8551       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8552                    diag::err_trailing_requires_clause_on_deduction_guide)
8553           << TrailingRequiresClause->getSourceRange();
8554     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8555 
8556     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8557                                          ExplicitSpecifier, NameInfo, R, TInfo,
8558                                          D.getEndLoc());
8559   } else if (DC->isRecord()) {
8560     // If the name of the function is the same as the name of the record,
8561     // then this must be an invalid constructor that has a return type.
8562     // (The parser checks for a return type and makes the declarator a
8563     // constructor if it has no return type).
8564     if (Name.getAsIdentifierInfo() &&
8565         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8566       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8567         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8568         << SourceRange(D.getIdentifierLoc());
8569       return nullptr;
8570     }
8571 
8572     // This is a C++ method declaration.
8573     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8574         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8575         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8576         TrailingRequiresClause);
8577     IsVirtualOkay = !Ret->isStatic();
8578     return Ret;
8579   } else {
8580     bool isFriend =
8581         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8582     if (!isFriend && SemaRef.CurContext->isRecord())
8583       return nullptr;
8584 
8585     // Determine whether the function was written with a
8586     // prototype. This true when:
8587     //   - we're in C++ (where every function has a prototype),
8588     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8589                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8590                                 ConstexprKind, TrailingRequiresClause);
8591   }
8592 }
8593 
8594 enum OpenCLParamType {
8595   ValidKernelParam,
8596   PtrPtrKernelParam,
8597   PtrKernelParam,
8598   InvalidAddrSpacePtrKernelParam,
8599   InvalidKernelParam,
8600   RecordKernelParam
8601 };
8602 
8603 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8604   // Size dependent types are just typedefs to normal integer types
8605   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8606   // integers other than by their names.
8607   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8608 
8609   // Remove typedefs one by one until we reach a typedef
8610   // for a size dependent type.
8611   QualType DesugaredTy = Ty;
8612   do {
8613     ArrayRef<StringRef> Names(SizeTypeNames);
8614     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8615     if (Names.end() != Match)
8616       return true;
8617 
8618     Ty = DesugaredTy;
8619     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8620   } while (DesugaredTy != Ty);
8621 
8622   return false;
8623 }
8624 
8625 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8626   if (PT->isPointerType()) {
8627     QualType PointeeType = PT->getPointeeType();
8628     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8629         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8630         PointeeType.getAddressSpace() == LangAS::Default)
8631       return InvalidAddrSpacePtrKernelParam;
8632 
8633     if (PointeeType->isPointerType()) {
8634       // This is a pointer to pointer parameter.
8635       // Recursively check inner type.
8636       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8637       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8638           ParamKind == InvalidKernelParam)
8639         return ParamKind;
8640 
8641       return PtrPtrKernelParam;
8642     }
8643     return PtrKernelParam;
8644   }
8645 
8646   // OpenCL v1.2 s6.9.k:
8647   // Arguments to kernel functions in a program cannot be declared with the
8648   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8649   // uintptr_t or a struct and/or union that contain fields declared to be one
8650   // of these built-in scalar types.
8651   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8652     return InvalidKernelParam;
8653 
8654   if (PT->isImageType())
8655     return PtrKernelParam;
8656 
8657   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8658     return InvalidKernelParam;
8659 
8660   // OpenCL extension spec v1.2 s9.5:
8661   // This extension adds support for half scalar and vector types as built-in
8662   // types that can be used for arithmetic operations, conversions etc.
8663   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8664     return InvalidKernelParam;
8665 
8666   if (PT->isRecordType())
8667     return RecordKernelParam;
8668 
8669   // Look into an array argument to check if it has a forbidden type.
8670   if (PT->isArrayType()) {
8671     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8672     // Call ourself to check an underlying type of an array. Since the
8673     // getPointeeOrArrayElementType returns an innermost type which is not an
8674     // array, this recursive call only happens once.
8675     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8676   }
8677 
8678   return ValidKernelParam;
8679 }
8680 
8681 static void checkIsValidOpenCLKernelParameter(
8682   Sema &S,
8683   Declarator &D,
8684   ParmVarDecl *Param,
8685   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8686   QualType PT = Param->getType();
8687 
8688   // Cache the valid types we encounter to avoid rechecking structs that are
8689   // used again
8690   if (ValidTypes.count(PT.getTypePtr()))
8691     return;
8692 
8693   switch (getOpenCLKernelParameterType(S, PT)) {
8694   case PtrPtrKernelParam:
8695     // OpenCL v3.0 s6.11.a:
8696     // A kernel function argument cannot be declared as a pointer to a pointer
8697     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8698     if (S.getLangOpts().OpenCLVersion < 120 &&
8699         !S.getLangOpts().OpenCLCPlusPlus) {
8700       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8701       D.setInvalidType();
8702       return;
8703     }
8704 
8705     ValidTypes.insert(PT.getTypePtr());
8706     return;
8707 
8708   case InvalidAddrSpacePtrKernelParam:
8709     // OpenCL v1.0 s6.5:
8710     // __kernel function arguments declared to be a pointer of a type can point
8711     // to one of the following address spaces only : __global, __local or
8712     // __constant.
8713     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8714     D.setInvalidType();
8715     return;
8716 
8717     // OpenCL v1.2 s6.9.k:
8718     // Arguments to kernel functions in a program cannot be declared with the
8719     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8720     // uintptr_t or a struct and/or union that contain fields declared to be
8721     // one of these built-in scalar types.
8722 
8723   case InvalidKernelParam:
8724     // OpenCL v1.2 s6.8 n:
8725     // A kernel function argument cannot be declared
8726     // of event_t type.
8727     // Do not diagnose half type since it is diagnosed as invalid argument
8728     // type for any function elsewhere.
8729     if (!PT->isHalfType()) {
8730       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8731 
8732       // Explain what typedefs are involved.
8733       const TypedefType *Typedef = nullptr;
8734       while ((Typedef = PT->getAs<TypedefType>())) {
8735         SourceLocation Loc = Typedef->getDecl()->getLocation();
8736         // SourceLocation may be invalid for a built-in type.
8737         if (Loc.isValid())
8738           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8739         PT = Typedef->desugar();
8740       }
8741     }
8742 
8743     D.setInvalidType();
8744     return;
8745 
8746   case PtrKernelParam:
8747   case ValidKernelParam:
8748     ValidTypes.insert(PT.getTypePtr());
8749     return;
8750 
8751   case RecordKernelParam:
8752     break;
8753   }
8754 
8755   // Track nested structs we will inspect
8756   SmallVector<const Decl *, 4> VisitStack;
8757 
8758   // Track where we are in the nested structs. Items will migrate from
8759   // VisitStack to HistoryStack as we do the DFS for bad field.
8760   SmallVector<const FieldDecl *, 4> HistoryStack;
8761   HistoryStack.push_back(nullptr);
8762 
8763   // At this point we already handled everything except of a RecordType or
8764   // an ArrayType of a RecordType.
8765   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8766   const RecordType *RecTy =
8767       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8768   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8769 
8770   VisitStack.push_back(RecTy->getDecl());
8771   assert(VisitStack.back() && "First decl null?");
8772 
8773   do {
8774     const Decl *Next = VisitStack.pop_back_val();
8775     if (!Next) {
8776       assert(!HistoryStack.empty());
8777       // Found a marker, we have gone up a level
8778       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8779         ValidTypes.insert(Hist->getType().getTypePtr());
8780 
8781       continue;
8782     }
8783 
8784     // Adds everything except the original parameter declaration (which is not a
8785     // field itself) to the history stack.
8786     const RecordDecl *RD;
8787     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8788       HistoryStack.push_back(Field);
8789 
8790       QualType FieldTy = Field->getType();
8791       // Other field types (known to be valid or invalid) are handled while we
8792       // walk around RecordDecl::fields().
8793       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8794              "Unexpected type.");
8795       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8796 
8797       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8798     } else {
8799       RD = cast<RecordDecl>(Next);
8800     }
8801 
8802     // Add a null marker so we know when we've gone back up a level
8803     VisitStack.push_back(nullptr);
8804 
8805     for (const auto *FD : RD->fields()) {
8806       QualType QT = FD->getType();
8807 
8808       if (ValidTypes.count(QT.getTypePtr()))
8809         continue;
8810 
8811       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8812       if (ParamType == ValidKernelParam)
8813         continue;
8814 
8815       if (ParamType == RecordKernelParam) {
8816         VisitStack.push_back(FD);
8817         continue;
8818       }
8819 
8820       // OpenCL v1.2 s6.9.p:
8821       // Arguments to kernel functions that are declared to be a struct or union
8822       // do not allow OpenCL objects to be passed as elements of the struct or
8823       // union.
8824       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8825           ParamType == InvalidAddrSpacePtrKernelParam) {
8826         S.Diag(Param->getLocation(),
8827                diag::err_record_with_pointers_kernel_param)
8828           << PT->isUnionType()
8829           << PT;
8830       } else {
8831         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8832       }
8833 
8834       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8835           << OrigRecDecl->getDeclName();
8836 
8837       // We have an error, now let's go back up through history and show where
8838       // the offending field came from
8839       for (ArrayRef<const FieldDecl *>::const_iterator
8840                I = HistoryStack.begin() + 1,
8841                E = HistoryStack.end();
8842            I != E; ++I) {
8843         const FieldDecl *OuterField = *I;
8844         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8845           << OuterField->getType();
8846       }
8847 
8848       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8849         << QT->isPointerType()
8850         << QT;
8851       D.setInvalidType();
8852       return;
8853     }
8854   } while (!VisitStack.empty());
8855 }
8856 
8857 /// Find the DeclContext in which a tag is implicitly declared if we see an
8858 /// elaborated type specifier in the specified context, and lookup finds
8859 /// nothing.
8860 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8861   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8862     DC = DC->getParent();
8863   return DC;
8864 }
8865 
8866 /// Find the Scope in which a tag is implicitly declared if we see an
8867 /// elaborated type specifier in the specified context, and lookup finds
8868 /// nothing.
8869 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8870   while (S->isClassScope() ||
8871          (LangOpts.CPlusPlus &&
8872           S->isFunctionPrototypeScope()) ||
8873          ((S->getFlags() & Scope::DeclScope) == 0) ||
8874          (S->getEntity() && S->getEntity()->isTransparentContext()))
8875     S = S->getParent();
8876   return S;
8877 }
8878 
8879 NamedDecl*
8880 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8881                               TypeSourceInfo *TInfo, LookupResult &Previous,
8882                               MultiTemplateParamsArg TemplateParamListsRef,
8883                               bool &AddToScope) {
8884   QualType R = TInfo->getType();
8885 
8886   assert(R->isFunctionType());
8887   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8888     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8889 
8890   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8891   for (TemplateParameterList *TPL : TemplateParamListsRef)
8892     TemplateParamLists.push_back(TPL);
8893   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8894     if (!TemplateParamLists.empty() &&
8895         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8896       TemplateParamLists.back() = Invented;
8897     else
8898       TemplateParamLists.push_back(Invented);
8899   }
8900 
8901   // TODO: consider using NameInfo for diagnostic.
8902   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8903   DeclarationName Name = NameInfo.getName();
8904   StorageClass SC = getFunctionStorageClass(*this, D);
8905 
8906   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8907     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8908          diag::err_invalid_thread)
8909       << DeclSpec::getSpecifierName(TSCS);
8910 
8911   if (D.isFirstDeclarationOfMember())
8912     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8913                            D.getIdentifierLoc());
8914 
8915   bool isFriend = false;
8916   FunctionTemplateDecl *FunctionTemplate = nullptr;
8917   bool isMemberSpecialization = false;
8918   bool isFunctionTemplateSpecialization = false;
8919 
8920   bool isDependentClassScopeExplicitSpecialization = false;
8921   bool HasExplicitTemplateArgs = false;
8922   TemplateArgumentListInfo TemplateArgs;
8923 
8924   bool isVirtualOkay = false;
8925 
8926   DeclContext *OriginalDC = DC;
8927   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8928 
8929   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8930                                               isVirtualOkay);
8931   if (!NewFD) return nullptr;
8932 
8933   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8934     NewFD->setTopLevelDeclInObjCContainer();
8935 
8936   // Set the lexical context. If this is a function-scope declaration, or has a
8937   // C++ scope specifier, or is the object of a friend declaration, the lexical
8938   // context will be different from the semantic context.
8939   NewFD->setLexicalDeclContext(CurContext);
8940 
8941   if (IsLocalExternDecl)
8942     NewFD->setLocalExternDecl();
8943 
8944   if (getLangOpts().CPlusPlus) {
8945     bool isInline = D.getDeclSpec().isInlineSpecified();
8946     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8947     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8948     isFriend = D.getDeclSpec().isFriendSpecified();
8949     if (isFriend && !isInline && D.isFunctionDefinition()) {
8950       // C++ [class.friend]p5
8951       //   A function can be defined in a friend declaration of a
8952       //   class . . . . Such a function is implicitly inline.
8953       NewFD->setImplicitlyInline();
8954     }
8955 
8956     // If this is a method defined in an __interface, and is not a constructor
8957     // or an overloaded operator, then set the pure flag (isVirtual will already
8958     // return true).
8959     if (const CXXRecordDecl *Parent =
8960           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8961       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8962         NewFD->setPure(true);
8963 
8964       // C++ [class.union]p2
8965       //   A union can have member functions, but not virtual functions.
8966       if (isVirtual && Parent->isUnion())
8967         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8968     }
8969 
8970     SetNestedNameSpecifier(*this, NewFD, D);
8971     isMemberSpecialization = false;
8972     isFunctionTemplateSpecialization = false;
8973     if (D.isInvalidType())
8974       NewFD->setInvalidDecl();
8975 
8976     // Match up the template parameter lists with the scope specifier, then
8977     // determine whether we have a template or a template specialization.
8978     bool Invalid = false;
8979     TemplateParameterList *TemplateParams =
8980         MatchTemplateParametersToScopeSpecifier(
8981             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8982             D.getCXXScopeSpec(),
8983             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8984                 ? D.getName().TemplateId
8985                 : nullptr,
8986             TemplateParamLists, isFriend, isMemberSpecialization,
8987             Invalid);
8988     if (TemplateParams) {
8989       // Check that we can declare a template here.
8990       if (CheckTemplateDeclScope(S, TemplateParams))
8991         NewFD->setInvalidDecl();
8992 
8993       if (TemplateParams->size() > 0) {
8994         // This is a function template
8995 
8996         // A destructor cannot be a template.
8997         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8998           Diag(NewFD->getLocation(), diag::err_destructor_template);
8999           NewFD->setInvalidDecl();
9000         }
9001 
9002         // If we're adding a template to a dependent context, we may need to
9003         // rebuilding some of the types used within the template parameter list,
9004         // now that we know what the current instantiation is.
9005         if (DC->isDependentContext()) {
9006           ContextRAII SavedContext(*this, DC);
9007           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9008             Invalid = true;
9009         }
9010 
9011         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9012                                                         NewFD->getLocation(),
9013                                                         Name, TemplateParams,
9014                                                         NewFD);
9015         FunctionTemplate->setLexicalDeclContext(CurContext);
9016         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9017 
9018         // For source fidelity, store the other template param lists.
9019         if (TemplateParamLists.size() > 1) {
9020           NewFD->setTemplateParameterListsInfo(Context,
9021               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9022                   .drop_back(1));
9023         }
9024       } else {
9025         // This is a function template specialization.
9026         isFunctionTemplateSpecialization = true;
9027         // For source fidelity, store all the template param lists.
9028         if (TemplateParamLists.size() > 0)
9029           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9030 
9031         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9032         if (isFriend) {
9033           // We want to remove the "template<>", found here.
9034           SourceRange RemoveRange = TemplateParams->getSourceRange();
9035 
9036           // If we remove the template<> and the name is not a
9037           // template-id, we're actually silently creating a problem:
9038           // the friend declaration will refer to an untemplated decl,
9039           // and clearly the user wants a template specialization.  So
9040           // we need to insert '<>' after the name.
9041           SourceLocation InsertLoc;
9042           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9043             InsertLoc = D.getName().getSourceRange().getEnd();
9044             InsertLoc = getLocForEndOfToken(InsertLoc);
9045           }
9046 
9047           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9048             << Name << RemoveRange
9049             << FixItHint::CreateRemoval(RemoveRange)
9050             << FixItHint::CreateInsertion(InsertLoc, "<>");
9051         }
9052       }
9053     } else {
9054       // Check that we can declare a template here.
9055       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9056           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9057         NewFD->setInvalidDecl();
9058 
9059       // All template param lists were matched against the scope specifier:
9060       // this is NOT (an explicit specialization of) a template.
9061       if (TemplateParamLists.size() > 0)
9062         // For source fidelity, store all the template param lists.
9063         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9064     }
9065 
9066     if (Invalid) {
9067       NewFD->setInvalidDecl();
9068       if (FunctionTemplate)
9069         FunctionTemplate->setInvalidDecl();
9070     }
9071 
9072     // C++ [dcl.fct.spec]p5:
9073     //   The virtual specifier shall only be used in declarations of
9074     //   nonstatic class member functions that appear within a
9075     //   member-specification of a class declaration; see 10.3.
9076     //
9077     if (isVirtual && !NewFD->isInvalidDecl()) {
9078       if (!isVirtualOkay) {
9079         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9080              diag::err_virtual_non_function);
9081       } else if (!CurContext->isRecord()) {
9082         // 'virtual' was specified outside of the class.
9083         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9084              diag::err_virtual_out_of_class)
9085           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9086       } else if (NewFD->getDescribedFunctionTemplate()) {
9087         // C++ [temp.mem]p3:
9088         //  A member function template shall not be virtual.
9089         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9090              diag::err_virtual_member_function_template)
9091           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9092       } else {
9093         // Okay: Add virtual to the method.
9094         NewFD->setVirtualAsWritten(true);
9095       }
9096 
9097       if (getLangOpts().CPlusPlus14 &&
9098           NewFD->getReturnType()->isUndeducedType())
9099         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9100     }
9101 
9102     if (getLangOpts().CPlusPlus14 &&
9103         (NewFD->isDependentContext() ||
9104          (isFriend && CurContext->isDependentContext())) &&
9105         NewFD->getReturnType()->isUndeducedType()) {
9106       // If the function template is referenced directly (for instance, as a
9107       // member of the current instantiation), pretend it has a dependent type.
9108       // This is not really justified by the standard, but is the only sane
9109       // thing to do.
9110       // FIXME: For a friend function, we have not marked the function as being
9111       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9112       const FunctionProtoType *FPT =
9113           NewFD->getType()->castAs<FunctionProtoType>();
9114       QualType Result =
9115           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9116       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9117                                              FPT->getExtProtoInfo()));
9118     }
9119 
9120     // C++ [dcl.fct.spec]p3:
9121     //  The inline specifier shall not appear on a block scope function
9122     //  declaration.
9123     if (isInline && !NewFD->isInvalidDecl()) {
9124       if (CurContext->isFunctionOrMethod()) {
9125         // 'inline' is not allowed on block scope function declaration.
9126         Diag(D.getDeclSpec().getInlineSpecLoc(),
9127              diag::err_inline_declaration_block_scope) << Name
9128           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9129       }
9130     }
9131 
9132     // C++ [dcl.fct.spec]p6:
9133     //  The explicit specifier shall be used only in the declaration of a
9134     //  constructor or conversion function within its class definition;
9135     //  see 12.3.1 and 12.3.2.
9136     if (hasExplicit && !NewFD->isInvalidDecl() &&
9137         !isa<CXXDeductionGuideDecl>(NewFD)) {
9138       if (!CurContext->isRecord()) {
9139         // 'explicit' was specified outside of the class.
9140         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9141              diag::err_explicit_out_of_class)
9142             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9143       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9144                  !isa<CXXConversionDecl>(NewFD)) {
9145         // 'explicit' was specified on a function that wasn't a constructor
9146         // or conversion function.
9147         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9148              diag::err_explicit_non_ctor_or_conv_function)
9149             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9150       }
9151     }
9152 
9153     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9154     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9155       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9156       // are implicitly inline.
9157       NewFD->setImplicitlyInline();
9158 
9159       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9160       // be either constructors or to return a literal type. Therefore,
9161       // destructors cannot be declared constexpr.
9162       if (isa<CXXDestructorDecl>(NewFD) &&
9163           (!getLangOpts().CPlusPlus20 ||
9164            ConstexprKind == ConstexprSpecKind::Consteval)) {
9165         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9166             << static_cast<int>(ConstexprKind);
9167         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9168                                     ? ConstexprSpecKind::Unspecified
9169                                     : ConstexprSpecKind::Constexpr);
9170       }
9171       // C++20 [dcl.constexpr]p2: An allocation function, or a
9172       // deallocation function shall not be declared with the consteval
9173       // specifier.
9174       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9175           (NewFD->getOverloadedOperator() == OO_New ||
9176            NewFD->getOverloadedOperator() == OO_Array_New ||
9177            NewFD->getOverloadedOperator() == OO_Delete ||
9178            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9179         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9180              diag::err_invalid_consteval_decl_kind)
9181             << NewFD;
9182         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9183       }
9184     }
9185 
9186     // If __module_private__ was specified, mark the function accordingly.
9187     if (D.getDeclSpec().isModulePrivateSpecified()) {
9188       if (isFunctionTemplateSpecialization) {
9189         SourceLocation ModulePrivateLoc
9190           = D.getDeclSpec().getModulePrivateSpecLoc();
9191         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9192           << 0
9193           << FixItHint::CreateRemoval(ModulePrivateLoc);
9194       } else {
9195         NewFD->setModulePrivate();
9196         if (FunctionTemplate)
9197           FunctionTemplate->setModulePrivate();
9198       }
9199     }
9200 
9201     if (isFriend) {
9202       if (FunctionTemplate) {
9203         FunctionTemplate->setObjectOfFriendDecl();
9204         FunctionTemplate->setAccess(AS_public);
9205       }
9206       NewFD->setObjectOfFriendDecl();
9207       NewFD->setAccess(AS_public);
9208     }
9209 
9210     // If a function is defined as defaulted or deleted, mark it as such now.
9211     // We'll do the relevant checks on defaulted / deleted functions later.
9212     switch (D.getFunctionDefinitionKind()) {
9213     case FunctionDefinitionKind::Declaration:
9214     case FunctionDefinitionKind::Definition:
9215       break;
9216 
9217     case FunctionDefinitionKind::Defaulted:
9218       NewFD->setDefaulted();
9219       break;
9220 
9221     case FunctionDefinitionKind::Deleted:
9222       NewFD->setDeletedAsWritten();
9223       break;
9224     }
9225 
9226     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9227         D.isFunctionDefinition()) {
9228       // C++ [class.mfct]p2:
9229       //   A member function may be defined (8.4) in its class definition, in
9230       //   which case it is an inline member function (7.1.2)
9231       NewFD->setImplicitlyInline();
9232     }
9233 
9234     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9235         !CurContext->isRecord()) {
9236       // C++ [class.static]p1:
9237       //   A data or function member of a class may be declared static
9238       //   in a class definition, in which case it is a static member of
9239       //   the class.
9240 
9241       // Complain about the 'static' specifier if it's on an out-of-line
9242       // member function definition.
9243 
9244       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9245       // member function template declaration and class member template
9246       // declaration (MSVC versions before 2015), warn about this.
9247       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9248            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9249              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9250            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9251            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9252         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9253     }
9254 
9255     // C++11 [except.spec]p15:
9256     //   A deallocation function with no exception-specification is treated
9257     //   as if it were specified with noexcept(true).
9258     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9259     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9260          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9261         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9262       NewFD->setType(Context.getFunctionType(
9263           FPT->getReturnType(), FPT->getParamTypes(),
9264           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9265   }
9266 
9267   // Filter out previous declarations that don't match the scope.
9268   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9269                        D.getCXXScopeSpec().isNotEmpty() ||
9270                        isMemberSpecialization ||
9271                        isFunctionTemplateSpecialization);
9272 
9273   // Handle GNU asm-label extension (encoded as an attribute).
9274   if (Expr *E = (Expr*) D.getAsmLabel()) {
9275     // The parser guarantees this is a string.
9276     StringLiteral *SE = cast<StringLiteral>(E);
9277     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9278                                         /*IsLiteralLabel=*/true,
9279                                         SE->getStrTokenLoc(0)));
9280   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9281     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9282       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9283     if (I != ExtnameUndeclaredIdentifiers.end()) {
9284       if (isDeclExternC(NewFD)) {
9285         NewFD->addAttr(I->second);
9286         ExtnameUndeclaredIdentifiers.erase(I);
9287       } else
9288         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9289             << /*Variable*/0 << NewFD;
9290     }
9291   }
9292 
9293   // Copy the parameter declarations from the declarator D to the function
9294   // declaration NewFD, if they are available.  First scavenge them into Params.
9295   SmallVector<ParmVarDecl*, 16> Params;
9296   unsigned FTIIdx;
9297   if (D.isFunctionDeclarator(FTIIdx)) {
9298     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9299 
9300     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9301     // function that takes no arguments, not a function that takes a
9302     // single void argument.
9303     // We let through "const void" here because Sema::GetTypeForDeclarator
9304     // already checks for that case.
9305     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9306       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9307         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9308         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9309         Param->setDeclContext(NewFD);
9310         Params.push_back(Param);
9311 
9312         if (Param->isInvalidDecl())
9313           NewFD->setInvalidDecl();
9314       }
9315     }
9316 
9317     if (!getLangOpts().CPlusPlus) {
9318       // In C, find all the tag declarations from the prototype and move them
9319       // into the function DeclContext. Remove them from the surrounding tag
9320       // injection context of the function, which is typically but not always
9321       // the TU.
9322       DeclContext *PrototypeTagContext =
9323           getTagInjectionContext(NewFD->getLexicalDeclContext());
9324       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9325         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9326 
9327         // We don't want to reparent enumerators. Look at their parent enum
9328         // instead.
9329         if (!TD) {
9330           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9331             TD = cast<EnumDecl>(ECD->getDeclContext());
9332         }
9333         if (!TD)
9334           continue;
9335         DeclContext *TagDC = TD->getLexicalDeclContext();
9336         if (!TagDC->containsDecl(TD))
9337           continue;
9338         TagDC->removeDecl(TD);
9339         TD->setDeclContext(NewFD);
9340         NewFD->addDecl(TD);
9341 
9342         // Preserve the lexical DeclContext if it is not the surrounding tag
9343         // injection context of the FD. In this example, the semantic context of
9344         // E will be f and the lexical context will be S, while both the
9345         // semantic and lexical contexts of S will be f:
9346         //   void f(struct S { enum E { a } f; } s);
9347         if (TagDC != PrototypeTagContext)
9348           TD->setLexicalDeclContext(TagDC);
9349       }
9350     }
9351   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9352     // When we're declaring a function with a typedef, typeof, etc as in the
9353     // following example, we'll need to synthesize (unnamed)
9354     // parameters for use in the declaration.
9355     //
9356     // @code
9357     // typedef void fn(int);
9358     // fn f;
9359     // @endcode
9360 
9361     // Synthesize a parameter for each argument type.
9362     for (const auto &AI : FT->param_types()) {
9363       ParmVarDecl *Param =
9364           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9365       Param->setScopeInfo(0, Params.size());
9366       Params.push_back(Param);
9367     }
9368   } else {
9369     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9370            "Should not need args for typedef of non-prototype fn");
9371   }
9372 
9373   // Finally, we know we have the right number of parameters, install them.
9374   NewFD->setParams(Params);
9375 
9376   if (D.getDeclSpec().isNoreturnSpecified())
9377     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9378                                            D.getDeclSpec().getNoreturnSpecLoc(),
9379                                            AttributeCommonInfo::AS_Keyword));
9380 
9381   // Functions returning a variably modified type violate C99 6.7.5.2p2
9382   // because all functions have linkage.
9383   if (!NewFD->isInvalidDecl() &&
9384       NewFD->getReturnType()->isVariablyModifiedType()) {
9385     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9386     NewFD->setInvalidDecl();
9387   }
9388 
9389   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9390   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9391       !NewFD->hasAttr<SectionAttr>())
9392     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9393         Context, PragmaClangTextSection.SectionName,
9394         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9395 
9396   // Apply an implicit SectionAttr if #pragma code_seg is active.
9397   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9398       !NewFD->hasAttr<SectionAttr>()) {
9399     NewFD->addAttr(SectionAttr::CreateImplicit(
9400         Context, CodeSegStack.CurrentValue->getString(),
9401         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9402         SectionAttr::Declspec_allocate));
9403     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9404                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9405                          ASTContext::PSF_Read,
9406                      NewFD))
9407       NewFD->dropAttr<SectionAttr>();
9408   }
9409 
9410   // Apply an implicit CodeSegAttr from class declspec or
9411   // apply an implicit SectionAttr from #pragma code_seg if active.
9412   if (!NewFD->hasAttr<CodeSegAttr>()) {
9413     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9414                                                                  D.isFunctionDefinition())) {
9415       NewFD->addAttr(SAttr);
9416     }
9417   }
9418 
9419   // Handle attributes.
9420   ProcessDeclAttributes(S, NewFD, D);
9421 
9422   if (getLangOpts().OpenCL) {
9423     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9424     // type declaration will generate a compilation error.
9425     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9426     if (AddressSpace != LangAS::Default) {
9427       Diag(NewFD->getLocation(),
9428            diag::err_opencl_return_value_with_address_space);
9429       NewFD->setInvalidDecl();
9430     }
9431   }
9432 
9433   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9434     checkDeviceDecl(NewFD, D.getBeginLoc());
9435 
9436   if (!getLangOpts().CPlusPlus) {
9437     // Perform semantic checking on the function declaration.
9438     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9439       CheckMain(NewFD, D.getDeclSpec());
9440 
9441     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9442       CheckMSVCRTEntryPoint(NewFD);
9443 
9444     if (!NewFD->isInvalidDecl())
9445       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9446                                                   isMemberSpecialization));
9447     else if (!Previous.empty())
9448       // Recover gracefully from an invalid redeclaration.
9449       D.setRedeclaration(true);
9450     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9451             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9452            "previous declaration set still overloaded");
9453 
9454     // Diagnose no-prototype function declarations with calling conventions that
9455     // don't support variadic calls. Only do this in C and do it after merging
9456     // possibly prototyped redeclarations.
9457     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9458     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9459       CallingConv CC = FT->getExtInfo().getCC();
9460       if (!supportsVariadicCall(CC)) {
9461         // Windows system headers sometimes accidentally use stdcall without
9462         // (void) parameters, so we relax this to a warning.
9463         int DiagID =
9464             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9465         Diag(NewFD->getLocation(), DiagID)
9466             << FunctionType::getNameForCallConv(CC);
9467       }
9468     }
9469 
9470    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9471        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9472      checkNonTrivialCUnion(NewFD->getReturnType(),
9473                            NewFD->getReturnTypeSourceRange().getBegin(),
9474                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9475   } else {
9476     // C++11 [replacement.functions]p3:
9477     //  The program's definitions shall not be specified as inline.
9478     //
9479     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9480     //
9481     // Suppress the diagnostic if the function is __attribute__((used)), since
9482     // that forces an external definition to be emitted.
9483     if (D.getDeclSpec().isInlineSpecified() &&
9484         NewFD->isReplaceableGlobalAllocationFunction() &&
9485         !NewFD->hasAttr<UsedAttr>())
9486       Diag(D.getDeclSpec().getInlineSpecLoc(),
9487            diag::ext_operator_new_delete_declared_inline)
9488         << NewFD->getDeclName();
9489 
9490     // If the declarator is a template-id, translate the parser's template
9491     // argument list into our AST format.
9492     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9493       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9494       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9495       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9496       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9497                                          TemplateId->NumArgs);
9498       translateTemplateArguments(TemplateArgsPtr,
9499                                  TemplateArgs);
9500 
9501       HasExplicitTemplateArgs = true;
9502 
9503       if (NewFD->isInvalidDecl()) {
9504         HasExplicitTemplateArgs = false;
9505       } else if (FunctionTemplate) {
9506         // Function template with explicit template arguments.
9507         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9508           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9509 
9510         HasExplicitTemplateArgs = false;
9511       } else {
9512         assert((isFunctionTemplateSpecialization ||
9513                 D.getDeclSpec().isFriendSpecified()) &&
9514                "should have a 'template<>' for this decl");
9515         // "friend void foo<>(int);" is an implicit specialization decl.
9516         isFunctionTemplateSpecialization = true;
9517       }
9518     } else if (isFriend && isFunctionTemplateSpecialization) {
9519       // This combination is only possible in a recovery case;  the user
9520       // wrote something like:
9521       //   template <> friend void foo(int);
9522       // which we're recovering from as if the user had written:
9523       //   friend void foo<>(int);
9524       // Go ahead and fake up a template id.
9525       HasExplicitTemplateArgs = true;
9526       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9527       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9528     }
9529 
9530     // We do not add HD attributes to specializations here because
9531     // they may have different constexpr-ness compared to their
9532     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9533     // may end up with different effective targets. Instead, a
9534     // specialization inherits its target attributes from its template
9535     // in the CheckFunctionTemplateSpecialization() call below.
9536     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9537       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9538 
9539     // If it's a friend (and only if it's a friend), it's possible
9540     // that either the specialized function type or the specialized
9541     // template is dependent, and therefore matching will fail.  In
9542     // this case, don't check the specialization yet.
9543     if (isFunctionTemplateSpecialization && isFriend &&
9544         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9545          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9546              TemplateArgs.arguments()))) {
9547       assert(HasExplicitTemplateArgs &&
9548              "friend function specialization without template args");
9549       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9550                                                        Previous))
9551         NewFD->setInvalidDecl();
9552     } else if (isFunctionTemplateSpecialization) {
9553       if (CurContext->isDependentContext() && CurContext->isRecord()
9554           && !isFriend) {
9555         isDependentClassScopeExplicitSpecialization = true;
9556       } else if (!NewFD->isInvalidDecl() &&
9557                  CheckFunctionTemplateSpecialization(
9558                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9559                      Previous))
9560         NewFD->setInvalidDecl();
9561 
9562       // C++ [dcl.stc]p1:
9563       //   A storage-class-specifier shall not be specified in an explicit
9564       //   specialization (14.7.3)
9565       FunctionTemplateSpecializationInfo *Info =
9566           NewFD->getTemplateSpecializationInfo();
9567       if (Info && SC != SC_None) {
9568         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9569           Diag(NewFD->getLocation(),
9570                diag::err_explicit_specialization_inconsistent_storage_class)
9571             << SC
9572             << FixItHint::CreateRemoval(
9573                                       D.getDeclSpec().getStorageClassSpecLoc());
9574 
9575         else
9576           Diag(NewFD->getLocation(),
9577                diag::ext_explicit_specialization_storage_class)
9578             << FixItHint::CreateRemoval(
9579                                       D.getDeclSpec().getStorageClassSpecLoc());
9580       }
9581     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9582       if (CheckMemberSpecialization(NewFD, Previous))
9583           NewFD->setInvalidDecl();
9584     }
9585 
9586     // Perform semantic checking on the function declaration.
9587     if (!isDependentClassScopeExplicitSpecialization) {
9588       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9589         CheckMain(NewFD, D.getDeclSpec());
9590 
9591       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9592         CheckMSVCRTEntryPoint(NewFD);
9593 
9594       if (!NewFD->isInvalidDecl())
9595         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9596                                                     isMemberSpecialization));
9597       else if (!Previous.empty())
9598         // Recover gracefully from an invalid redeclaration.
9599         D.setRedeclaration(true);
9600     }
9601 
9602     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9603             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9604            "previous declaration set still overloaded");
9605 
9606     NamedDecl *PrincipalDecl = (FunctionTemplate
9607                                 ? cast<NamedDecl>(FunctionTemplate)
9608                                 : NewFD);
9609 
9610     if (isFriend && NewFD->getPreviousDecl()) {
9611       AccessSpecifier Access = AS_public;
9612       if (!NewFD->isInvalidDecl())
9613         Access = NewFD->getPreviousDecl()->getAccess();
9614 
9615       NewFD->setAccess(Access);
9616       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9617     }
9618 
9619     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9620         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9621       PrincipalDecl->setNonMemberOperator();
9622 
9623     // If we have a function template, check the template parameter
9624     // list. This will check and merge default template arguments.
9625     if (FunctionTemplate) {
9626       FunctionTemplateDecl *PrevTemplate =
9627                                      FunctionTemplate->getPreviousDecl();
9628       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9629                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9630                                     : nullptr,
9631                             D.getDeclSpec().isFriendSpecified()
9632                               ? (D.isFunctionDefinition()
9633                                    ? TPC_FriendFunctionTemplateDefinition
9634                                    : TPC_FriendFunctionTemplate)
9635                               : (D.getCXXScopeSpec().isSet() &&
9636                                  DC && DC->isRecord() &&
9637                                  DC->isDependentContext())
9638                                   ? TPC_ClassTemplateMember
9639                                   : TPC_FunctionTemplate);
9640     }
9641 
9642     if (NewFD->isInvalidDecl()) {
9643       // Ignore all the rest of this.
9644     } else if (!D.isRedeclaration()) {
9645       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9646                                        AddToScope };
9647       // Fake up an access specifier if it's supposed to be a class member.
9648       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9649         NewFD->setAccess(AS_public);
9650 
9651       // Qualified decls generally require a previous declaration.
9652       if (D.getCXXScopeSpec().isSet()) {
9653         // ...with the major exception of templated-scope or
9654         // dependent-scope friend declarations.
9655 
9656         // TODO: we currently also suppress this check in dependent
9657         // contexts because (1) the parameter depth will be off when
9658         // matching friend templates and (2) we might actually be
9659         // selecting a friend based on a dependent factor.  But there
9660         // are situations where these conditions don't apply and we
9661         // can actually do this check immediately.
9662         //
9663         // Unless the scope is dependent, it's always an error if qualified
9664         // redeclaration lookup found nothing at all. Diagnose that now;
9665         // nothing will diagnose that error later.
9666         if (isFriend &&
9667             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9668              (!Previous.empty() && CurContext->isDependentContext()))) {
9669           // ignore these
9670         } else {
9671           // The user tried to provide an out-of-line definition for a
9672           // function that is a member of a class or namespace, but there
9673           // was no such member function declared (C++ [class.mfct]p2,
9674           // C++ [namespace.memdef]p2). For example:
9675           //
9676           // class X {
9677           //   void f() const;
9678           // };
9679           //
9680           // void X::f() { } // ill-formed
9681           //
9682           // Complain about this problem, and attempt to suggest close
9683           // matches (e.g., those that differ only in cv-qualifiers and
9684           // whether the parameter types are references).
9685 
9686           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9687                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9688             AddToScope = ExtraArgs.AddToScope;
9689             return Result;
9690           }
9691         }
9692 
9693         // Unqualified local friend declarations are required to resolve
9694         // to something.
9695       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9696         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9697                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9698           AddToScope = ExtraArgs.AddToScope;
9699           return Result;
9700         }
9701       }
9702     } else if (!D.isFunctionDefinition() &&
9703                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9704                !isFriend && !isFunctionTemplateSpecialization &&
9705                !isMemberSpecialization) {
9706       // An out-of-line member function declaration must also be a
9707       // definition (C++ [class.mfct]p2).
9708       // Note that this is not the case for explicit specializations of
9709       // function templates or member functions of class templates, per
9710       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9711       // extension for compatibility with old SWIG code which likes to
9712       // generate them.
9713       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9714         << D.getCXXScopeSpec().getRange();
9715     }
9716   }
9717 
9718   // If this is the first declaration of a library builtin function, add
9719   // attributes as appropriate.
9720   if (!D.isRedeclaration() &&
9721       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9722     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9723       if (unsigned BuiltinID = II->getBuiltinID()) {
9724         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9725           // Validate the type matches unless this builtin is specified as
9726           // matching regardless of its declared type.
9727           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9728             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9729           } else {
9730             ASTContext::GetBuiltinTypeError Error;
9731             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9732             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9733 
9734             if (!Error && !BuiltinType.isNull() &&
9735                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9736                     NewFD->getType(), BuiltinType))
9737               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9738           }
9739         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9740                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9741           // FIXME: We should consider this a builtin only in the std namespace.
9742           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9743         }
9744       }
9745     }
9746   }
9747 
9748   ProcessPragmaWeak(S, NewFD);
9749   checkAttributesAfterMerging(*this, *NewFD);
9750 
9751   AddKnownFunctionAttributes(NewFD);
9752 
9753   if (NewFD->hasAttr<OverloadableAttr>() &&
9754       !NewFD->getType()->getAs<FunctionProtoType>()) {
9755     Diag(NewFD->getLocation(),
9756          diag::err_attribute_overloadable_no_prototype)
9757       << NewFD;
9758 
9759     // Turn this into a variadic function with no parameters.
9760     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9761     FunctionProtoType::ExtProtoInfo EPI(
9762         Context.getDefaultCallingConvention(true, false));
9763     EPI.Variadic = true;
9764     EPI.ExtInfo = FT->getExtInfo();
9765 
9766     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9767     NewFD->setType(R);
9768   }
9769 
9770   // If there's a #pragma GCC visibility in scope, and this isn't a class
9771   // member, set the visibility of this function.
9772   if (!DC->isRecord() && NewFD->isExternallyVisible())
9773     AddPushedVisibilityAttribute(NewFD);
9774 
9775   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9776   // marking the function.
9777   AddCFAuditedAttribute(NewFD);
9778 
9779   // If this is a function definition, check if we have to apply optnone due to
9780   // a pragma.
9781   if(D.isFunctionDefinition())
9782     AddRangeBasedOptnone(NewFD);
9783 
9784   // If this is the first declaration of an extern C variable, update
9785   // the map of such variables.
9786   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9787       isIncompleteDeclExternC(*this, NewFD))
9788     RegisterLocallyScopedExternCDecl(NewFD, S);
9789 
9790   // Set this FunctionDecl's range up to the right paren.
9791   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9792 
9793   if (D.isRedeclaration() && !Previous.empty()) {
9794     NamedDecl *Prev = Previous.getRepresentativeDecl();
9795     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9796                                    isMemberSpecialization ||
9797                                        isFunctionTemplateSpecialization,
9798                                    D.isFunctionDefinition());
9799   }
9800 
9801   if (getLangOpts().CUDA) {
9802     IdentifierInfo *II = NewFD->getIdentifier();
9803     if (II && II->isStr(getCudaConfigureFuncName()) &&
9804         !NewFD->isInvalidDecl() &&
9805         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9806       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9807         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9808             << getCudaConfigureFuncName();
9809       Context.setcudaConfigureCallDecl(NewFD);
9810     }
9811 
9812     // Variadic functions, other than a *declaration* of printf, are not allowed
9813     // in device-side CUDA code, unless someone passed
9814     // -fcuda-allow-variadic-functions.
9815     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9816         (NewFD->hasAttr<CUDADeviceAttr>() ||
9817          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9818         !(II && II->isStr("printf") && NewFD->isExternC() &&
9819           !D.isFunctionDefinition())) {
9820       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9821     }
9822   }
9823 
9824   MarkUnusedFileScopedDecl(NewFD);
9825 
9826 
9827 
9828   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9829     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9830     if ((getLangOpts().OpenCLVersion >= 120)
9831         && (SC == SC_Static)) {
9832       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9833       D.setInvalidType();
9834     }
9835 
9836     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9837     if (!NewFD->getReturnType()->isVoidType()) {
9838       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9839       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9840           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9841                                 : FixItHint());
9842       D.setInvalidType();
9843     }
9844 
9845     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9846     for (auto Param : NewFD->parameters())
9847       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9848 
9849     if (getLangOpts().OpenCLCPlusPlus) {
9850       if (DC->isRecord()) {
9851         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9852         D.setInvalidType();
9853       }
9854       if (FunctionTemplate) {
9855         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9856         D.setInvalidType();
9857       }
9858     }
9859   }
9860 
9861   if (getLangOpts().CPlusPlus) {
9862     if (FunctionTemplate) {
9863       if (NewFD->isInvalidDecl())
9864         FunctionTemplate->setInvalidDecl();
9865       return FunctionTemplate;
9866     }
9867 
9868     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9869       CompleteMemberSpecialization(NewFD, Previous);
9870   }
9871 
9872   for (const ParmVarDecl *Param : NewFD->parameters()) {
9873     QualType PT = Param->getType();
9874 
9875     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9876     // types.
9877     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9878       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9879         QualType ElemTy = PipeTy->getElementType();
9880           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9881             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9882             D.setInvalidType();
9883           }
9884       }
9885     }
9886   }
9887 
9888   // Here we have an function template explicit specialization at class scope.
9889   // The actual specialization will be postponed to template instatiation
9890   // time via the ClassScopeFunctionSpecializationDecl node.
9891   if (isDependentClassScopeExplicitSpecialization) {
9892     ClassScopeFunctionSpecializationDecl *NewSpec =
9893                          ClassScopeFunctionSpecializationDecl::Create(
9894                                 Context, CurContext, NewFD->getLocation(),
9895                                 cast<CXXMethodDecl>(NewFD),
9896                                 HasExplicitTemplateArgs, TemplateArgs);
9897     CurContext->addDecl(NewSpec);
9898     AddToScope = false;
9899   }
9900 
9901   // Diagnose availability attributes. Availability cannot be used on functions
9902   // that are run during load/unload.
9903   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9904     if (NewFD->hasAttr<ConstructorAttr>()) {
9905       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9906           << 1;
9907       NewFD->dropAttr<AvailabilityAttr>();
9908     }
9909     if (NewFD->hasAttr<DestructorAttr>()) {
9910       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9911           << 2;
9912       NewFD->dropAttr<AvailabilityAttr>();
9913     }
9914   }
9915 
9916   // Diagnose no_builtin attribute on function declaration that are not a
9917   // definition.
9918   // FIXME: We should really be doing this in
9919   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9920   // the FunctionDecl and at this point of the code
9921   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9922   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9923   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9924     switch (D.getFunctionDefinitionKind()) {
9925     case FunctionDefinitionKind::Defaulted:
9926     case FunctionDefinitionKind::Deleted:
9927       Diag(NBA->getLocation(),
9928            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9929           << NBA->getSpelling();
9930       break;
9931     case FunctionDefinitionKind::Declaration:
9932       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9933           << NBA->getSpelling();
9934       break;
9935     case FunctionDefinitionKind::Definition:
9936       break;
9937     }
9938 
9939   return NewFD;
9940 }
9941 
9942 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9943 /// when __declspec(code_seg) "is applied to a class, all member functions of
9944 /// the class and nested classes -- this includes compiler-generated special
9945 /// member functions -- are put in the specified segment."
9946 /// The actual behavior is a little more complicated. The Microsoft compiler
9947 /// won't check outer classes if there is an active value from #pragma code_seg.
9948 /// The CodeSeg is always applied from the direct parent but only from outer
9949 /// classes when the #pragma code_seg stack is empty. See:
9950 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9951 /// available since MS has removed the page.
9952 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9953   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9954   if (!Method)
9955     return nullptr;
9956   const CXXRecordDecl *Parent = Method->getParent();
9957   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9958     Attr *NewAttr = SAttr->clone(S.getASTContext());
9959     NewAttr->setImplicit(true);
9960     return NewAttr;
9961   }
9962 
9963   // The Microsoft compiler won't check outer classes for the CodeSeg
9964   // when the #pragma code_seg stack is active.
9965   if (S.CodeSegStack.CurrentValue)
9966    return nullptr;
9967 
9968   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9969     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9970       Attr *NewAttr = SAttr->clone(S.getASTContext());
9971       NewAttr->setImplicit(true);
9972       return NewAttr;
9973     }
9974   }
9975   return nullptr;
9976 }
9977 
9978 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9979 /// containing class. Otherwise it will return implicit SectionAttr if the
9980 /// function is a definition and there is an active value on CodeSegStack
9981 /// (from the current #pragma code-seg value).
9982 ///
9983 /// \param FD Function being declared.
9984 /// \param IsDefinition Whether it is a definition or just a declarartion.
9985 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9986 ///          nullptr if no attribute should be added.
9987 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9988                                                        bool IsDefinition) {
9989   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9990     return A;
9991   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9992       CodeSegStack.CurrentValue)
9993     return SectionAttr::CreateImplicit(
9994         getASTContext(), CodeSegStack.CurrentValue->getString(),
9995         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9996         SectionAttr::Declspec_allocate);
9997   return nullptr;
9998 }
9999 
10000 /// Determines if we can perform a correct type check for \p D as a
10001 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10002 /// best-effort check.
10003 ///
10004 /// \param NewD The new declaration.
10005 /// \param OldD The old declaration.
10006 /// \param NewT The portion of the type of the new declaration to check.
10007 /// \param OldT The portion of the type of the old declaration to check.
10008 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10009                                           QualType NewT, QualType OldT) {
10010   if (!NewD->getLexicalDeclContext()->isDependentContext())
10011     return true;
10012 
10013   // For dependently-typed local extern declarations and friends, we can't
10014   // perform a correct type check in general until instantiation:
10015   //
10016   //   int f();
10017   //   template<typename T> void g() { T f(); }
10018   //
10019   // (valid if g() is only instantiated with T = int).
10020   if (NewT->isDependentType() &&
10021       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10022     return false;
10023 
10024   // Similarly, if the previous declaration was a dependent local extern
10025   // declaration, we don't really know its type yet.
10026   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10027     return false;
10028 
10029   return true;
10030 }
10031 
10032 /// Checks if the new declaration declared in dependent context must be
10033 /// put in the same redeclaration chain as the specified declaration.
10034 ///
10035 /// \param D Declaration that is checked.
10036 /// \param PrevDecl Previous declaration found with proper lookup method for the
10037 ///                 same declaration name.
10038 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10039 ///          belongs to.
10040 ///
10041 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10042   if (!D->getLexicalDeclContext()->isDependentContext())
10043     return true;
10044 
10045   // Don't chain dependent friend function definitions until instantiation, to
10046   // permit cases like
10047   //
10048   //   void func();
10049   //   template<typename T> class C1 { friend void func() {} };
10050   //   template<typename T> class C2 { friend void func() {} };
10051   //
10052   // ... which is valid if only one of C1 and C2 is ever instantiated.
10053   //
10054   // FIXME: This need only apply to function definitions. For now, we proxy
10055   // this by checking for a file-scope function. We do not want this to apply
10056   // to friend declarations nominating member functions, because that gets in
10057   // the way of access checks.
10058   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10059     return false;
10060 
10061   auto *VD = dyn_cast<ValueDecl>(D);
10062   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10063   return !VD || !PrevVD ||
10064          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10065                                         PrevVD->getType());
10066 }
10067 
10068 /// Check the target attribute of the function for MultiVersion
10069 /// validity.
10070 ///
10071 /// Returns true if there was an error, false otherwise.
10072 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10073   const auto *TA = FD->getAttr<TargetAttr>();
10074   assert(TA && "MultiVersion Candidate requires a target attribute");
10075   ParsedTargetAttr ParseInfo = TA->parse();
10076   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10077   enum ErrType { Feature = 0, Architecture = 1 };
10078 
10079   if (!ParseInfo.Architecture.empty() &&
10080       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10081     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10082         << Architecture << ParseInfo.Architecture;
10083     return true;
10084   }
10085 
10086   for (const auto &Feat : ParseInfo.Features) {
10087     auto BareFeat = StringRef{Feat}.substr(1);
10088     if (Feat[0] == '-') {
10089       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10090           << Feature << ("no-" + BareFeat).str();
10091       return true;
10092     }
10093 
10094     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10095         !TargetInfo.isValidFeatureName(BareFeat)) {
10096       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10097           << Feature << BareFeat;
10098       return true;
10099     }
10100   }
10101   return false;
10102 }
10103 
10104 // Provide a white-list of attributes that are allowed to be combined with
10105 // multiversion functions.
10106 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10107                                            MultiVersionKind MVType) {
10108   // Note: this list/diagnosis must match the list in
10109   // checkMultiversionAttributesAllSame.
10110   switch (Kind) {
10111   default:
10112     return false;
10113   case attr::Used:
10114     return MVType == MultiVersionKind::Target;
10115   case attr::NonNull:
10116   case attr::NoThrow:
10117     return true;
10118   }
10119 }
10120 
10121 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10122                                                  const FunctionDecl *FD,
10123                                                  const FunctionDecl *CausedFD,
10124                                                  MultiVersionKind MVType) {
10125   bool IsCPUSpecificCPUDispatchMVType =
10126       MVType == MultiVersionKind::CPUDispatch ||
10127       MVType == MultiVersionKind::CPUSpecific;
10128   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10129                             Sema &S, const Attr *A) {
10130     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10131         << IsCPUSpecificCPUDispatchMVType << A;
10132     if (CausedFD)
10133       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10134     return true;
10135   };
10136 
10137   for (const Attr *A : FD->attrs()) {
10138     switch (A->getKind()) {
10139     case attr::CPUDispatch:
10140     case attr::CPUSpecific:
10141       if (MVType != MultiVersionKind::CPUDispatch &&
10142           MVType != MultiVersionKind::CPUSpecific)
10143         return Diagnose(S, A);
10144       break;
10145     case attr::Target:
10146       if (MVType != MultiVersionKind::Target)
10147         return Diagnose(S, A);
10148       break;
10149     default:
10150       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10151         return Diagnose(S, A);
10152       break;
10153     }
10154   }
10155   return false;
10156 }
10157 
10158 bool Sema::areMultiversionVariantFunctionsCompatible(
10159     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10160     const PartialDiagnostic &NoProtoDiagID,
10161     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10162     const PartialDiagnosticAt &NoSupportDiagIDAt,
10163     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10164     bool ConstexprSupported, bool CLinkageMayDiffer) {
10165   enum DoesntSupport {
10166     FuncTemplates = 0,
10167     VirtFuncs = 1,
10168     DeducedReturn = 2,
10169     Constructors = 3,
10170     Destructors = 4,
10171     DeletedFuncs = 5,
10172     DefaultedFuncs = 6,
10173     ConstexprFuncs = 7,
10174     ConstevalFuncs = 8,
10175   };
10176   enum Different {
10177     CallingConv = 0,
10178     ReturnType = 1,
10179     ConstexprSpec = 2,
10180     InlineSpec = 3,
10181     StorageClass = 4,
10182     Linkage = 5,
10183   };
10184 
10185   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10186       !OldFD->getType()->getAs<FunctionProtoType>()) {
10187     Diag(OldFD->getLocation(), NoProtoDiagID);
10188     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10189     return true;
10190   }
10191 
10192   if (NoProtoDiagID.getDiagID() != 0 &&
10193       !NewFD->getType()->getAs<FunctionProtoType>())
10194     return Diag(NewFD->getLocation(), NoProtoDiagID);
10195 
10196   if (!TemplatesSupported &&
10197       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10198     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10199            << FuncTemplates;
10200 
10201   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10202     if (NewCXXFD->isVirtual())
10203       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10204              << VirtFuncs;
10205 
10206     if (isa<CXXConstructorDecl>(NewCXXFD))
10207       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10208              << Constructors;
10209 
10210     if (isa<CXXDestructorDecl>(NewCXXFD))
10211       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10212              << Destructors;
10213   }
10214 
10215   if (NewFD->isDeleted())
10216     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10217            << DeletedFuncs;
10218 
10219   if (NewFD->isDefaulted())
10220     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10221            << DefaultedFuncs;
10222 
10223   if (!ConstexprSupported && NewFD->isConstexpr())
10224     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10225            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10226 
10227   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10228   const auto *NewType = cast<FunctionType>(NewQType);
10229   QualType NewReturnType = NewType->getReturnType();
10230 
10231   if (NewReturnType->isUndeducedType())
10232     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10233            << DeducedReturn;
10234 
10235   // Ensure the return type is identical.
10236   if (OldFD) {
10237     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10238     const auto *OldType = cast<FunctionType>(OldQType);
10239     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10240     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10241 
10242     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10243       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10244 
10245     QualType OldReturnType = OldType->getReturnType();
10246 
10247     if (OldReturnType != NewReturnType)
10248       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10249 
10250     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10251       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10252 
10253     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10254       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10255 
10256     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10257       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10258 
10259     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10260       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10261 
10262     if (CheckEquivalentExceptionSpec(
10263             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10264             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10265       return true;
10266   }
10267   return false;
10268 }
10269 
10270 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10271                                              const FunctionDecl *NewFD,
10272                                              bool CausesMV,
10273                                              MultiVersionKind MVType) {
10274   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10275     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10276     if (OldFD)
10277       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10278     return true;
10279   }
10280 
10281   bool IsCPUSpecificCPUDispatchMVType =
10282       MVType == MultiVersionKind::CPUDispatch ||
10283       MVType == MultiVersionKind::CPUSpecific;
10284 
10285   if (CausesMV && OldFD &&
10286       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10287     return true;
10288 
10289   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10290     return true;
10291 
10292   // Only allow transition to MultiVersion if it hasn't been used.
10293   if (OldFD && CausesMV && OldFD->isUsed(false))
10294     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10295 
10296   return S.areMultiversionVariantFunctionsCompatible(
10297       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10298       PartialDiagnosticAt(NewFD->getLocation(),
10299                           S.PDiag(diag::note_multiversioning_caused_here)),
10300       PartialDiagnosticAt(NewFD->getLocation(),
10301                           S.PDiag(diag::err_multiversion_doesnt_support)
10302                               << IsCPUSpecificCPUDispatchMVType),
10303       PartialDiagnosticAt(NewFD->getLocation(),
10304                           S.PDiag(diag::err_multiversion_diff)),
10305       /*TemplatesSupported=*/false,
10306       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10307       /*CLinkageMayDiffer=*/false);
10308 }
10309 
10310 /// Check the validity of a multiversion function declaration that is the
10311 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10312 ///
10313 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10314 ///
10315 /// Returns true if there was an error, false otherwise.
10316 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10317                                            MultiVersionKind MVType,
10318                                            const TargetAttr *TA) {
10319   assert(MVType != MultiVersionKind::None &&
10320          "Function lacks multiversion attribute");
10321 
10322   // Target only causes MV if it is default, otherwise this is a normal
10323   // function.
10324   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10325     return false;
10326 
10327   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10328     FD->setInvalidDecl();
10329     return true;
10330   }
10331 
10332   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10333     FD->setInvalidDecl();
10334     return true;
10335   }
10336 
10337   FD->setIsMultiVersion();
10338   return false;
10339 }
10340 
10341 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10342   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10343     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10344       return true;
10345   }
10346 
10347   return false;
10348 }
10349 
10350 static bool CheckTargetCausesMultiVersioning(
10351     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10352     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10353     LookupResult &Previous) {
10354   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10355   ParsedTargetAttr NewParsed = NewTA->parse();
10356   // Sort order doesn't matter, it just needs to be consistent.
10357   llvm::sort(NewParsed.Features);
10358 
10359   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10360   // to change, this is a simple redeclaration.
10361   if (!NewTA->isDefaultVersion() &&
10362       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10363     return false;
10364 
10365   // Otherwise, this decl causes MultiVersioning.
10366   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10367     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10368     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10369     NewFD->setInvalidDecl();
10370     return true;
10371   }
10372 
10373   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10374                                        MultiVersionKind::Target)) {
10375     NewFD->setInvalidDecl();
10376     return true;
10377   }
10378 
10379   if (CheckMultiVersionValue(S, NewFD)) {
10380     NewFD->setInvalidDecl();
10381     return true;
10382   }
10383 
10384   // If this is 'default', permit the forward declaration.
10385   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10386     Redeclaration = true;
10387     OldDecl = OldFD;
10388     OldFD->setIsMultiVersion();
10389     NewFD->setIsMultiVersion();
10390     return false;
10391   }
10392 
10393   if (CheckMultiVersionValue(S, OldFD)) {
10394     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10395     NewFD->setInvalidDecl();
10396     return true;
10397   }
10398 
10399   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10400 
10401   if (OldParsed == NewParsed) {
10402     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10403     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10404     NewFD->setInvalidDecl();
10405     return true;
10406   }
10407 
10408   for (const auto *FD : OldFD->redecls()) {
10409     const auto *CurTA = FD->getAttr<TargetAttr>();
10410     // We allow forward declarations before ANY multiversioning attributes, but
10411     // nothing after the fact.
10412     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10413         (!CurTA || CurTA->isInherited())) {
10414       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10415           << 0;
10416       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10417       NewFD->setInvalidDecl();
10418       return true;
10419     }
10420   }
10421 
10422   OldFD->setIsMultiVersion();
10423   NewFD->setIsMultiVersion();
10424   Redeclaration = false;
10425   MergeTypeWithPrevious = false;
10426   OldDecl = nullptr;
10427   Previous.clear();
10428   return false;
10429 }
10430 
10431 /// Check the validity of a new function declaration being added to an existing
10432 /// multiversioned declaration collection.
10433 static bool CheckMultiVersionAdditionalDecl(
10434     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10435     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10436     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10437     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10438     LookupResult &Previous) {
10439 
10440   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10441   // Disallow mixing of multiversioning types.
10442   if ((OldMVType == MultiVersionKind::Target &&
10443        NewMVType != MultiVersionKind::Target) ||
10444       (NewMVType == MultiVersionKind::Target &&
10445        OldMVType != MultiVersionKind::Target)) {
10446     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10447     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10448     NewFD->setInvalidDecl();
10449     return true;
10450   }
10451 
10452   ParsedTargetAttr NewParsed;
10453   if (NewTA) {
10454     NewParsed = NewTA->parse();
10455     llvm::sort(NewParsed.Features);
10456   }
10457 
10458   bool UseMemberUsingDeclRules =
10459       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10460 
10461   // Next, check ALL non-overloads to see if this is a redeclaration of a
10462   // previous member of the MultiVersion set.
10463   for (NamedDecl *ND : Previous) {
10464     FunctionDecl *CurFD = ND->getAsFunction();
10465     if (!CurFD)
10466       continue;
10467     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10468       continue;
10469 
10470     if (NewMVType == MultiVersionKind::Target) {
10471       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10472       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10473         NewFD->setIsMultiVersion();
10474         Redeclaration = true;
10475         OldDecl = ND;
10476         return false;
10477       }
10478 
10479       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10480       if (CurParsed == NewParsed) {
10481         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10482         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10483         NewFD->setInvalidDecl();
10484         return true;
10485       }
10486     } else {
10487       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10488       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10489       // Handle CPUDispatch/CPUSpecific versions.
10490       // Only 1 CPUDispatch function is allowed, this will make it go through
10491       // the redeclaration errors.
10492       if (NewMVType == MultiVersionKind::CPUDispatch &&
10493           CurFD->hasAttr<CPUDispatchAttr>()) {
10494         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10495             std::equal(
10496                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10497                 NewCPUDisp->cpus_begin(),
10498                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10499                   return Cur->getName() == New->getName();
10500                 })) {
10501           NewFD->setIsMultiVersion();
10502           Redeclaration = true;
10503           OldDecl = ND;
10504           return false;
10505         }
10506 
10507         // If the declarations don't match, this is an error condition.
10508         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10509         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10510         NewFD->setInvalidDecl();
10511         return true;
10512       }
10513       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10514 
10515         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10516             std::equal(
10517                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10518                 NewCPUSpec->cpus_begin(),
10519                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10520                   return Cur->getName() == New->getName();
10521                 })) {
10522           NewFD->setIsMultiVersion();
10523           Redeclaration = true;
10524           OldDecl = ND;
10525           return false;
10526         }
10527 
10528         // Only 1 version of CPUSpecific is allowed for each CPU.
10529         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10530           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10531             if (CurII == NewII) {
10532               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10533                   << NewII;
10534               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10535               NewFD->setInvalidDecl();
10536               return true;
10537             }
10538           }
10539         }
10540       }
10541       // If the two decls aren't the same MVType, there is no possible error
10542       // condition.
10543     }
10544   }
10545 
10546   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10547   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10548   // handled in the attribute adding step.
10549   if (NewMVType == MultiVersionKind::Target &&
10550       CheckMultiVersionValue(S, NewFD)) {
10551     NewFD->setInvalidDecl();
10552     return true;
10553   }
10554 
10555   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10556                                        !OldFD->isMultiVersion(), NewMVType)) {
10557     NewFD->setInvalidDecl();
10558     return true;
10559   }
10560 
10561   // Permit forward declarations in the case where these two are compatible.
10562   if (!OldFD->isMultiVersion()) {
10563     OldFD->setIsMultiVersion();
10564     NewFD->setIsMultiVersion();
10565     Redeclaration = true;
10566     OldDecl = OldFD;
10567     return false;
10568   }
10569 
10570   NewFD->setIsMultiVersion();
10571   Redeclaration = false;
10572   MergeTypeWithPrevious = false;
10573   OldDecl = nullptr;
10574   Previous.clear();
10575   return false;
10576 }
10577 
10578 
10579 /// Check the validity of a mulitversion function declaration.
10580 /// Also sets the multiversion'ness' of the function itself.
10581 ///
10582 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10583 ///
10584 /// Returns true if there was an error, false otherwise.
10585 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10586                                       bool &Redeclaration, NamedDecl *&OldDecl,
10587                                       bool &MergeTypeWithPrevious,
10588                                       LookupResult &Previous) {
10589   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10590   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10591   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10592 
10593   // Mixing Multiversioning types is prohibited.
10594   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10595       (NewCPUDisp && NewCPUSpec)) {
10596     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10597     NewFD->setInvalidDecl();
10598     return true;
10599   }
10600 
10601   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10602 
10603   // Main isn't allowed to become a multiversion function, however it IS
10604   // permitted to have 'main' be marked with the 'target' optimization hint.
10605   if (NewFD->isMain()) {
10606     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10607         MVType == MultiVersionKind::CPUDispatch ||
10608         MVType == MultiVersionKind::CPUSpecific) {
10609       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10610       NewFD->setInvalidDecl();
10611       return true;
10612     }
10613     return false;
10614   }
10615 
10616   if (!OldDecl || !OldDecl->getAsFunction() ||
10617       OldDecl->getDeclContext()->getRedeclContext() !=
10618           NewFD->getDeclContext()->getRedeclContext()) {
10619     // If there's no previous declaration, AND this isn't attempting to cause
10620     // multiversioning, this isn't an error condition.
10621     if (MVType == MultiVersionKind::None)
10622       return false;
10623     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10624   }
10625 
10626   FunctionDecl *OldFD = OldDecl->getAsFunction();
10627 
10628   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10629     return false;
10630 
10631   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10632     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10633         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10634     NewFD->setInvalidDecl();
10635     return true;
10636   }
10637 
10638   // Handle the target potentially causes multiversioning case.
10639   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10640     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10641                                             Redeclaration, OldDecl,
10642                                             MergeTypeWithPrevious, Previous);
10643 
10644   // At this point, we have a multiversion function decl (in OldFD) AND an
10645   // appropriate attribute in the current function decl.  Resolve that these are
10646   // still compatible with previous declarations.
10647   return CheckMultiVersionAdditionalDecl(
10648       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10649       OldDecl, MergeTypeWithPrevious, Previous);
10650 }
10651 
10652 /// Perform semantic checking of a new function declaration.
10653 ///
10654 /// Performs semantic analysis of the new function declaration
10655 /// NewFD. This routine performs all semantic checking that does not
10656 /// require the actual declarator involved in the declaration, and is
10657 /// used both for the declaration of functions as they are parsed
10658 /// (called via ActOnDeclarator) and for the declaration of functions
10659 /// that have been instantiated via C++ template instantiation (called
10660 /// via InstantiateDecl).
10661 ///
10662 /// \param IsMemberSpecialization whether this new function declaration is
10663 /// a member specialization (that replaces any definition provided by the
10664 /// previous declaration).
10665 ///
10666 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10667 ///
10668 /// \returns true if the function declaration is a redeclaration.
10669 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10670                                     LookupResult &Previous,
10671                                     bool IsMemberSpecialization) {
10672   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10673          "Variably modified return types are not handled here");
10674 
10675   // Determine whether the type of this function should be merged with
10676   // a previous visible declaration. This never happens for functions in C++,
10677   // and always happens in C if the previous declaration was visible.
10678   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10679                                !Previous.isShadowed();
10680 
10681   bool Redeclaration = false;
10682   NamedDecl *OldDecl = nullptr;
10683   bool MayNeedOverloadableChecks = false;
10684 
10685   // Merge or overload the declaration with an existing declaration of
10686   // the same name, if appropriate.
10687   if (!Previous.empty()) {
10688     // Determine whether NewFD is an overload of PrevDecl or
10689     // a declaration that requires merging. If it's an overload,
10690     // there's no more work to do here; we'll just add the new
10691     // function to the scope.
10692     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10693       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10694       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10695         Redeclaration = true;
10696         OldDecl = Candidate;
10697       }
10698     } else {
10699       MayNeedOverloadableChecks = true;
10700       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10701                             /*NewIsUsingDecl*/ false)) {
10702       case Ovl_Match:
10703         Redeclaration = true;
10704         break;
10705 
10706       case Ovl_NonFunction:
10707         Redeclaration = true;
10708         break;
10709 
10710       case Ovl_Overload:
10711         Redeclaration = false;
10712         break;
10713       }
10714     }
10715   }
10716 
10717   // Check for a previous extern "C" declaration with this name.
10718   if (!Redeclaration &&
10719       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10720     if (!Previous.empty()) {
10721       // This is an extern "C" declaration with the same name as a previous
10722       // declaration, and thus redeclares that entity...
10723       Redeclaration = true;
10724       OldDecl = Previous.getFoundDecl();
10725       MergeTypeWithPrevious = false;
10726 
10727       // ... except in the presence of __attribute__((overloadable)).
10728       if (OldDecl->hasAttr<OverloadableAttr>() ||
10729           NewFD->hasAttr<OverloadableAttr>()) {
10730         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10731           MayNeedOverloadableChecks = true;
10732           Redeclaration = false;
10733           OldDecl = nullptr;
10734         }
10735       }
10736     }
10737   }
10738 
10739   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10740                                 MergeTypeWithPrevious, Previous))
10741     return Redeclaration;
10742 
10743   // PPC MMA non-pointer types are not allowed as function return types.
10744   if (Context.getTargetInfo().getTriple().isPPC64() &&
10745       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10746     NewFD->setInvalidDecl();
10747   }
10748 
10749   // C++11 [dcl.constexpr]p8:
10750   //   A constexpr specifier for a non-static member function that is not
10751   //   a constructor declares that member function to be const.
10752   //
10753   // This needs to be delayed until we know whether this is an out-of-line
10754   // definition of a static member function.
10755   //
10756   // This rule is not present in C++1y, so we produce a backwards
10757   // compatibility warning whenever it happens in C++11.
10758   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10759   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10760       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10761       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10762     CXXMethodDecl *OldMD = nullptr;
10763     if (OldDecl)
10764       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10765     if (!OldMD || !OldMD->isStatic()) {
10766       const FunctionProtoType *FPT =
10767         MD->getType()->castAs<FunctionProtoType>();
10768       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10769       EPI.TypeQuals.addConst();
10770       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10771                                           FPT->getParamTypes(), EPI));
10772 
10773       // Warn that we did this, if we're not performing template instantiation.
10774       // In that case, we'll have warned already when the template was defined.
10775       if (!inTemplateInstantiation()) {
10776         SourceLocation AddConstLoc;
10777         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10778                 .IgnoreParens().getAs<FunctionTypeLoc>())
10779           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10780 
10781         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10782           << FixItHint::CreateInsertion(AddConstLoc, " const");
10783       }
10784     }
10785   }
10786 
10787   if (Redeclaration) {
10788     // NewFD and OldDecl represent declarations that need to be
10789     // merged.
10790     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10791       NewFD->setInvalidDecl();
10792       return Redeclaration;
10793     }
10794 
10795     Previous.clear();
10796     Previous.addDecl(OldDecl);
10797 
10798     if (FunctionTemplateDecl *OldTemplateDecl =
10799             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10800       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10801       FunctionTemplateDecl *NewTemplateDecl
10802         = NewFD->getDescribedFunctionTemplate();
10803       assert(NewTemplateDecl && "Template/non-template mismatch");
10804 
10805       // The call to MergeFunctionDecl above may have created some state in
10806       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10807       // can add it as a redeclaration.
10808       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10809 
10810       NewFD->setPreviousDeclaration(OldFD);
10811       if (NewFD->isCXXClassMember()) {
10812         NewFD->setAccess(OldTemplateDecl->getAccess());
10813         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10814       }
10815 
10816       // If this is an explicit specialization of a member that is a function
10817       // template, mark it as a member specialization.
10818       if (IsMemberSpecialization &&
10819           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10820         NewTemplateDecl->setMemberSpecialization();
10821         assert(OldTemplateDecl->isMemberSpecialization());
10822         // Explicit specializations of a member template do not inherit deleted
10823         // status from the parent member template that they are specializing.
10824         if (OldFD->isDeleted()) {
10825           // FIXME: This assert will not hold in the presence of modules.
10826           assert(OldFD->getCanonicalDecl() == OldFD);
10827           // FIXME: We need an update record for this AST mutation.
10828           OldFD->setDeletedAsWritten(false);
10829         }
10830       }
10831 
10832     } else {
10833       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10834         auto *OldFD = cast<FunctionDecl>(OldDecl);
10835         // This needs to happen first so that 'inline' propagates.
10836         NewFD->setPreviousDeclaration(OldFD);
10837         if (NewFD->isCXXClassMember())
10838           NewFD->setAccess(OldFD->getAccess());
10839       }
10840     }
10841   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10842              !NewFD->getAttr<OverloadableAttr>()) {
10843     assert((Previous.empty() ||
10844             llvm::any_of(Previous,
10845                          [](const NamedDecl *ND) {
10846                            return ND->hasAttr<OverloadableAttr>();
10847                          })) &&
10848            "Non-redecls shouldn't happen without overloadable present");
10849 
10850     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10851       const auto *FD = dyn_cast<FunctionDecl>(ND);
10852       return FD && !FD->hasAttr<OverloadableAttr>();
10853     });
10854 
10855     if (OtherUnmarkedIter != Previous.end()) {
10856       Diag(NewFD->getLocation(),
10857            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10858       Diag((*OtherUnmarkedIter)->getLocation(),
10859            diag::note_attribute_overloadable_prev_overload)
10860           << false;
10861 
10862       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10863     }
10864   }
10865 
10866   if (LangOpts.OpenMP)
10867     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10868 
10869   // Semantic checking for this function declaration (in isolation).
10870 
10871   if (getLangOpts().CPlusPlus) {
10872     // C++-specific checks.
10873     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10874       CheckConstructor(Constructor);
10875     } else if (CXXDestructorDecl *Destructor =
10876                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10877       CXXRecordDecl *Record = Destructor->getParent();
10878       QualType ClassType = Context.getTypeDeclType(Record);
10879 
10880       // FIXME: Shouldn't we be able to perform this check even when the class
10881       // type is dependent? Both gcc and edg can handle that.
10882       if (!ClassType->isDependentType()) {
10883         DeclarationName Name
10884           = Context.DeclarationNames.getCXXDestructorName(
10885                                         Context.getCanonicalType(ClassType));
10886         if (NewFD->getDeclName() != Name) {
10887           Diag(NewFD->getLocation(), diag::err_destructor_name);
10888           NewFD->setInvalidDecl();
10889           return Redeclaration;
10890         }
10891       }
10892     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10893       if (auto *TD = Guide->getDescribedFunctionTemplate())
10894         CheckDeductionGuideTemplate(TD);
10895 
10896       // A deduction guide is not on the list of entities that can be
10897       // explicitly specialized.
10898       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10899         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10900             << /*explicit specialization*/ 1;
10901     }
10902 
10903     // Find any virtual functions that this function overrides.
10904     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10905       if (!Method->isFunctionTemplateSpecialization() &&
10906           !Method->getDescribedFunctionTemplate() &&
10907           Method->isCanonicalDecl()) {
10908         AddOverriddenMethods(Method->getParent(), Method);
10909       }
10910       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10911         // C++2a [class.virtual]p6
10912         // A virtual method shall not have a requires-clause.
10913         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10914              diag::err_constrained_virtual_method);
10915 
10916       if (Method->isStatic())
10917         checkThisInStaticMemberFunctionType(Method);
10918     }
10919 
10920     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10921       ActOnConversionDeclarator(Conversion);
10922 
10923     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10924     if (NewFD->isOverloadedOperator() &&
10925         CheckOverloadedOperatorDeclaration(NewFD)) {
10926       NewFD->setInvalidDecl();
10927       return Redeclaration;
10928     }
10929 
10930     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10931     if (NewFD->getLiteralIdentifier() &&
10932         CheckLiteralOperatorDeclaration(NewFD)) {
10933       NewFD->setInvalidDecl();
10934       return Redeclaration;
10935     }
10936 
10937     // In C++, check default arguments now that we have merged decls. Unless
10938     // the lexical context is the class, because in this case this is done
10939     // during delayed parsing anyway.
10940     if (!CurContext->isRecord())
10941       CheckCXXDefaultArguments(NewFD);
10942 
10943     // If this function declares a builtin function, check the type of this
10944     // declaration against the expected type for the builtin.
10945     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10946       ASTContext::GetBuiltinTypeError Error;
10947       LookupNecessaryTypesForBuiltin(S, BuiltinID);
10948       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10949       // If the type of the builtin differs only in its exception
10950       // specification, that's OK.
10951       // FIXME: If the types do differ in this way, it would be better to
10952       // retain the 'noexcept' form of the type.
10953       if (!T.isNull() &&
10954           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10955                                                             NewFD->getType()))
10956         // The type of this function differs from the type of the builtin,
10957         // so forget about the builtin entirely.
10958         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10959     }
10960 
10961     // If this function is declared as being extern "C", then check to see if
10962     // the function returns a UDT (class, struct, or union type) that is not C
10963     // compatible, and if it does, warn the user.
10964     // But, issue any diagnostic on the first declaration only.
10965     if (Previous.empty() && NewFD->isExternC()) {
10966       QualType R = NewFD->getReturnType();
10967       if (R->isIncompleteType() && !R->isVoidType())
10968         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10969             << NewFD << R;
10970       else if (!R.isPODType(Context) && !R->isVoidType() &&
10971                !R->isObjCObjectPointerType())
10972         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10973     }
10974 
10975     // C++1z [dcl.fct]p6:
10976     //   [...] whether the function has a non-throwing exception-specification
10977     //   [is] part of the function type
10978     //
10979     // This results in an ABI break between C++14 and C++17 for functions whose
10980     // declared type includes an exception-specification in a parameter or
10981     // return type. (Exception specifications on the function itself are OK in
10982     // most cases, and exception specifications are not permitted in most other
10983     // contexts where they could make it into a mangling.)
10984     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10985       auto HasNoexcept = [&](QualType T) -> bool {
10986         // Strip off declarator chunks that could be between us and a function
10987         // type. We don't need to look far, exception specifications are very
10988         // restricted prior to C++17.
10989         if (auto *RT = T->getAs<ReferenceType>())
10990           T = RT->getPointeeType();
10991         else if (T->isAnyPointerType())
10992           T = T->getPointeeType();
10993         else if (auto *MPT = T->getAs<MemberPointerType>())
10994           T = MPT->getPointeeType();
10995         if (auto *FPT = T->getAs<FunctionProtoType>())
10996           if (FPT->isNothrow())
10997             return true;
10998         return false;
10999       };
11000 
11001       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11002       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11003       for (QualType T : FPT->param_types())
11004         AnyNoexcept |= HasNoexcept(T);
11005       if (AnyNoexcept)
11006         Diag(NewFD->getLocation(),
11007              diag::warn_cxx17_compat_exception_spec_in_signature)
11008             << NewFD;
11009     }
11010 
11011     if (!Redeclaration && LangOpts.CUDA)
11012       checkCUDATargetOverload(NewFD, Previous);
11013   }
11014   return Redeclaration;
11015 }
11016 
11017 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11018   // C++11 [basic.start.main]p3:
11019   //   A program that [...] declares main to be inline, static or
11020   //   constexpr is ill-formed.
11021   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11022   //   appear in a declaration of main.
11023   // static main is not an error under C99, but we should warn about it.
11024   // We accept _Noreturn main as an extension.
11025   if (FD->getStorageClass() == SC_Static)
11026     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11027          ? diag::err_static_main : diag::warn_static_main)
11028       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11029   if (FD->isInlineSpecified())
11030     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11031       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11032   if (DS.isNoreturnSpecified()) {
11033     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11034     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11035     Diag(NoreturnLoc, diag::ext_noreturn_main);
11036     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11037       << FixItHint::CreateRemoval(NoreturnRange);
11038   }
11039   if (FD->isConstexpr()) {
11040     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11041         << FD->isConsteval()
11042         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11043     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11044   }
11045 
11046   if (getLangOpts().OpenCL) {
11047     Diag(FD->getLocation(), diag::err_opencl_no_main)
11048         << FD->hasAttr<OpenCLKernelAttr>();
11049     FD->setInvalidDecl();
11050     return;
11051   }
11052 
11053   QualType T = FD->getType();
11054   assert(T->isFunctionType() && "function decl is not of function type");
11055   const FunctionType* FT = T->castAs<FunctionType>();
11056 
11057   // Set default calling convention for main()
11058   if (FT->getCallConv() != CC_C) {
11059     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11060     FD->setType(QualType(FT, 0));
11061     T = Context.getCanonicalType(FD->getType());
11062   }
11063 
11064   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11065     // In C with GNU extensions we allow main() to have non-integer return
11066     // type, but we should warn about the extension, and we disable the
11067     // implicit-return-zero rule.
11068 
11069     // GCC in C mode accepts qualified 'int'.
11070     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11071       FD->setHasImplicitReturnZero(true);
11072     else {
11073       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11074       SourceRange RTRange = FD->getReturnTypeSourceRange();
11075       if (RTRange.isValid())
11076         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11077             << FixItHint::CreateReplacement(RTRange, "int");
11078     }
11079   } else {
11080     // In C and C++, main magically returns 0 if you fall off the end;
11081     // set the flag which tells us that.
11082     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11083 
11084     // All the standards say that main() should return 'int'.
11085     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11086       FD->setHasImplicitReturnZero(true);
11087     else {
11088       // Otherwise, this is just a flat-out error.
11089       SourceRange RTRange = FD->getReturnTypeSourceRange();
11090       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11091           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11092                                 : FixItHint());
11093       FD->setInvalidDecl(true);
11094     }
11095   }
11096 
11097   // Treat protoless main() as nullary.
11098   if (isa<FunctionNoProtoType>(FT)) return;
11099 
11100   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11101   unsigned nparams = FTP->getNumParams();
11102   assert(FD->getNumParams() == nparams);
11103 
11104   bool HasExtraParameters = (nparams > 3);
11105 
11106   if (FTP->isVariadic()) {
11107     Diag(FD->getLocation(), diag::ext_variadic_main);
11108     // FIXME: if we had information about the location of the ellipsis, we
11109     // could add a FixIt hint to remove it as a parameter.
11110   }
11111 
11112   // Darwin passes an undocumented fourth argument of type char**.  If
11113   // other platforms start sprouting these, the logic below will start
11114   // getting shifty.
11115   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11116     HasExtraParameters = false;
11117 
11118   if (HasExtraParameters) {
11119     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11120     FD->setInvalidDecl(true);
11121     nparams = 3;
11122   }
11123 
11124   // FIXME: a lot of the following diagnostics would be improved
11125   // if we had some location information about types.
11126 
11127   QualType CharPP =
11128     Context.getPointerType(Context.getPointerType(Context.CharTy));
11129   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11130 
11131   for (unsigned i = 0; i < nparams; ++i) {
11132     QualType AT = FTP->getParamType(i);
11133 
11134     bool mismatch = true;
11135 
11136     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11137       mismatch = false;
11138     else if (Expected[i] == CharPP) {
11139       // As an extension, the following forms are okay:
11140       //   char const **
11141       //   char const * const *
11142       //   char * const *
11143 
11144       QualifierCollector qs;
11145       const PointerType* PT;
11146       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11147           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11148           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11149                               Context.CharTy)) {
11150         qs.removeConst();
11151         mismatch = !qs.empty();
11152       }
11153     }
11154 
11155     if (mismatch) {
11156       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11157       // TODO: suggest replacing given type with expected type
11158       FD->setInvalidDecl(true);
11159     }
11160   }
11161 
11162   if (nparams == 1 && !FD->isInvalidDecl()) {
11163     Diag(FD->getLocation(), diag::warn_main_one_arg);
11164   }
11165 
11166   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11167     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11168     FD->setInvalidDecl();
11169   }
11170 }
11171 
11172 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11173   QualType T = FD->getType();
11174   assert(T->isFunctionType() && "function decl is not of function type");
11175   const FunctionType *FT = T->castAs<FunctionType>();
11176 
11177   // Set an implicit return of 'zero' if the function can return some integral,
11178   // enumeration, pointer or nullptr type.
11179   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11180       FT->getReturnType()->isAnyPointerType() ||
11181       FT->getReturnType()->isNullPtrType())
11182     // DllMain is exempt because a return value of zero means it failed.
11183     if (FD->getName() != "DllMain")
11184       FD->setHasImplicitReturnZero(true);
11185 
11186   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11187     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11188     FD->setInvalidDecl();
11189   }
11190 }
11191 
11192 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11193   // FIXME: Need strict checking.  In C89, we need to check for
11194   // any assignment, increment, decrement, function-calls, or
11195   // commas outside of a sizeof.  In C99, it's the same list,
11196   // except that the aforementioned are allowed in unevaluated
11197   // expressions.  Everything else falls under the
11198   // "may accept other forms of constant expressions" exception.
11199   //
11200   // Regular C++ code will not end up here (exceptions: language extensions,
11201   // OpenCL C++ etc), so the constant expression rules there don't matter.
11202   if (Init->isValueDependent()) {
11203     assert(Init->containsErrors() &&
11204            "Dependent code should only occur in error-recovery path.");
11205     return true;
11206   }
11207   const Expr *Culprit;
11208   if (Init->isConstantInitializer(Context, false, &Culprit))
11209     return false;
11210   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11211     << Culprit->getSourceRange();
11212   return true;
11213 }
11214 
11215 namespace {
11216   // Visits an initialization expression to see if OrigDecl is evaluated in
11217   // its own initialization and throws a warning if it does.
11218   class SelfReferenceChecker
11219       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11220     Sema &S;
11221     Decl *OrigDecl;
11222     bool isRecordType;
11223     bool isPODType;
11224     bool isReferenceType;
11225 
11226     bool isInitList;
11227     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11228 
11229   public:
11230     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11231 
11232     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11233                                                     S(S), OrigDecl(OrigDecl) {
11234       isPODType = false;
11235       isRecordType = false;
11236       isReferenceType = false;
11237       isInitList = false;
11238       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11239         isPODType = VD->getType().isPODType(S.Context);
11240         isRecordType = VD->getType()->isRecordType();
11241         isReferenceType = VD->getType()->isReferenceType();
11242       }
11243     }
11244 
11245     // For most expressions, just call the visitor.  For initializer lists,
11246     // track the index of the field being initialized since fields are
11247     // initialized in order allowing use of previously initialized fields.
11248     void CheckExpr(Expr *E) {
11249       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11250       if (!InitList) {
11251         Visit(E);
11252         return;
11253       }
11254 
11255       // Track and increment the index here.
11256       isInitList = true;
11257       InitFieldIndex.push_back(0);
11258       for (auto Child : InitList->children()) {
11259         CheckExpr(cast<Expr>(Child));
11260         ++InitFieldIndex.back();
11261       }
11262       InitFieldIndex.pop_back();
11263     }
11264 
11265     // Returns true if MemberExpr is checked and no further checking is needed.
11266     // Returns false if additional checking is required.
11267     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11268       llvm::SmallVector<FieldDecl*, 4> Fields;
11269       Expr *Base = E;
11270       bool ReferenceField = false;
11271 
11272       // Get the field members used.
11273       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11274         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11275         if (!FD)
11276           return false;
11277         Fields.push_back(FD);
11278         if (FD->getType()->isReferenceType())
11279           ReferenceField = true;
11280         Base = ME->getBase()->IgnoreParenImpCasts();
11281       }
11282 
11283       // Keep checking only if the base Decl is the same.
11284       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11285       if (!DRE || DRE->getDecl() != OrigDecl)
11286         return false;
11287 
11288       // A reference field can be bound to an unininitialized field.
11289       if (CheckReference && !ReferenceField)
11290         return true;
11291 
11292       // Convert FieldDecls to their index number.
11293       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11294       for (const FieldDecl *I : llvm::reverse(Fields))
11295         UsedFieldIndex.push_back(I->getFieldIndex());
11296 
11297       // See if a warning is needed by checking the first difference in index
11298       // numbers.  If field being used has index less than the field being
11299       // initialized, then the use is safe.
11300       for (auto UsedIter = UsedFieldIndex.begin(),
11301                 UsedEnd = UsedFieldIndex.end(),
11302                 OrigIter = InitFieldIndex.begin(),
11303                 OrigEnd = InitFieldIndex.end();
11304            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11305         if (*UsedIter < *OrigIter)
11306           return true;
11307         if (*UsedIter > *OrigIter)
11308           break;
11309       }
11310 
11311       // TODO: Add a different warning which will print the field names.
11312       HandleDeclRefExpr(DRE);
11313       return true;
11314     }
11315 
11316     // For most expressions, the cast is directly above the DeclRefExpr.
11317     // For conditional operators, the cast can be outside the conditional
11318     // operator if both expressions are DeclRefExpr's.
11319     void HandleValue(Expr *E) {
11320       E = E->IgnoreParens();
11321       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11322         HandleDeclRefExpr(DRE);
11323         return;
11324       }
11325 
11326       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11327         Visit(CO->getCond());
11328         HandleValue(CO->getTrueExpr());
11329         HandleValue(CO->getFalseExpr());
11330         return;
11331       }
11332 
11333       if (BinaryConditionalOperator *BCO =
11334               dyn_cast<BinaryConditionalOperator>(E)) {
11335         Visit(BCO->getCond());
11336         HandleValue(BCO->getFalseExpr());
11337         return;
11338       }
11339 
11340       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11341         HandleValue(OVE->getSourceExpr());
11342         return;
11343       }
11344 
11345       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11346         if (BO->getOpcode() == BO_Comma) {
11347           Visit(BO->getLHS());
11348           HandleValue(BO->getRHS());
11349           return;
11350         }
11351       }
11352 
11353       if (isa<MemberExpr>(E)) {
11354         if (isInitList) {
11355           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11356                                       false /*CheckReference*/))
11357             return;
11358         }
11359 
11360         Expr *Base = E->IgnoreParenImpCasts();
11361         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11362           // Check for static member variables and don't warn on them.
11363           if (!isa<FieldDecl>(ME->getMemberDecl()))
11364             return;
11365           Base = ME->getBase()->IgnoreParenImpCasts();
11366         }
11367         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11368           HandleDeclRefExpr(DRE);
11369         return;
11370       }
11371 
11372       Visit(E);
11373     }
11374 
11375     // Reference types not handled in HandleValue are handled here since all
11376     // uses of references are bad, not just r-value uses.
11377     void VisitDeclRefExpr(DeclRefExpr *E) {
11378       if (isReferenceType)
11379         HandleDeclRefExpr(E);
11380     }
11381 
11382     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11383       if (E->getCastKind() == CK_LValueToRValue) {
11384         HandleValue(E->getSubExpr());
11385         return;
11386       }
11387 
11388       Inherited::VisitImplicitCastExpr(E);
11389     }
11390 
11391     void VisitMemberExpr(MemberExpr *E) {
11392       if (isInitList) {
11393         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11394           return;
11395       }
11396 
11397       // Don't warn on arrays since they can be treated as pointers.
11398       if (E->getType()->canDecayToPointerType()) return;
11399 
11400       // Warn when a non-static method call is followed by non-static member
11401       // field accesses, which is followed by a DeclRefExpr.
11402       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11403       bool Warn = (MD && !MD->isStatic());
11404       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11405       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11406         if (!isa<FieldDecl>(ME->getMemberDecl()))
11407           Warn = false;
11408         Base = ME->getBase()->IgnoreParenImpCasts();
11409       }
11410 
11411       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11412         if (Warn)
11413           HandleDeclRefExpr(DRE);
11414         return;
11415       }
11416 
11417       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11418       // Visit that expression.
11419       Visit(Base);
11420     }
11421 
11422     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11423       Expr *Callee = E->getCallee();
11424 
11425       if (isa<UnresolvedLookupExpr>(Callee))
11426         return Inherited::VisitCXXOperatorCallExpr(E);
11427 
11428       Visit(Callee);
11429       for (auto Arg: E->arguments())
11430         HandleValue(Arg->IgnoreParenImpCasts());
11431     }
11432 
11433     void VisitUnaryOperator(UnaryOperator *E) {
11434       // For POD record types, addresses of its own members are well-defined.
11435       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11436           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11437         if (!isPODType)
11438           HandleValue(E->getSubExpr());
11439         return;
11440       }
11441 
11442       if (E->isIncrementDecrementOp()) {
11443         HandleValue(E->getSubExpr());
11444         return;
11445       }
11446 
11447       Inherited::VisitUnaryOperator(E);
11448     }
11449 
11450     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11451 
11452     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11453       if (E->getConstructor()->isCopyConstructor()) {
11454         Expr *ArgExpr = E->getArg(0);
11455         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11456           if (ILE->getNumInits() == 1)
11457             ArgExpr = ILE->getInit(0);
11458         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11459           if (ICE->getCastKind() == CK_NoOp)
11460             ArgExpr = ICE->getSubExpr();
11461         HandleValue(ArgExpr);
11462         return;
11463       }
11464       Inherited::VisitCXXConstructExpr(E);
11465     }
11466 
11467     void VisitCallExpr(CallExpr *E) {
11468       // Treat std::move as a use.
11469       if (E->isCallToStdMove()) {
11470         HandleValue(E->getArg(0));
11471         return;
11472       }
11473 
11474       Inherited::VisitCallExpr(E);
11475     }
11476 
11477     void VisitBinaryOperator(BinaryOperator *E) {
11478       if (E->isCompoundAssignmentOp()) {
11479         HandleValue(E->getLHS());
11480         Visit(E->getRHS());
11481         return;
11482       }
11483 
11484       Inherited::VisitBinaryOperator(E);
11485     }
11486 
11487     // A custom visitor for BinaryConditionalOperator is needed because the
11488     // regular visitor would check the condition and true expression separately
11489     // but both point to the same place giving duplicate diagnostics.
11490     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11491       Visit(E->getCond());
11492       Visit(E->getFalseExpr());
11493     }
11494 
11495     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11496       Decl* ReferenceDecl = DRE->getDecl();
11497       if (OrigDecl != ReferenceDecl) return;
11498       unsigned diag;
11499       if (isReferenceType) {
11500         diag = diag::warn_uninit_self_reference_in_reference_init;
11501       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11502         diag = diag::warn_static_self_reference_in_init;
11503       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11504                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11505                  DRE->getDecl()->getType()->isRecordType()) {
11506         diag = diag::warn_uninit_self_reference_in_init;
11507       } else {
11508         // Local variables will be handled by the CFG analysis.
11509         return;
11510       }
11511 
11512       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11513                             S.PDiag(diag)
11514                                 << DRE->getDecl() << OrigDecl->getLocation()
11515                                 << DRE->getSourceRange());
11516     }
11517   };
11518 
11519   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11520   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11521                                  bool DirectInit) {
11522     // Parameters arguments are occassionially constructed with itself,
11523     // for instance, in recursive functions.  Skip them.
11524     if (isa<ParmVarDecl>(OrigDecl))
11525       return;
11526 
11527     E = E->IgnoreParens();
11528 
11529     // Skip checking T a = a where T is not a record or reference type.
11530     // Doing so is a way to silence uninitialized warnings.
11531     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11532       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11533         if (ICE->getCastKind() == CK_LValueToRValue)
11534           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11535             if (DRE->getDecl() == OrigDecl)
11536               return;
11537 
11538     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11539   }
11540 } // end anonymous namespace
11541 
11542 namespace {
11543   // Simple wrapper to add the name of a variable or (if no variable is
11544   // available) a DeclarationName into a diagnostic.
11545   struct VarDeclOrName {
11546     VarDecl *VDecl;
11547     DeclarationName Name;
11548 
11549     friend const Sema::SemaDiagnosticBuilder &
11550     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11551       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11552     }
11553   };
11554 } // end anonymous namespace
11555 
11556 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11557                                             DeclarationName Name, QualType Type,
11558                                             TypeSourceInfo *TSI,
11559                                             SourceRange Range, bool DirectInit,
11560                                             Expr *Init) {
11561   bool IsInitCapture = !VDecl;
11562   assert((!VDecl || !VDecl->isInitCapture()) &&
11563          "init captures are expected to be deduced prior to initialization");
11564 
11565   VarDeclOrName VN{VDecl, Name};
11566 
11567   DeducedType *Deduced = Type->getContainedDeducedType();
11568   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11569 
11570   // C++11 [dcl.spec.auto]p3
11571   if (!Init) {
11572     assert(VDecl && "no init for init capture deduction?");
11573 
11574     // Except for class argument deduction, and then for an initializing
11575     // declaration only, i.e. no static at class scope or extern.
11576     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11577         VDecl->hasExternalStorage() ||
11578         VDecl->isStaticDataMember()) {
11579       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11580         << VDecl->getDeclName() << Type;
11581       return QualType();
11582     }
11583   }
11584 
11585   ArrayRef<Expr*> DeduceInits;
11586   if (Init)
11587     DeduceInits = Init;
11588 
11589   if (DirectInit) {
11590     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11591       DeduceInits = PL->exprs();
11592   }
11593 
11594   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11595     assert(VDecl && "non-auto type for init capture deduction?");
11596     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11597     InitializationKind Kind = InitializationKind::CreateForInit(
11598         VDecl->getLocation(), DirectInit, Init);
11599     // FIXME: Initialization should not be taking a mutable list of inits.
11600     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11601     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11602                                                        InitsCopy);
11603   }
11604 
11605   if (DirectInit) {
11606     if (auto *IL = dyn_cast<InitListExpr>(Init))
11607       DeduceInits = IL->inits();
11608   }
11609 
11610   // Deduction only works if we have exactly one source expression.
11611   if (DeduceInits.empty()) {
11612     // It isn't possible to write this directly, but it is possible to
11613     // end up in this situation with "auto x(some_pack...);"
11614     Diag(Init->getBeginLoc(), IsInitCapture
11615                                   ? diag::err_init_capture_no_expression
11616                                   : diag::err_auto_var_init_no_expression)
11617         << VN << Type << Range;
11618     return QualType();
11619   }
11620 
11621   if (DeduceInits.size() > 1) {
11622     Diag(DeduceInits[1]->getBeginLoc(),
11623          IsInitCapture ? diag::err_init_capture_multiple_expressions
11624                        : diag::err_auto_var_init_multiple_expressions)
11625         << VN << Type << Range;
11626     return QualType();
11627   }
11628 
11629   Expr *DeduceInit = DeduceInits[0];
11630   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11631     Diag(Init->getBeginLoc(), IsInitCapture
11632                                   ? diag::err_init_capture_paren_braces
11633                                   : diag::err_auto_var_init_paren_braces)
11634         << isa<InitListExpr>(Init) << VN << Type << Range;
11635     return QualType();
11636   }
11637 
11638   // Expressions default to 'id' when we're in a debugger.
11639   bool DefaultedAnyToId = false;
11640   if (getLangOpts().DebuggerCastResultToId &&
11641       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11642     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11643     if (Result.isInvalid()) {
11644       return QualType();
11645     }
11646     Init = Result.get();
11647     DefaultedAnyToId = true;
11648   }
11649 
11650   // C++ [dcl.decomp]p1:
11651   //   If the assignment-expression [...] has array type A and no ref-qualifier
11652   //   is present, e has type cv A
11653   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11654       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11655       DeduceInit->getType()->isConstantArrayType())
11656     return Context.getQualifiedType(DeduceInit->getType(),
11657                                     Type.getQualifiers());
11658 
11659   QualType DeducedType;
11660   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11661     if (!IsInitCapture)
11662       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11663     else if (isa<InitListExpr>(Init))
11664       Diag(Range.getBegin(),
11665            diag::err_init_capture_deduction_failure_from_init_list)
11666           << VN
11667           << (DeduceInit->getType().isNull() ? TSI->getType()
11668                                              : DeduceInit->getType())
11669           << DeduceInit->getSourceRange();
11670     else
11671       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11672           << VN << TSI->getType()
11673           << (DeduceInit->getType().isNull() ? TSI->getType()
11674                                              : DeduceInit->getType())
11675           << DeduceInit->getSourceRange();
11676   }
11677 
11678   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11679   // 'id' instead of a specific object type prevents most of our usual
11680   // checks.
11681   // We only want to warn outside of template instantiations, though:
11682   // inside a template, the 'id' could have come from a parameter.
11683   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11684       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11685     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11686     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11687   }
11688 
11689   return DeducedType;
11690 }
11691 
11692 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11693                                          Expr *Init) {
11694   assert(!Init || !Init->containsErrors());
11695   QualType DeducedType = deduceVarTypeFromInitializer(
11696       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11697       VDecl->getSourceRange(), DirectInit, Init);
11698   if (DeducedType.isNull()) {
11699     VDecl->setInvalidDecl();
11700     return true;
11701   }
11702 
11703   VDecl->setType(DeducedType);
11704   assert(VDecl->isLinkageValid());
11705 
11706   // In ARC, infer lifetime.
11707   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11708     VDecl->setInvalidDecl();
11709 
11710   if (getLangOpts().OpenCL)
11711     deduceOpenCLAddressSpace(VDecl);
11712 
11713   // If this is a redeclaration, check that the type we just deduced matches
11714   // the previously declared type.
11715   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11716     // We never need to merge the type, because we cannot form an incomplete
11717     // array of auto, nor deduce such a type.
11718     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11719   }
11720 
11721   // Check the deduced type is valid for a variable declaration.
11722   CheckVariableDeclarationType(VDecl);
11723   return VDecl->isInvalidDecl();
11724 }
11725 
11726 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11727                                               SourceLocation Loc) {
11728   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11729     Init = EWC->getSubExpr();
11730 
11731   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11732     Init = CE->getSubExpr();
11733 
11734   QualType InitType = Init->getType();
11735   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11736           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11737          "shouldn't be called if type doesn't have a non-trivial C struct");
11738   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11739     for (auto I : ILE->inits()) {
11740       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11741           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11742         continue;
11743       SourceLocation SL = I->getExprLoc();
11744       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11745     }
11746     return;
11747   }
11748 
11749   if (isa<ImplicitValueInitExpr>(Init)) {
11750     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11751       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11752                             NTCUK_Init);
11753   } else {
11754     // Assume all other explicit initializers involving copying some existing
11755     // object.
11756     // TODO: ignore any explicit initializers where we can guarantee
11757     // copy-elision.
11758     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11759       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11760   }
11761 }
11762 
11763 namespace {
11764 
11765 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11766   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11767   // in the source code or implicitly by the compiler if it is in a union
11768   // defined in a system header and has non-trivial ObjC ownership
11769   // qualifications. We don't want those fields to participate in determining
11770   // whether the containing union is non-trivial.
11771   return FD->hasAttr<UnavailableAttr>();
11772 }
11773 
11774 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11775     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11776                                     void> {
11777   using Super =
11778       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11779                                     void>;
11780 
11781   DiagNonTrivalCUnionDefaultInitializeVisitor(
11782       QualType OrigTy, SourceLocation OrigLoc,
11783       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11784       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11785 
11786   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11787                      const FieldDecl *FD, bool InNonTrivialUnion) {
11788     if (const auto *AT = S.Context.getAsArrayType(QT))
11789       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11790                                      InNonTrivialUnion);
11791     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11792   }
11793 
11794   void visitARCStrong(QualType QT, const FieldDecl *FD,
11795                       bool InNonTrivialUnion) {
11796     if (InNonTrivialUnion)
11797       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11798           << 1 << 0 << QT << FD->getName();
11799   }
11800 
11801   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11802     if (InNonTrivialUnion)
11803       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11804           << 1 << 0 << QT << FD->getName();
11805   }
11806 
11807   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11808     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11809     if (RD->isUnion()) {
11810       if (OrigLoc.isValid()) {
11811         bool IsUnion = false;
11812         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11813           IsUnion = OrigRD->isUnion();
11814         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11815             << 0 << OrigTy << IsUnion << UseContext;
11816         // Reset OrigLoc so that this diagnostic is emitted only once.
11817         OrigLoc = SourceLocation();
11818       }
11819       InNonTrivialUnion = true;
11820     }
11821 
11822     if (InNonTrivialUnion)
11823       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11824           << 0 << 0 << QT.getUnqualifiedType() << "";
11825 
11826     for (const FieldDecl *FD : RD->fields())
11827       if (!shouldIgnoreForRecordTriviality(FD))
11828         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11829   }
11830 
11831   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11832 
11833   // The non-trivial C union type or the struct/union type that contains a
11834   // non-trivial C union.
11835   QualType OrigTy;
11836   SourceLocation OrigLoc;
11837   Sema::NonTrivialCUnionContext UseContext;
11838   Sema &S;
11839 };
11840 
11841 struct DiagNonTrivalCUnionDestructedTypeVisitor
11842     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11843   using Super =
11844       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11845 
11846   DiagNonTrivalCUnionDestructedTypeVisitor(
11847       QualType OrigTy, SourceLocation OrigLoc,
11848       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11849       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11850 
11851   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11852                      const FieldDecl *FD, bool InNonTrivialUnion) {
11853     if (const auto *AT = S.Context.getAsArrayType(QT))
11854       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11855                                      InNonTrivialUnion);
11856     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11857   }
11858 
11859   void visitARCStrong(QualType QT, const FieldDecl *FD,
11860                       bool InNonTrivialUnion) {
11861     if (InNonTrivialUnion)
11862       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11863           << 1 << 1 << QT << FD->getName();
11864   }
11865 
11866   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11867     if (InNonTrivialUnion)
11868       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11869           << 1 << 1 << QT << FD->getName();
11870   }
11871 
11872   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11873     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11874     if (RD->isUnion()) {
11875       if (OrigLoc.isValid()) {
11876         bool IsUnion = false;
11877         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11878           IsUnion = OrigRD->isUnion();
11879         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11880             << 1 << OrigTy << IsUnion << UseContext;
11881         // Reset OrigLoc so that this diagnostic is emitted only once.
11882         OrigLoc = SourceLocation();
11883       }
11884       InNonTrivialUnion = true;
11885     }
11886 
11887     if (InNonTrivialUnion)
11888       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11889           << 0 << 1 << QT.getUnqualifiedType() << "";
11890 
11891     for (const FieldDecl *FD : RD->fields())
11892       if (!shouldIgnoreForRecordTriviality(FD))
11893         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11894   }
11895 
11896   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11897   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11898                           bool InNonTrivialUnion) {}
11899 
11900   // The non-trivial C union type or the struct/union type that contains a
11901   // non-trivial C union.
11902   QualType OrigTy;
11903   SourceLocation OrigLoc;
11904   Sema::NonTrivialCUnionContext UseContext;
11905   Sema &S;
11906 };
11907 
11908 struct DiagNonTrivalCUnionCopyVisitor
11909     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11910   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11911 
11912   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11913                                  Sema::NonTrivialCUnionContext UseContext,
11914                                  Sema &S)
11915       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11916 
11917   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11918                      const FieldDecl *FD, bool InNonTrivialUnion) {
11919     if (const auto *AT = S.Context.getAsArrayType(QT))
11920       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11921                                      InNonTrivialUnion);
11922     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11923   }
11924 
11925   void visitARCStrong(QualType QT, const FieldDecl *FD,
11926                       bool InNonTrivialUnion) {
11927     if (InNonTrivialUnion)
11928       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11929           << 1 << 2 << QT << FD->getName();
11930   }
11931 
11932   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11933     if (InNonTrivialUnion)
11934       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11935           << 1 << 2 << QT << FD->getName();
11936   }
11937 
11938   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11939     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11940     if (RD->isUnion()) {
11941       if (OrigLoc.isValid()) {
11942         bool IsUnion = false;
11943         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11944           IsUnion = OrigRD->isUnion();
11945         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11946             << 2 << OrigTy << IsUnion << UseContext;
11947         // Reset OrigLoc so that this diagnostic is emitted only once.
11948         OrigLoc = SourceLocation();
11949       }
11950       InNonTrivialUnion = true;
11951     }
11952 
11953     if (InNonTrivialUnion)
11954       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11955           << 0 << 2 << QT.getUnqualifiedType() << "";
11956 
11957     for (const FieldDecl *FD : RD->fields())
11958       if (!shouldIgnoreForRecordTriviality(FD))
11959         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11960   }
11961 
11962   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11963                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11964   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11965   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11966                             bool InNonTrivialUnion) {}
11967 
11968   // The non-trivial C union type or the struct/union type that contains a
11969   // non-trivial C union.
11970   QualType OrigTy;
11971   SourceLocation OrigLoc;
11972   Sema::NonTrivialCUnionContext UseContext;
11973   Sema &S;
11974 };
11975 
11976 } // namespace
11977 
11978 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11979                                  NonTrivialCUnionContext UseContext,
11980                                  unsigned NonTrivialKind) {
11981   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11982           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11983           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11984          "shouldn't be called if type doesn't have a non-trivial C union");
11985 
11986   if ((NonTrivialKind & NTCUK_Init) &&
11987       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11988     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11989         .visit(QT, nullptr, false);
11990   if ((NonTrivialKind & NTCUK_Destruct) &&
11991       QT.hasNonTrivialToPrimitiveDestructCUnion())
11992     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11993         .visit(QT, nullptr, false);
11994   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11995     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11996         .visit(QT, nullptr, false);
11997 }
11998 
11999 /// AddInitializerToDecl - Adds the initializer Init to the
12000 /// declaration dcl. If DirectInit is true, this is C++ direct
12001 /// initialization rather than copy initialization.
12002 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12003   // If there is no declaration, there was an error parsing it.  Just ignore
12004   // the initializer.
12005   if (!RealDecl || RealDecl->isInvalidDecl()) {
12006     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12007     return;
12008   }
12009 
12010   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12011     // Pure-specifiers are handled in ActOnPureSpecifier.
12012     Diag(Method->getLocation(), diag::err_member_function_initialization)
12013       << Method->getDeclName() << Init->getSourceRange();
12014     Method->setInvalidDecl();
12015     return;
12016   }
12017 
12018   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12019   if (!VDecl) {
12020     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12021     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12022     RealDecl->setInvalidDecl();
12023     return;
12024   }
12025 
12026   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12027   if (VDecl->getType()->isUndeducedType()) {
12028     // Attempt typo correction early so that the type of the init expression can
12029     // be deduced based on the chosen correction if the original init contains a
12030     // TypoExpr.
12031     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12032     if (!Res.isUsable()) {
12033       // There are unresolved typos in Init, just drop them.
12034       // FIXME: improve the recovery strategy to preserve the Init.
12035       RealDecl->setInvalidDecl();
12036       return;
12037     }
12038     if (Res.get()->containsErrors()) {
12039       // Invalidate the decl as we don't know the type for recovery-expr yet.
12040       RealDecl->setInvalidDecl();
12041       VDecl->setInit(Res.get());
12042       return;
12043     }
12044     Init = Res.get();
12045 
12046     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12047       return;
12048   }
12049 
12050   // dllimport cannot be used on variable definitions.
12051   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12052     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12053     VDecl->setInvalidDecl();
12054     return;
12055   }
12056 
12057   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12058     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12059     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12060     VDecl->setInvalidDecl();
12061     return;
12062   }
12063 
12064   if (!VDecl->getType()->isDependentType()) {
12065     // A definition must end up with a complete type, which means it must be
12066     // complete with the restriction that an array type might be completed by
12067     // the initializer; note that later code assumes this restriction.
12068     QualType BaseDeclType = VDecl->getType();
12069     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12070       BaseDeclType = Array->getElementType();
12071     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12072                             diag::err_typecheck_decl_incomplete_type)) {
12073       RealDecl->setInvalidDecl();
12074       return;
12075     }
12076 
12077     // The variable can not have an abstract class type.
12078     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12079                                diag::err_abstract_type_in_decl,
12080                                AbstractVariableType))
12081       VDecl->setInvalidDecl();
12082   }
12083 
12084   // If adding the initializer will turn this declaration into a definition,
12085   // and we already have a definition for this variable, diagnose or otherwise
12086   // handle the situation.
12087   VarDecl *Def;
12088   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12089       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12090       !VDecl->isThisDeclarationADemotedDefinition() &&
12091       checkVarDeclRedefinition(Def, VDecl))
12092     return;
12093 
12094   if (getLangOpts().CPlusPlus) {
12095     // C++ [class.static.data]p4
12096     //   If a static data member is of const integral or const
12097     //   enumeration type, its declaration in the class definition can
12098     //   specify a constant-initializer which shall be an integral
12099     //   constant expression (5.19). In that case, the member can appear
12100     //   in integral constant expressions. The member shall still be
12101     //   defined in a namespace scope if it is used in the program and the
12102     //   namespace scope definition shall not contain an initializer.
12103     //
12104     // We already performed a redefinition check above, but for static
12105     // data members we also need to check whether there was an in-class
12106     // declaration with an initializer.
12107     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12108       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12109           << VDecl->getDeclName();
12110       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12111            diag::note_previous_initializer)
12112           << 0;
12113       return;
12114     }
12115 
12116     if (VDecl->hasLocalStorage())
12117       setFunctionHasBranchProtectedScope();
12118 
12119     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12120       VDecl->setInvalidDecl();
12121       return;
12122     }
12123   }
12124 
12125   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12126   // a kernel function cannot be initialized."
12127   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12128     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12129     VDecl->setInvalidDecl();
12130     return;
12131   }
12132 
12133   // The LoaderUninitialized attribute acts as a definition (of undef).
12134   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12135     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12136     VDecl->setInvalidDecl();
12137     return;
12138   }
12139 
12140   // Get the decls type and save a reference for later, since
12141   // CheckInitializerTypes may change it.
12142   QualType DclT = VDecl->getType(), SavT = DclT;
12143 
12144   // Expressions default to 'id' when we're in a debugger
12145   // and we are assigning it to a variable of Objective-C pointer type.
12146   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12147       Init->getType() == Context.UnknownAnyTy) {
12148     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12149     if (Result.isInvalid()) {
12150       VDecl->setInvalidDecl();
12151       return;
12152     }
12153     Init = Result.get();
12154   }
12155 
12156   // Perform the initialization.
12157   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12158   if (!VDecl->isInvalidDecl()) {
12159     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12160     InitializationKind Kind = InitializationKind::CreateForInit(
12161         VDecl->getLocation(), DirectInit, Init);
12162 
12163     MultiExprArg Args = Init;
12164     if (CXXDirectInit)
12165       Args = MultiExprArg(CXXDirectInit->getExprs(),
12166                           CXXDirectInit->getNumExprs());
12167 
12168     // Try to correct any TypoExprs in the initialization arguments.
12169     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12170       ExprResult Res = CorrectDelayedTyposInExpr(
12171           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12172           [this, Entity, Kind](Expr *E) {
12173             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12174             return Init.Failed() ? ExprError() : E;
12175           });
12176       if (Res.isInvalid()) {
12177         VDecl->setInvalidDecl();
12178       } else if (Res.get() != Args[Idx]) {
12179         Args[Idx] = Res.get();
12180       }
12181     }
12182     if (VDecl->isInvalidDecl())
12183       return;
12184 
12185     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12186                                    /*TopLevelOfInitList=*/false,
12187                                    /*TreatUnavailableAsInvalid=*/false);
12188     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12189     if (Result.isInvalid()) {
12190       // If the provied initializer fails to initialize the var decl,
12191       // we attach a recovery expr for better recovery.
12192       auto RecoveryExpr =
12193           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12194       if (RecoveryExpr.get())
12195         VDecl->setInit(RecoveryExpr.get());
12196       return;
12197     }
12198 
12199     Init = Result.getAs<Expr>();
12200   }
12201 
12202   // Check for self-references within variable initializers.
12203   // Variables declared within a function/method body (except for references)
12204   // are handled by a dataflow analysis.
12205   // This is undefined behavior in C++, but valid in C.
12206   if (getLangOpts().CPlusPlus) {
12207     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12208         VDecl->getType()->isReferenceType()) {
12209       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12210     }
12211   }
12212 
12213   // If the type changed, it means we had an incomplete type that was
12214   // completed by the initializer. For example:
12215   //   int ary[] = { 1, 3, 5 };
12216   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12217   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12218     VDecl->setType(DclT);
12219 
12220   if (!VDecl->isInvalidDecl()) {
12221     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12222 
12223     if (VDecl->hasAttr<BlocksAttr>())
12224       checkRetainCycles(VDecl, Init);
12225 
12226     // It is safe to assign a weak reference into a strong variable.
12227     // Although this code can still have problems:
12228     //   id x = self.weakProp;
12229     //   id y = self.weakProp;
12230     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12231     // paths through the function. This should be revisited if
12232     // -Wrepeated-use-of-weak is made flow-sensitive.
12233     if (FunctionScopeInfo *FSI = getCurFunction())
12234       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12235            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12236           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12237                            Init->getBeginLoc()))
12238         FSI->markSafeWeakUse(Init);
12239   }
12240 
12241   // The initialization is usually a full-expression.
12242   //
12243   // FIXME: If this is a braced initialization of an aggregate, it is not
12244   // an expression, and each individual field initializer is a separate
12245   // full-expression. For instance, in:
12246   //
12247   //   struct Temp { ~Temp(); };
12248   //   struct S { S(Temp); };
12249   //   struct T { S a, b; } t = { Temp(), Temp() }
12250   //
12251   // we should destroy the first Temp before constructing the second.
12252   ExprResult Result =
12253       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12254                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12255   if (Result.isInvalid()) {
12256     VDecl->setInvalidDecl();
12257     return;
12258   }
12259   Init = Result.get();
12260 
12261   // Attach the initializer to the decl.
12262   VDecl->setInit(Init);
12263 
12264   if (VDecl->isLocalVarDecl()) {
12265     // Don't check the initializer if the declaration is malformed.
12266     if (VDecl->isInvalidDecl()) {
12267       // do nothing
12268 
12269     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12270     // This is true even in C++ for OpenCL.
12271     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12272       CheckForConstantInitializer(Init, DclT);
12273 
12274     // Otherwise, C++ does not restrict the initializer.
12275     } else if (getLangOpts().CPlusPlus) {
12276       // do nothing
12277 
12278     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12279     // static storage duration shall be constant expressions or string literals.
12280     } else if (VDecl->getStorageClass() == SC_Static) {
12281       CheckForConstantInitializer(Init, DclT);
12282 
12283     // C89 is stricter than C99 for aggregate initializers.
12284     // C89 6.5.7p3: All the expressions [...] in an initializer list
12285     // for an object that has aggregate or union type shall be
12286     // constant expressions.
12287     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12288                isa<InitListExpr>(Init)) {
12289       const Expr *Culprit;
12290       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12291         Diag(Culprit->getExprLoc(),
12292              diag::ext_aggregate_init_not_constant)
12293           << Culprit->getSourceRange();
12294       }
12295     }
12296 
12297     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12298       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12299         if (VDecl->hasLocalStorage())
12300           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12301   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12302              VDecl->getLexicalDeclContext()->isRecord()) {
12303     // This is an in-class initialization for a static data member, e.g.,
12304     //
12305     // struct S {
12306     //   static const int value = 17;
12307     // };
12308 
12309     // C++ [class.mem]p4:
12310     //   A member-declarator can contain a constant-initializer only
12311     //   if it declares a static member (9.4) of const integral or
12312     //   const enumeration type, see 9.4.2.
12313     //
12314     // C++11 [class.static.data]p3:
12315     //   If a non-volatile non-inline const static data member is of integral
12316     //   or enumeration type, its declaration in the class definition can
12317     //   specify a brace-or-equal-initializer in which every initializer-clause
12318     //   that is an assignment-expression is a constant expression. A static
12319     //   data member of literal type can be declared in the class definition
12320     //   with the constexpr specifier; if so, its declaration shall specify a
12321     //   brace-or-equal-initializer in which every initializer-clause that is
12322     //   an assignment-expression is a constant expression.
12323 
12324     // Do nothing on dependent types.
12325     if (DclT->isDependentType()) {
12326 
12327     // Allow any 'static constexpr' members, whether or not they are of literal
12328     // type. We separately check that every constexpr variable is of literal
12329     // type.
12330     } else if (VDecl->isConstexpr()) {
12331 
12332     // Require constness.
12333     } else if (!DclT.isConstQualified()) {
12334       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12335         << Init->getSourceRange();
12336       VDecl->setInvalidDecl();
12337 
12338     // We allow integer constant expressions in all cases.
12339     } else if (DclT->isIntegralOrEnumerationType()) {
12340       // Check whether the expression is a constant expression.
12341       SourceLocation Loc;
12342       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12343         // In C++11, a non-constexpr const static data member with an
12344         // in-class initializer cannot be volatile.
12345         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12346       else if (Init->isValueDependent())
12347         ; // Nothing to check.
12348       else if (Init->isIntegerConstantExpr(Context, &Loc))
12349         ; // Ok, it's an ICE!
12350       else if (Init->getType()->isScopedEnumeralType() &&
12351                Init->isCXX11ConstantExpr(Context))
12352         ; // Ok, it is a scoped-enum constant expression.
12353       else if (Init->isEvaluatable(Context)) {
12354         // If we can constant fold the initializer through heroics, accept it,
12355         // but report this as a use of an extension for -pedantic.
12356         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12357           << Init->getSourceRange();
12358       } else {
12359         // Otherwise, this is some crazy unknown case.  Report the issue at the
12360         // location provided by the isIntegerConstantExpr failed check.
12361         Diag(Loc, diag::err_in_class_initializer_non_constant)
12362           << Init->getSourceRange();
12363         VDecl->setInvalidDecl();
12364       }
12365 
12366     // We allow foldable floating-point constants as an extension.
12367     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12368       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12369       // it anyway and provide a fixit to add the 'constexpr'.
12370       if (getLangOpts().CPlusPlus11) {
12371         Diag(VDecl->getLocation(),
12372              diag::ext_in_class_initializer_float_type_cxx11)
12373             << DclT << Init->getSourceRange();
12374         Diag(VDecl->getBeginLoc(),
12375              diag::note_in_class_initializer_float_type_cxx11)
12376             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12377       } else {
12378         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12379           << DclT << Init->getSourceRange();
12380 
12381         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12382           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12383             << Init->getSourceRange();
12384           VDecl->setInvalidDecl();
12385         }
12386       }
12387 
12388     // Suggest adding 'constexpr' in C++11 for literal types.
12389     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12390       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12391           << DclT << Init->getSourceRange()
12392           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12393       VDecl->setConstexpr(true);
12394 
12395     } else {
12396       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12397         << DclT << Init->getSourceRange();
12398       VDecl->setInvalidDecl();
12399     }
12400   } else if (VDecl->isFileVarDecl()) {
12401     // In C, extern is typically used to avoid tentative definitions when
12402     // declaring variables in headers, but adding an intializer makes it a
12403     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12404     // In C++, extern is often used to give implictly static const variables
12405     // external linkage, so don't warn in that case. If selectany is present,
12406     // this might be header code intended for C and C++ inclusion, so apply the
12407     // C++ rules.
12408     if (VDecl->getStorageClass() == SC_Extern &&
12409         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12410          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12411         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12412         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12413       Diag(VDecl->getLocation(), diag::warn_extern_init);
12414 
12415     // In Microsoft C++ mode, a const variable defined in namespace scope has
12416     // external linkage by default if the variable is declared with
12417     // __declspec(dllexport).
12418     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12419         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12420         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12421       VDecl->setStorageClass(SC_Extern);
12422 
12423     // C99 6.7.8p4. All file scoped initializers need to be constant.
12424     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12425       CheckForConstantInitializer(Init, DclT);
12426   }
12427 
12428   QualType InitType = Init->getType();
12429   if (!InitType.isNull() &&
12430       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12431        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12432     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12433 
12434   // We will represent direct-initialization similarly to copy-initialization:
12435   //    int x(1);  -as-> int x = 1;
12436   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12437   //
12438   // Clients that want to distinguish between the two forms, can check for
12439   // direct initializer using VarDecl::getInitStyle().
12440   // A major benefit is that clients that don't particularly care about which
12441   // exactly form was it (like the CodeGen) can handle both cases without
12442   // special case code.
12443 
12444   // C++ 8.5p11:
12445   // The form of initialization (using parentheses or '=') is generally
12446   // insignificant, but does matter when the entity being initialized has a
12447   // class type.
12448   if (CXXDirectInit) {
12449     assert(DirectInit && "Call-style initializer must be direct init.");
12450     VDecl->setInitStyle(VarDecl::CallInit);
12451   } else if (DirectInit) {
12452     // This must be list-initialization. No other way is direct-initialization.
12453     VDecl->setInitStyle(VarDecl::ListInit);
12454   }
12455 
12456   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12457     DeclsToCheckForDeferredDiags.push_back(VDecl);
12458   CheckCompleteVariableDeclaration(VDecl);
12459 }
12460 
12461 /// ActOnInitializerError - Given that there was an error parsing an
12462 /// initializer for the given declaration, try to return to some form
12463 /// of sanity.
12464 void Sema::ActOnInitializerError(Decl *D) {
12465   // Our main concern here is re-establishing invariants like "a
12466   // variable's type is either dependent or complete".
12467   if (!D || D->isInvalidDecl()) return;
12468 
12469   VarDecl *VD = dyn_cast<VarDecl>(D);
12470   if (!VD) return;
12471 
12472   // Bindings are not usable if we can't make sense of the initializer.
12473   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12474     for (auto *BD : DD->bindings())
12475       BD->setInvalidDecl();
12476 
12477   // Auto types are meaningless if we can't make sense of the initializer.
12478   if (VD->getType()->isUndeducedType()) {
12479     D->setInvalidDecl();
12480     return;
12481   }
12482 
12483   QualType Ty = VD->getType();
12484   if (Ty->isDependentType()) return;
12485 
12486   // Require a complete type.
12487   if (RequireCompleteType(VD->getLocation(),
12488                           Context.getBaseElementType(Ty),
12489                           diag::err_typecheck_decl_incomplete_type)) {
12490     VD->setInvalidDecl();
12491     return;
12492   }
12493 
12494   // Require a non-abstract type.
12495   if (RequireNonAbstractType(VD->getLocation(), Ty,
12496                              diag::err_abstract_type_in_decl,
12497                              AbstractVariableType)) {
12498     VD->setInvalidDecl();
12499     return;
12500   }
12501 
12502   // Don't bother complaining about constructors or destructors,
12503   // though.
12504 }
12505 
12506 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12507   // If there is no declaration, there was an error parsing it. Just ignore it.
12508   if (!RealDecl)
12509     return;
12510 
12511   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12512     QualType Type = Var->getType();
12513 
12514     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12515     if (isa<DecompositionDecl>(RealDecl)) {
12516       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12517       Var->setInvalidDecl();
12518       return;
12519     }
12520 
12521     if (Type->isUndeducedType() &&
12522         DeduceVariableDeclarationType(Var, false, nullptr))
12523       return;
12524 
12525     // C++11 [class.static.data]p3: A static data member can be declared with
12526     // the constexpr specifier; if so, its declaration shall specify
12527     // a brace-or-equal-initializer.
12528     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12529     // the definition of a variable [...] or the declaration of a static data
12530     // member.
12531     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12532         !Var->isThisDeclarationADemotedDefinition()) {
12533       if (Var->isStaticDataMember()) {
12534         // C++1z removes the relevant rule; the in-class declaration is always
12535         // a definition there.
12536         if (!getLangOpts().CPlusPlus17 &&
12537             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12538           Diag(Var->getLocation(),
12539                diag::err_constexpr_static_mem_var_requires_init)
12540               << Var;
12541           Var->setInvalidDecl();
12542           return;
12543         }
12544       } else {
12545         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12546         Var->setInvalidDecl();
12547         return;
12548       }
12549     }
12550 
12551     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12552     // be initialized.
12553     if (!Var->isInvalidDecl() &&
12554         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12555         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12556       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12557       Var->setInvalidDecl();
12558       return;
12559     }
12560 
12561     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12562       if (Var->getStorageClass() == SC_Extern) {
12563         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12564             << Var;
12565         Var->setInvalidDecl();
12566         return;
12567       }
12568       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12569                               diag::err_typecheck_decl_incomplete_type)) {
12570         Var->setInvalidDecl();
12571         return;
12572       }
12573       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12574         if (!RD->hasTrivialDefaultConstructor()) {
12575           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12576           Var->setInvalidDecl();
12577           return;
12578         }
12579       }
12580     }
12581 
12582     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12583     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12584         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12585       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12586                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12587 
12588 
12589     switch (DefKind) {
12590     case VarDecl::Definition:
12591       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12592         break;
12593 
12594       // We have an out-of-line definition of a static data member
12595       // that has an in-class initializer, so we type-check this like
12596       // a declaration.
12597       //
12598       LLVM_FALLTHROUGH;
12599 
12600     case VarDecl::DeclarationOnly:
12601       // It's only a declaration.
12602 
12603       // Block scope. C99 6.7p7: If an identifier for an object is
12604       // declared with no linkage (C99 6.2.2p6), the type for the
12605       // object shall be complete.
12606       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12607           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12608           RequireCompleteType(Var->getLocation(), Type,
12609                               diag::err_typecheck_decl_incomplete_type))
12610         Var->setInvalidDecl();
12611 
12612       // Make sure that the type is not abstract.
12613       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12614           RequireNonAbstractType(Var->getLocation(), Type,
12615                                  diag::err_abstract_type_in_decl,
12616                                  AbstractVariableType))
12617         Var->setInvalidDecl();
12618       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12619           Var->getStorageClass() == SC_PrivateExtern) {
12620         Diag(Var->getLocation(), diag::warn_private_extern);
12621         Diag(Var->getLocation(), diag::note_private_extern);
12622       }
12623 
12624       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12625           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12626         ExternalDeclarations.push_back(Var);
12627 
12628       return;
12629 
12630     case VarDecl::TentativeDefinition:
12631       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12632       // object that has file scope without an initializer, and without a
12633       // storage-class specifier or with the storage-class specifier "static",
12634       // constitutes a tentative definition. Note: A tentative definition with
12635       // external linkage is valid (C99 6.2.2p5).
12636       if (!Var->isInvalidDecl()) {
12637         if (const IncompleteArrayType *ArrayT
12638                                     = Context.getAsIncompleteArrayType(Type)) {
12639           if (RequireCompleteSizedType(
12640                   Var->getLocation(), ArrayT->getElementType(),
12641                   diag::err_array_incomplete_or_sizeless_type))
12642             Var->setInvalidDecl();
12643         } else if (Var->getStorageClass() == SC_Static) {
12644           // C99 6.9.2p3: If the declaration of an identifier for an object is
12645           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12646           // declared type shall not be an incomplete type.
12647           // NOTE: code such as the following
12648           //     static struct s;
12649           //     struct s { int a; };
12650           // is accepted by gcc. Hence here we issue a warning instead of
12651           // an error and we do not invalidate the static declaration.
12652           // NOTE: to avoid multiple warnings, only check the first declaration.
12653           if (Var->isFirstDecl())
12654             RequireCompleteType(Var->getLocation(), Type,
12655                                 diag::ext_typecheck_decl_incomplete_type);
12656         }
12657       }
12658 
12659       // Record the tentative definition; we're done.
12660       if (!Var->isInvalidDecl())
12661         TentativeDefinitions.push_back(Var);
12662       return;
12663     }
12664 
12665     // Provide a specific diagnostic for uninitialized variable
12666     // definitions with incomplete array type.
12667     if (Type->isIncompleteArrayType()) {
12668       Diag(Var->getLocation(),
12669            diag::err_typecheck_incomplete_array_needs_initializer);
12670       Var->setInvalidDecl();
12671       return;
12672     }
12673 
12674     // Provide a specific diagnostic for uninitialized variable
12675     // definitions with reference type.
12676     if (Type->isReferenceType()) {
12677       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12678           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12679       Var->setInvalidDecl();
12680       return;
12681     }
12682 
12683     // Do not attempt to type-check the default initializer for a
12684     // variable with dependent type.
12685     if (Type->isDependentType())
12686       return;
12687 
12688     if (Var->isInvalidDecl())
12689       return;
12690 
12691     if (!Var->hasAttr<AliasAttr>()) {
12692       if (RequireCompleteType(Var->getLocation(),
12693                               Context.getBaseElementType(Type),
12694                               diag::err_typecheck_decl_incomplete_type)) {
12695         Var->setInvalidDecl();
12696         return;
12697       }
12698     } else {
12699       return;
12700     }
12701 
12702     // The variable can not have an abstract class type.
12703     if (RequireNonAbstractType(Var->getLocation(), Type,
12704                                diag::err_abstract_type_in_decl,
12705                                AbstractVariableType)) {
12706       Var->setInvalidDecl();
12707       return;
12708     }
12709 
12710     // Check for jumps past the implicit initializer.  C++0x
12711     // clarifies that this applies to a "variable with automatic
12712     // storage duration", not a "local variable".
12713     // C++11 [stmt.dcl]p3
12714     //   A program that jumps from a point where a variable with automatic
12715     //   storage duration is not in scope to a point where it is in scope is
12716     //   ill-formed unless the variable has scalar type, class type with a
12717     //   trivial default constructor and a trivial destructor, a cv-qualified
12718     //   version of one of these types, or an array of one of the preceding
12719     //   types and is declared without an initializer.
12720     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12721       if (const RecordType *Record
12722             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12723         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12724         // Mark the function (if we're in one) for further checking even if the
12725         // looser rules of C++11 do not require such checks, so that we can
12726         // diagnose incompatibilities with C++98.
12727         if (!CXXRecord->isPOD())
12728           setFunctionHasBranchProtectedScope();
12729       }
12730     }
12731     // In OpenCL, we can't initialize objects in the __local address space,
12732     // even implicitly, so don't synthesize an implicit initializer.
12733     if (getLangOpts().OpenCL &&
12734         Var->getType().getAddressSpace() == LangAS::opencl_local)
12735       return;
12736     // C++03 [dcl.init]p9:
12737     //   If no initializer is specified for an object, and the
12738     //   object is of (possibly cv-qualified) non-POD class type (or
12739     //   array thereof), the object shall be default-initialized; if
12740     //   the object is of const-qualified type, the underlying class
12741     //   type shall have a user-declared default
12742     //   constructor. Otherwise, if no initializer is specified for
12743     //   a non- static object, the object and its subobjects, if
12744     //   any, have an indeterminate initial value); if the object
12745     //   or any of its subobjects are of const-qualified type, the
12746     //   program is ill-formed.
12747     // C++0x [dcl.init]p11:
12748     //   If no initializer is specified for an object, the object is
12749     //   default-initialized; [...].
12750     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12751     InitializationKind Kind
12752       = InitializationKind::CreateDefault(Var->getLocation());
12753 
12754     InitializationSequence InitSeq(*this, Entity, Kind, None);
12755     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12756 
12757     if (Init.get()) {
12758       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12759       // This is important for template substitution.
12760       Var->setInitStyle(VarDecl::CallInit);
12761     } else if (Init.isInvalid()) {
12762       // If default-init fails, attach a recovery-expr initializer to track
12763       // that initialization was attempted and failed.
12764       auto RecoveryExpr =
12765           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12766       if (RecoveryExpr.get())
12767         Var->setInit(RecoveryExpr.get());
12768     }
12769 
12770     CheckCompleteVariableDeclaration(Var);
12771   }
12772 }
12773 
12774 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12775   // If there is no declaration, there was an error parsing it. Ignore it.
12776   if (!D)
12777     return;
12778 
12779   VarDecl *VD = dyn_cast<VarDecl>(D);
12780   if (!VD) {
12781     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12782     D->setInvalidDecl();
12783     return;
12784   }
12785 
12786   VD->setCXXForRangeDecl(true);
12787 
12788   // for-range-declaration cannot be given a storage class specifier.
12789   int Error = -1;
12790   switch (VD->getStorageClass()) {
12791   case SC_None:
12792     break;
12793   case SC_Extern:
12794     Error = 0;
12795     break;
12796   case SC_Static:
12797     Error = 1;
12798     break;
12799   case SC_PrivateExtern:
12800     Error = 2;
12801     break;
12802   case SC_Auto:
12803     Error = 3;
12804     break;
12805   case SC_Register:
12806     Error = 4;
12807     break;
12808   }
12809 
12810   // for-range-declaration cannot be given a storage class specifier con't.
12811   switch (VD->getTSCSpec()) {
12812   case TSCS_thread_local:
12813     Error = 6;
12814     break;
12815   case TSCS___thread:
12816   case TSCS__Thread_local:
12817   case TSCS_unspecified:
12818     break;
12819   }
12820 
12821   if (Error != -1) {
12822     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12823         << VD << Error;
12824     D->setInvalidDecl();
12825   }
12826 }
12827 
12828 StmtResult
12829 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12830                                  IdentifierInfo *Ident,
12831                                  ParsedAttributes &Attrs,
12832                                  SourceLocation AttrEnd) {
12833   // C++1y [stmt.iter]p1:
12834   //   A range-based for statement of the form
12835   //      for ( for-range-identifier : for-range-initializer ) statement
12836   //   is equivalent to
12837   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12838   DeclSpec DS(Attrs.getPool().getFactory());
12839 
12840   const char *PrevSpec;
12841   unsigned DiagID;
12842   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12843                      getPrintingPolicy());
12844 
12845   Declarator D(DS, DeclaratorContext::ForInit);
12846   D.SetIdentifier(Ident, IdentLoc);
12847   D.takeAttributes(Attrs, AttrEnd);
12848 
12849   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12850                 IdentLoc);
12851   Decl *Var = ActOnDeclarator(S, D);
12852   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12853   FinalizeDeclaration(Var);
12854   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12855                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12856 }
12857 
12858 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12859   if (var->isInvalidDecl()) return;
12860 
12861   if (getLangOpts().OpenCL) {
12862     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12863     // initialiser
12864     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12865         !var->hasInit()) {
12866       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12867           << 1 /*Init*/;
12868       var->setInvalidDecl();
12869       return;
12870     }
12871   }
12872 
12873   // In Objective-C, don't allow jumps past the implicit initialization of a
12874   // local retaining variable.
12875   if (getLangOpts().ObjC &&
12876       var->hasLocalStorage()) {
12877     switch (var->getType().getObjCLifetime()) {
12878     case Qualifiers::OCL_None:
12879     case Qualifiers::OCL_ExplicitNone:
12880     case Qualifiers::OCL_Autoreleasing:
12881       break;
12882 
12883     case Qualifiers::OCL_Weak:
12884     case Qualifiers::OCL_Strong:
12885       setFunctionHasBranchProtectedScope();
12886       break;
12887     }
12888   }
12889 
12890   if (var->hasLocalStorage() &&
12891       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12892     setFunctionHasBranchProtectedScope();
12893 
12894   // Warn about externally-visible variables being defined without a
12895   // prior declaration.  We only want to do this for global
12896   // declarations, but we also specifically need to avoid doing it for
12897   // class members because the linkage of an anonymous class can
12898   // change if it's later given a typedef name.
12899   if (var->isThisDeclarationADefinition() &&
12900       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12901       var->isExternallyVisible() && var->hasLinkage() &&
12902       !var->isInline() && !var->getDescribedVarTemplate() &&
12903       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12904       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12905       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12906                                   var->getLocation())) {
12907     // Find a previous declaration that's not a definition.
12908     VarDecl *prev = var->getPreviousDecl();
12909     while (prev && prev->isThisDeclarationADefinition())
12910       prev = prev->getPreviousDecl();
12911 
12912     if (!prev) {
12913       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12914       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12915           << /* variable */ 0;
12916     }
12917   }
12918 
12919   // Cache the result of checking for constant initialization.
12920   Optional<bool> CacheHasConstInit;
12921   const Expr *CacheCulprit = nullptr;
12922   auto checkConstInit = [&]() mutable {
12923     if (!CacheHasConstInit)
12924       CacheHasConstInit = var->getInit()->isConstantInitializer(
12925             Context, var->getType()->isReferenceType(), &CacheCulprit);
12926     return *CacheHasConstInit;
12927   };
12928 
12929   if (var->getTLSKind() == VarDecl::TLS_Static) {
12930     if (var->getType().isDestructedType()) {
12931       // GNU C++98 edits for __thread, [basic.start.term]p3:
12932       //   The type of an object with thread storage duration shall not
12933       //   have a non-trivial destructor.
12934       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12935       if (getLangOpts().CPlusPlus11)
12936         Diag(var->getLocation(), diag::note_use_thread_local);
12937     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12938       if (!checkConstInit()) {
12939         // GNU C++98 edits for __thread, [basic.start.init]p4:
12940         //   An object of thread storage duration shall not require dynamic
12941         //   initialization.
12942         // FIXME: Need strict checking here.
12943         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12944           << CacheCulprit->getSourceRange();
12945         if (getLangOpts().CPlusPlus11)
12946           Diag(var->getLocation(), diag::note_use_thread_local);
12947       }
12948     }
12949   }
12950 
12951   // Apply section attributes and pragmas to global variables.
12952   bool GlobalStorage = var->hasGlobalStorage();
12953   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12954       !inTemplateInstantiation()) {
12955     PragmaStack<StringLiteral *> *Stack = nullptr;
12956     int SectionFlags = ASTContext::PSF_Read;
12957     if (var->getType().isConstQualified())
12958       Stack = &ConstSegStack;
12959     else if (!var->getInit()) {
12960       Stack = &BSSSegStack;
12961       SectionFlags |= ASTContext::PSF_Write;
12962     } else {
12963       Stack = &DataSegStack;
12964       SectionFlags |= ASTContext::PSF_Write;
12965     }
12966     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12967       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12968         SectionFlags |= ASTContext::PSF_Implicit;
12969       UnifySection(SA->getName(), SectionFlags, var);
12970     } else if (Stack->CurrentValue) {
12971       SectionFlags |= ASTContext::PSF_Implicit;
12972       auto SectionName = Stack->CurrentValue->getString();
12973       var->addAttr(SectionAttr::CreateImplicit(
12974           Context, SectionName, Stack->CurrentPragmaLocation,
12975           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12976       if (UnifySection(SectionName, SectionFlags, var))
12977         var->dropAttr<SectionAttr>();
12978     }
12979 
12980     // Apply the init_seg attribute if this has an initializer.  If the
12981     // initializer turns out to not be dynamic, we'll end up ignoring this
12982     // attribute.
12983     if (CurInitSeg && var->getInit())
12984       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12985                                                CurInitSegLoc,
12986                                                AttributeCommonInfo::AS_Pragma));
12987   }
12988 
12989   if (!var->getType()->isStructureType() && var->hasInit() &&
12990       isa<InitListExpr>(var->getInit())) {
12991     const auto *ILE = cast<InitListExpr>(var->getInit());
12992     unsigned NumInits = ILE->getNumInits();
12993     if (NumInits > 2)
12994       for (unsigned I = 0; I < NumInits; ++I) {
12995         const auto *Init = ILE->getInit(I);
12996         if (!Init)
12997           break;
12998         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12999         if (!SL)
13000           break;
13001 
13002         unsigned NumConcat = SL->getNumConcatenated();
13003         // Diagnose missing comma in string array initialization.
13004         // Do not warn when all the elements in the initializer are concatenated
13005         // together. Do not warn for macros too.
13006         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13007           bool OnlyOneMissingComma = true;
13008           for (unsigned J = I + 1; J < NumInits; ++J) {
13009             const auto *Init = ILE->getInit(J);
13010             if (!Init)
13011               break;
13012             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13013             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13014               OnlyOneMissingComma = false;
13015               break;
13016             }
13017           }
13018 
13019           if (OnlyOneMissingComma) {
13020             SmallVector<FixItHint, 1> Hints;
13021             for (unsigned i = 0; i < NumConcat - 1; ++i)
13022               Hints.push_back(FixItHint::CreateInsertion(
13023                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13024 
13025             Diag(SL->getStrTokenLoc(1),
13026                  diag::warn_concatenated_literal_array_init)
13027                 << Hints;
13028             Diag(SL->getBeginLoc(),
13029                  diag::note_concatenated_string_literal_silence);
13030           }
13031           // In any case, stop now.
13032           break;
13033         }
13034       }
13035   }
13036 
13037   // All the following checks are C++ only.
13038   if (!getLangOpts().CPlusPlus) {
13039     // If this variable must be emitted, add it as an initializer for the
13040     // current module.
13041     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13042       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13043     return;
13044   }
13045 
13046   QualType type = var->getType();
13047 
13048   if (var->hasAttr<BlocksAttr>())
13049     getCurFunction()->addByrefBlockVar(var);
13050 
13051   Expr *Init = var->getInit();
13052   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13053   QualType baseType = Context.getBaseElementType(type);
13054 
13055   // Check whether the initializer is sufficiently constant.
13056   if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13057       (GlobalStorage || var->isConstexpr() ||
13058        var->mightBeUsableInConstantExpressions(Context))) {
13059     // If this variable might have a constant initializer or might be usable in
13060     // constant expressions, check whether or not it actually is now.  We can't
13061     // do this lazily, because the result might depend on things that change
13062     // later, such as which constexpr functions happen to be defined.
13063     SmallVector<PartialDiagnosticAt, 8> Notes;
13064     bool HasConstInit;
13065     if (!getLangOpts().CPlusPlus11) {
13066       // Prior to C++11, in contexts where a constant initializer is required,
13067       // the set of valid constant initializers is described by syntactic rules
13068       // in [expr.const]p2-6.
13069       // FIXME: Stricter checking for these rules would be useful for constinit /
13070       // -Wglobal-constructors.
13071       HasConstInit = checkConstInit();
13072 
13073       // Compute and cache the constant value, and remember that we have a
13074       // constant initializer.
13075       if (HasConstInit) {
13076         (void)var->checkForConstantInitialization(Notes);
13077         Notes.clear();
13078       } else if (CacheCulprit) {
13079         Notes.emplace_back(CacheCulprit->getExprLoc(),
13080                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13081         Notes.back().second << CacheCulprit->getSourceRange();
13082       }
13083     } else {
13084       // Evaluate the initializer to see if it's a constant initializer.
13085       HasConstInit = var->checkForConstantInitialization(Notes);
13086     }
13087 
13088     if (HasConstInit) {
13089       // FIXME: Consider replacing the initializer with a ConstantExpr.
13090     } else if (var->isConstexpr()) {
13091       SourceLocation DiagLoc = var->getLocation();
13092       // If the note doesn't add any useful information other than a source
13093       // location, fold it into the primary diagnostic.
13094       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13095                                    diag::note_invalid_subexpr_in_const_expr) {
13096         DiagLoc = Notes[0].first;
13097         Notes.clear();
13098       }
13099       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13100           << var << Init->getSourceRange();
13101       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13102         Diag(Notes[I].first, Notes[I].second);
13103     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13104       auto *Attr = var->getAttr<ConstInitAttr>();
13105       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13106           << Init->getSourceRange();
13107       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13108           << Attr->getRange() << Attr->isConstinit();
13109       for (auto &it : Notes)
13110         Diag(it.first, it.second);
13111     } else if (IsGlobal &&
13112                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13113                                            var->getLocation())) {
13114       // Warn about globals which don't have a constant initializer.  Don't
13115       // warn about globals with a non-trivial destructor because we already
13116       // warned about them.
13117       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13118       if (!(RD && !RD->hasTrivialDestructor())) {
13119         // checkConstInit() here permits trivial default initialization even in
13120         // C++11 onwards, where such an initializer is not a constant initializer
13121         // but nonetheless doesn't require a global constructor.
13122         if (!checkConstInit())
13123           Diag(var->getLocation(), diag::warn_global_constructor)
13124               << Init->getSourceRange();
13125       }
13126     }
13127   }
13128 
13129   // Require the destructor.
13130   if (!type->isDependentType())
13131     if (const RecordType *recordType = baseType->getAs<RecordType>())
13132       FinalizeVarWithDestructor(var, recordType);
13133 
13134   // If this variable must be emitted, add it as an initializer for the current
13135   // module.
13136   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13137     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13138 
13139   // Build the bindings if this is a structured binding declaration.
13140   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13141     CheckCompleteDecompositionDeclaration(DD);
13142 }
13143 
13144 /// Determines if a variable's alignment is dependent.
13145 static bool hasDependentAlignment(VarDecl *VD) {
13146   if (VD->getType()->isDependentType())
13147     return true;
13148   for (auto *I : VD->specific_attrs<AlignedAttr>())
13149     if (I->isAlignmentDependent())
13150       return true;
13151   return false;
13152 }
13153 
13154 /// Check if VD needs to be dllexport/dllimport due to being in a
13155 /// dllexport/import function.
13156 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13157   assert(VD->isStaticLocal());
13158 
13159   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13160 
13161   // Find outermost function when VD is in lambda function.
13162   while (FD && !getDLLAttr(FD) &&
13163          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13164          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13165     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13166   }
13167 
13168   if (!FD)
13169     return;
13170 
13171   // Static locals inherit dll attributes from their function.
13172   if (Attr *A = getDLLAttr(FD)) {
13173     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13174     NewAttr->setInherited(true);
13175     VD->addAttr(NewAttr);
13176   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13177     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13178     NewAttr->setInherited(true);
13179     VD->addAttr(NewAttr);
13180 
13181     // Export this function to enforce exporting this static variable even
13182     // if it is not used in this compilation unit.
13183     if (!FD->hasAttr<DLLExportAttr>())
13184       FD->addAttr(NewAttr);
13185 
13186   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13187     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13188     NewAttr->setInherited(true);
13189     VD->addAttr(NewAttr);
13190   }
13191 }
13192 
13193 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13194 /// any semantic actions necessary after any initializer has been attached.
13195 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13196   // Note that we are no longer parsing the initializer for this declaration.
13197   ParsingInitForAutoVars.erase(ThisDecl);
13198 
13199   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13200   if (!VD)
13201     return;
13202 
13203   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13204   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13205       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13206     if (PragmaClangBSSSection.Valid)
13207       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13208           Context, PragmaClangBSSSection.SectionName,
13209           PragmaClangBSSSection.PragmaLocation,
13210           AttributeCommonInfo::AS_Pragma));
13211     if (PragmaClangDataSection.Valid)
13212       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13213           Context, PragmaClangDataSection.SectionName,
13214           PragmaClangDataSection.PragmaLocation,
13215           AttributeCommonInfo::AS_Pragma));
13216     if (PragmaClangRodataSection.Valid)
13217       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13218           Context, PragmaClangRodataSection.SectionName,
13219           PragmaClangRodataSection.PragmaLocation,
13220           AttributeCommonInfo::AS_Pragma));
13221     if (PragmaClangRelroSection.Valid)
13222       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13223           Context, PragmaClangRelroSection.SectionName,
13224           PragmaClangRelroSection.PragmaLocation,
13225           AttributeCommonInfo::AS_Pragma));
13226   }
13227 
13228   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13229     for (auto *BD : DD->bindings()) {
13230       FinalizeDeclaration(BD);
13231     }
13232   }
13233 
13234   checkAttributesAfterMerging(*this, *VD);
13235 
13236   // Perform TLS alignment check here after attributes attached to the variable
13237   // which may affect the alignment have been processed. Only perform the check
13238   // if the target has a maximum TLS alignment (zero means no constraints).
13239   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13240     // Protect the check so that it's not performed on dependent types and
13241     // dependent alignments (we can't determine the alignment in that case).
13242     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13243         !VD->isInvalidDecl()) {
13244       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13245       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13246         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13247           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13248           << (unsigned)MaxAlignChars.getQuantity();
13249       }
13250     }
13251   }
13252 
13253   if (VD->isStaticLocal())
13254     CheckStaticLocalForDllExport(VD);
13255 
13256   // Perform check for initializers of device-side global variables.
13257   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13258   // 7.5). We must also apply the same checks to all __shared__
13259   // variables whether they are local or not. CUDA also allows
13260   // constant initializers for __constant__ and __device__ variables.
13261   if (getLangOpts().CUDA)
13262     checkAllowedCUDAInitializer(VD);
13263 
13264   // Grab the dllimport or dllexport attribute off of the VarDecl.
13265   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13266 
13267   // Imported static data members cannot be defined out-of-line.
13268   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13269     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13270         VD->isThisDeclarationADefinition()) {
13271       // We allow definitions of dllimport class template static data members
13272       // with a warning.
13273       CXXRecordDecl *Context =
13274         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13275       bool IsClassTemplateMember =
13276           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13277           Context->getDescribedClassTemplate();
13278 
13279       Diag(VD->getLocation(),
13280            IsClassTemplateMember
13281                ? diag::warn_attribute_dllimport_static_field_definition
13282                : diag::err_attribute_dllimport_static_field_definition);
13283       Diag(IA->getLocation(), diag::note_attribute);
13284       if (!IsClassTemplateMember)
13285         VD->setInvalidDecl();
13286     }
13287   }
13288 
13289   // dllimport/dllexport variables cannot be thread local, their TLS index
13290   // isn't exported with the variable.
13291   if (DLLAttr && VD->getTLSKind()) {
13292     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13293     if (F && getDLLAttr(F)) {
13294       assert(VD->isStaticLocal());
13295       // But if this is a static local in a dlimport/dllexport function, the
13296       // function will never be inlined, which means the var would never be
13297       // imported, so having it marked import/export is safe.
13298     } else {
13299       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13300                                                                     << DLLAttr;
13301       VD->setInvalidDecl();
13302     }
13303   }
13304 
13305   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13306     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13307       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13308           << Attr;
13309       VD->dropAttr<UsedAttr>();
13310     }
13311   }
13312   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13313     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13314       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13315           << Attr;
13316       VD->dropAttr<RetainAttr>();
13317     }
13318   }
13319 
13320   const DeclContext *DC = VD->getDeclContext();
13321   // If there's a #pragma GCC visibility in scope, and this isn't a class
13322   // member, set the visibility of this variable.
13323   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13324     AddPushedVisibilityAttribute(VD);
13325 
13326   // FIXME: Warn on unused var template partial specializations.
13327   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13328     MarkUnusedFileScopedDecl(VD);
13329 
13330   // Now we have parsed the initializer and can update the table of magic
13331   // tag values.
13332   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13333       !VD->getType()->isIntegralOrEnumerationType())
13334     return;
13335 
13336   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13337     const Expr *MagicValueExpr = VD->getInit();
13338     if (!MagicValueExpr) {
13339       continue;
13340     }
13341     Optional<llvm::APSInt> MagicValueInt;
13342     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13343       Diag(I->getRange().getBegin(),
13344            diag::err_type_tag_for_datatype_not_ice)
13345         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13346       continue;
13347     }
13348     if (MagicValueInt->getActiveBits() > 64) {
13349       Diag(I->getRange().getBegin(),
13350            diag::err_type_tag_for_datatype_too_large)
13351         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13352       continue;
13353     }
13354     uint64_t MagicValue = MagicValueInt->getZExtValue();
13355     RegisterTypeTagForDatatype(I->getArgumentKind(),
13356                                MagicValue,
13357                                I->getMatchingCType(),
13358                                I->getLayoutCompatible(),
13359                                I->getMustBeNull());
13360   }
13361 }
13362 
13363 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13364   auto *VD = dyn_cast<VarDecl>(DD);
13365   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13366 }
13367 
13368 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13369                                                    ArrayRef<Decl *> Group) {
13370   SmallVector<Decl*, 8> Decls;
13371 
13372   if (DS.isTypeSpecOwned())
13373     Decls.push_back(DS.getRepAsDecl());
13374 
13375   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13376   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13377   bool DiagnosedMultipleDecomps = false;
13378   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13379   bool DiagnosedNonDeducedAuto = false;
13380 
13381   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13382     if (Decl *D = Group[i]) {
13383       // For declarators, there are some additional syntactic-ish checks we need
13384       // to perform.
13385       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13386         if (!FirstDeclaratorInGroup)
13387           FirstDeclaratorInGroup = DD;
13388         if (!FirstDecompDeclaratorInGroup)
13389           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13390         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13391             !hasDeducedAuto(DD))
13392           FirstNonDeducedAutoInGroup = DD;
13393 
13394         if (FirstDeclaratorInGroup != DD) {
13395           // A decomposition declaration cannot be combined with any other
13396           // declaration in the same group.
13397           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13398             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13399                  diag::err_decomp_decl_not_alone)
13400                 << FirstDeclaratorInGroup->getSourceRange()
13401                 << DD->getSourceRange();
13402             DiagnosedMultipleDecomps = true;
13403           }
13404 
13405           // A declarator that uses 'auto' in any way other than to declare a
13406           // variable with a deduced type cannot be combined with any other
13407           // declarator in the same group.
13408           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13409             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13410                  diag::err_auto_non_deduced_not_alone)
13411                 << FirstNonDeducedAutoInGroup->getType()
13412                        ->hasAutoForTrailingReturnType()
13413                 << FirstDeclaratorInGroup->getSourceRange()
13414                 << DD->getSourceRange();
13415             DiagnosedNonDeducedAuto = true;
13416           }
13417         }
13418       }
13419 
13420       Decls.push_back(D);
13421     }
13422   }
13423 
13424   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13425     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13426       handleTagNumbering(Tag, S);
13427       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13428           getLangOpts().CPlusPlus)
13429         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13430     }
13431   }
13432 
13433   return BuildDeclaratorGroup(Decls);
13434 }
13435 
13436 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13437 /// group, performing any necessary semantic checking.
13438 Sema::DeclGroupPtrTy
13439 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13440   // C++14 [dcl.spec.auto]p7: (DR1347)
13441   //   If the type that replaces the placeholder type is not the same in each
13442   //   deduction, the program is ill-formed.
13443   if (Group.size() > 1) {
13444     QualType Deduced;
13445     VarDecl *DeducedDecl = nullptr;
13446     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13447       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13448       if (!D || D->isInvalidDecl())
13449         break;
13450       DeducedType *DT = D->getType()->getContainedDeducedType();
13451       if (!DT || DT->getDeducedType().isNull())
13452         continue;
13453       if (Deduced.isNull()) {
13454         Deduced = DT->getDeducedType();
13455         DeducedDecl = D;
13456       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13457         auto *AT = dyn_cast<AutoType>(DT);
13458         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13459                         diag::err_auto_different_deductions)
13460                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13461                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13462                    << D->getDeclName();
13463         if (DeducedDecl->hasInit())
13464           Dia << DeducedDecl->getInit()->getSourceRange();
13465         if (D->getInit())
13466           Dia << D->getInit()->getSourceRange();
13467         D->setInvalidDecl();
13468         break;
13469       }
13470     }
13471   }
13472 
13473   ActOnDocumentableDecls(Group);
13474 
13475   return DeclGroupPtrTy::make(
13476       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13477 }
13478 
13479 void Sema::ActOnDocumentableDecl(Decl *D) {
13480   ActOnDocumentableDecls(D);
13481 }
13482 
13483 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13484   // Don't parse the comment if Doxygen diagnostics are ignored.
13485   if (Group.empty() || !Group[0])
13486     return;
13487 
13488   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13489                       Group[0]->getLocation()) &&
13490       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13491                       Group[0]->getLocation()))
13492     return;
13493 
13494   if (Group.size() >= 2) {
13495     // This is a decl group.  Normally it will contain only declarations
13496     // produced from declarator list.  But in case we have any definitions or
13497     // additional declaration references:
13498     //   'typedef struct S {} S;'
13499     //   'typedef struct S *S;'
13500     //   'struct S *pS;'
13501     // FinalizeDeclaratorGroup adds these as separate declarations.
13502     Decl *MaybeTagDecl = Group[0];
13503     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13504       Group = Group.slice(1);
13505     }
13506   }
13507 
13508   // FIMXE: We assume every Decl in the group is in the same file.
13509   // This is false when preprocessor constructs the group from decls in
13510   // different files (e. g. macros or #include).
13511   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13512 }
13513 
13514 /// Common checks for a parameter-declaration that should apply to both function
13515 /// parameters and non-type template parameters.
13516 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13517   // Check that there are no default arguments inside the type of this
13518   // parameter.
13519   if (getLangOpts().CPlusPlus)
13520     CheckExtraCXXDefaultArguments(D);
13521 
13522   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13523   if (D.getCXXScopeSpec().isSet()) {
13524     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13525       << D.getCXXScopeSpec().getRange();
13526   }
13527 
13528   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13529   // simple identifier except [...irrelevant cases...].
13530   switch (D.getName().getKind()) {
13531   case UnqualifiedIdKind::IK_Identifier:
13532     break;
13533 
13534   case UnqualifiedIdKind::IK_OperatorFunctionId:
13535   case UnqualifiedIdKind::IK_ConversionFunctionId:
13536   case UnqualifiedIdKind::IK_LiteralOperatorId:
13537   case UnqualifiedIdKind::IK_ConstructorName:
13538   case UnqualifiedIdKind::IK_DestructorName:
13539   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13540   case UnqualifiedIdKind::IK_DeductionGuideName:
13541     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13542       << GetNameForDeclarator(D).getName();
13543     break;
13544 
13545   case UnqualifiedIdKind::IK_TemplateId:
13546   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13547     // GetNameForDeclarator would not produce a useful name in this case.
13548     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13549     break;
13550   }
13551 }
13552 
13553 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13554 /// to introduce parameters into function prototype scope.
13555 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13556   const DeclSpec &DS = D.getDeclSpec();
13557 
13558   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13559 
13560   // C++03 [dcl.stc]p2 also permits 'auto'.
13561   StorageClass SC = SC_None;
13562   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13563     SC = SC_Register;
13564     // In C++11, the 'register' storage class specifier is deprecated.
13565     // In C++17, it is not allowed, but we tolerate it as an extension.
13566     if (getLangOpts().CPlusPlus11) {
13567       Diag(DS.getStorageClassSpecLoc(),
13568            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13569                                      : diag::warn_deprecated_register)
13570         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13571     }
13572   } else if (getLangOpts().CPlusPlus &&
13573              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13574     SC = SC_Auto;
13575   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13576     Diag(DS.getStorageClassSpecLoc(),
13577          diag::err_invalid_storage_class_in_func_decl);
13578     D.getMutableDeclSpec().ClearStorageClassSpecs();
13579   }
13580 
13581   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13582     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13583       << DeclSpec::getSpecifierName(TSCS);
13584   if (DS.isInlineSpecified())
13585     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13586         << getLangOpts().CPlusPlus17;
13587   if (DS.hasConstexprSpecifier())
13588     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13589         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13590 
13591   DiagnoseFunctionSpecifiers(DS);
13592 
13593   CheckFunctionOrTemplateParamDeclarator(S, D);
13594 
13595   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13596   QualType parmDeclType = TInfo->getType();
13597 
13598   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13599   IdentifierInfo *II = D.getIdentifier();
13600   if (II) {
13601     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13602                    ForVisibleRedeclaration);
13603     LookupName(R, S);
13604     if (R.isSingleResult()) {
13605       NamedDecl *PrevDecl = R.getFoundDecl();
13606       if (PrevDecl->isTemplateParameter()) {
13607         // Maybe we will complain about the shadowed template parameter.
13608         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13609         // Just pretend that we didn't see the previous declaration.
13610         PrevDecl = nullptr;
13611       } else if (S->isDeclScope(PrevDecl)) {
13612         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13613         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13614 
13615         // Recover by removing the name
13616         II = nullptr;
13617         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13618         D.setInvalidType(true);
13619       }
13620     }
13621   }
13622 
13623   // Temporarily put parameter variables in the translation unit, not
13624   // the enclosing context.  This prevents them from accidentally
13625   // looking like class members in C++.
13626   ParmVarDecl *New =
13627       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13628                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13629 
13630   if (D.isInvalidType())
13631     New->setInvalidDecl();
13632 
13633   assert(S->isFunctionPrototypeScope());
13634   assert(S->getFunctionPrototypeDepth() >= 1);
13635   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13636                     S->getNextFunctionPrototypeIndex());
13637 
13638   // Add the parameter declaration into this scope.
13639   S->AddDecl(New);
13640   if (II)
13641     IdResolver.AddDecl(New);
13642 
13643   ProcessDeclAttributes(S, New, D);
13644 
13645   if (D.getDeclSpec().isModulePrivateSpecified())
13646     Diag(New->getLocation(), diag::err_module_private_local)
13647         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13648         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13649 
13650   if (New->hasAttr<BlocksAttr>()) {
13651     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13652   }
13653 
13654   if (getLangOpts().OpenCL)
13655     deduceOpenCLAddressSpace(New);
13656 
13657   return New;
13658 }
13659 
13660 /// Synthesizes a variable for a parameter arising from a
13661 /// typedef.
13662 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13663                                               SourceLocation Loc,
13664                                               QualType T) {
13665   /* FIXME: setting StartLoc == Loc.
13666      Would it be worth to modify callers so as to provide proper source
13667      location for the unnamed parameters, embedding the parameter's type? */
13668   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13669                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13670                                            SC_None, nullptr);
13671   Param->setImplicit();
13672   return Param;
13673 }
13674 
13675 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13676   // Don't diagnose unused-parameter errors in template instantiations; we
13677   // will already have done so in the template itself.
13678   if (inTemplateInstantiation())
13679     return;
13680 
13681   for (const ParmVarDecl *Parameter : Parameters) {
13682     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13683         !Parameter->hasAttr<UnusedAttr>()) {
13684       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13685         << Parameter->getDeclName();
13686     }
13687   }
13688 }
13689 
13690 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13691     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13692   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13693     return;
13694 
13695   // Warn if the return value is pass-by-value and larger than the specified
13696   // threshold.
13697   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13698     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13699     if (Size > LangOpts.NumLargeByValueCopy)
13700       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13701   }
13702 
13703   // Warn if any parameter is pass-by-value and larger than the specified
13704   // threshold.
13705   for (const ParmVarDecl *Parameter : Parameters) {
13706     QualType T = Parameter->getType();
13707     if (T->isDependentType() || !T.isPODType(Context))
13708       continue;
13709     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13710     if (Size > LangOpts.NumLargeByValueCopy)
13711       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13712           << Parameter << Size;
13713   }
13714 }
13715 
13716 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13717                                   SourceLocation NameLoc, IdentifierInfo *Name,
13718                                   QualType T, TypeSourceInfo *TSInfo,
13719                                   StorageClass SC) {
13720   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13721   if (getLangOpts().ObjCAutoRefCount &&
13722       T.getObjCLifetime() == Qualifiers::OCL_None &&
13723       T->isObjCLifetimeType()) {
13724 
13725     Qualifiers::ObjCLifetime lifetime;
13726 
13727     // Special cases for arrays:
13728     //   - if it's const, use __unsafe_unretained
13729     //   - otherwise, it's an error
13730     if (T->isArrayType()) {
13731       if (!T.isConstQualified()) {
13732         if (DelayedDiagnostics.shouldDelayDiagnostics())
13733           DelayedDiagnostics.add(
13734               sema::DelayedDiagnostic::makeForbiddenType(
13735               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13736         else
13737           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13738               << TSInfo->getTypeLoc().getSourceRange();
13739       }
13740       lifetime = Qualifiers::OCL_ExplicitNone;
13741     } else {
13742       lifetime = T->getObjCARCImplicitLifetime();
13743     }
13744     T = Context.getLifetimeQualifiedType(T, lifetime);
13745   }
13746 
13747   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13748                                          Context.getAdjustedParameterType(T),
13749                                          TSInfo, SC, nullptr);
13750 
13751   // Make a note if we created a new pack in the scope of a lambda, so that
13752   // we know that references to that pack must also be expanded within the
13753   // lambda scope.
13754   if (New->isParameterPack())
13755     if (auto *LSI = getEnclosingLambda())
13756       LSI->LocalPacks.push_back(New);
13757 
13758   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13759       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13760     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13761                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13762 
13763   // Parameters can not be abstract class types.
13764   // For record types, this is done by the AbstractClassUsageDiagnoser once
13765   // the class has been completely parsed.
13766   if (!CurContext->isRecord() &&
13767       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13768                              AbstractParamType))
13769     New->setInvalidDecl();
13770 
13771   // Parameter declarators cannot be interface types. All ObjC objects are
13772   // passed by reference.
13773   if (T->isObjCObjectType()) {
13774     SourceLocation TypeEndLoc =
13775         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13776     Diag(NameLoc,
13777          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13778       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13779     T = Context.getObjCObjectPointerType(T);
13780     New->setType(T);
13781   }
13782 
13783   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13784   // duration shall not be qualified by an address-space qualifier."
13785   // Since all parameters have automatic store duration, they can not have
13786   // an address space.
13787   if (T.getAddressSpace() != LangAS::Default &&
13788       // OpenCL allows function arguments declared to be an array of a type
13789       // to be qualified with an address space.
13790       !(getLangOpts().OpenCL &&
13791         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13792     Diag(NameLoc, diag::err_arg_with_address_space);
13793     New->setInvalidDecl();
13794   }
13795 
13796   // PPC MMA non-pointer types are not allowed as function argument types.
13797   if (Context.getTargetInfo().getTriple().isPPC64() &&
13798       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13799     New->setInvalidDecl();
13800   }
13801 
13802   return New;
13803 }
13804 
13805 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13806                                            SourceLocation LocAfterDecls) {
13807   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13808 
13809   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13810   // for a K&R function.
13811   if (!FTI.hasPrototype) {
13812     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13813       --i;
13814       if (FTI.Params[i].Param == nullptr) {
13815         SmallString<256> Code;
13816         llvm::raw_svector_ostream(Code)
13817             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13818         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13819             << FTI.Params[i].Ident
13820             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13821 
13822         // Implicitly declare the argument as type 'int' for lack of a better
13823         // type.
13824         AttributeFactory attrs;
13825         DeclSpec DS(attrs);
13826         const char* PrevSpec; // unused
13827         unsigned DiagID; // unused
13828         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13829                            DiagID, Context.getPrintingPolicy());
13830         // Use the identifier location for the type source range.
13831         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13832         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13833         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13834         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13835         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13836       }
13837     }
13838   }
13839 }
13840 
13841 Decl *
13842 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13843                               MultiTemplateParamsArg TemplateParameterLists,
13844                               SkipBodyInfo *SkipBody) {
13845   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13846   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13847   Scope *ParentScope = FnBodyScope->getParent();
13848 
13849   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13850   // we define a non-templated function definition, we will create a declaration
13851   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13852   // The base function declaration will have the equivalent of an `omp declare
13853   // variant` annotation which specifies the mangled definition as a
13854   // specialization function under the OpenMP context defined as part of the
13855   // `omp begin declare variant`.
13856   SmallVector<FunctionDecl *, 4> Bases;
13857   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13858     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13859         ParentScope, D, TemplateParameterLists, Bases);
13860 
13861   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13862   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13863   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13864 
13865   if (!Bases.empty())
13866     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13867 
13868   return Dcl;
13869 }
13870 
13871 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13872   Consumer.HandleInlineFunctionDefinition(D);
13873 }
13874 
13875 static bool
13876 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13877                                 const FunctionDecl *&PossiblePrototype) {
13878   // Don't warn about invalid declarations.
13879   if (FD->isInvalidDecl())
13880     return false;
13881 
13882   // Or declarations that aren't global.
13883   if (!FD->isGlobal())
13884     return false;
13885 
13886   // Don't warn about C++ member functions.
13887   if (isa<CXXMethodDecl>(FD))
13888     return false;
13889 
13890   // Don't warn about 'main'.
13891   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13892     if (IdentifierInfo *II = FD->getIdentifier())
13893       if (II->isStr("main") || II->isStr("efi_main"))
13894         return false;
13895 
13896   // Don't warn about inline functions.
13897   if (FD->isInlined())
13898     return false;
13899 
13900   // Don't warn about function templates.
13901   if (FD->getDescribedFunctionTemplate())
13902     return false;
13903 
13904   // Don't warn about function template specializations.
13905   if (FD->isFunctionTemplateSpecialization())
13906     return false;
13907 
13908   // Don't warn for OpenCL kernels.
13909   if (FD->hasAttr<OpenCLKernelAttr>())
13910     return false;
13911 
13912   // Don't warn on explicitly deleted functions.
13913   if (FD->isDeleted())
13914     return false;
13915 
13916   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13917        Prev; Prev = Prev->getPreviousDecl()) {
13918     // Ignore any declarations that occur in function or method
13919     // scope, because they aren't visible from the header.
13920     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13921       continue;
13922 
13923     PossiblePrototype = Prev;
13924     return Prev->getType()->isFunctionNoProtoType();
13925   }
13926 
13927   return true;
13928 }
13929 
13930 void
13931 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13932                                    const FunctionDecl *EffectiveDefinition,
13933                                    SkipBodyInfo *SkipBody) {
13934   const FunctionDecl *Definition = EffectiveDefinition;
13935   if (!Definition &&
13936       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
13937     return;
13938 
13939   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
13940     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
13941       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13942         // A merged copy of the same function, instantiated as a member of
13943         // the same class, is OK.
13944         if (declaresSameEntity(OrigFD, OrigDef) &&
13945             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
13946                                cast<Decl>(FD->getLexicalDeclContext())))
13947           return;
13948       }
13949     }
13950   }
13951 
13952   if (canRedefineFunction(Definition, getLangOpts()))
13953     return;
13954 
13955   // Don't emit an error when this is redefinition of a typo-corrected
13956   // definition.
13957   if (TypoCorrectedFunctionDefinitions.count(Definition))
13958     return;
13959 
13960   // If we don't have a visible definition of the function, and it's inline or
13961   // a template, skip the new definition.
13962   if (SkipBody && !hasVisibleDefinition(Definition) &&
13963       (Definition->getFormalLinkage() == InternalLinkage ||
13964        Definition->isInlined() ||
13965        Definition->getDescribedFunctionTemplate() ||
13966        Definition->getNumTemplateParameterLists())) {
13967     SkipBody->ShouldSkip = true;
13968     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13969     if (auto *TD = Definition->getDescribedFunctionTemplate())
13970       makeMergedDefinitionVisible(TD);
13971     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13972     return;
13973   }
13974 
13975   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13976       Definition->getStorageClass() == SC_Extern)
13977     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13978         << FD << getLangOpts().CPlusPlus;
13979   else
13980     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13981 
13982   Diag(Definition->getLocation(), diag::note_previous_definition);
13983   FD->setInvalidDecl();
13984 }
13985 
13986 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13987                                    Sema &S) {
13988   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13989 
13990   LambdaScopeInfo *LSI = S.PushLambdaScope();
13991   LSI->CallOperator = CallOperator;
13992   LSI->Lambda = LambdaClass;
13993   LSI->ReturnType = CallOperator->getReturnType();
13994   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13995 
13996   if (LCD == LCD_None)
13997     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13998   else if (LCD == LCD_ByCopy)
13999     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14000   else if (LCD == LCD_ByRef)
14001     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14002   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14003 
14004   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14005   LSI->Mutable = !CallOperator->isConst();
14006 
14007   // Add the captures to the LSI so they can be noted as already
14008   // captured within tryCaptureVar.
14009   auto I = LambdaClass->field_begin();
14010   for (const auto &C : LambdaClass->captures()) {
14011     if (C.capturesVariable()) {
14012       VarDecl *VD = C.getCapturedVar();
14013       if (VD->isInitCapture())
14014         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14015       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14016       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14017           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14018           /*EllipsisLoc*/C.isPackExpansion()
14019                          ? C.getEllipsisLoc() : SourceLocation(),
14020           I->getType(), /*Invalid*/false);
14021 
14022     } else if (C.capturesThis()) {
14023       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14024                           C.getCaptureKind() == LCK_StarThis);
14025     } else {
14026       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14027                              I->getType());
14028     }
14029     ++I;
14030   }
14031 }
14032 
14033 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14034                                     SkipBodyInfo *SkipBody) {
14035   if (!D) {
14036     // Parsing the function declaration failed in some way. Push on a fake scope
14037     // anyway so we can try to parse the function body.
14038     PushFunctionScope();
14039     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14040     return D;
14041   }
14042 
14043   FunctionDecl *FD = nullptr;
14044 
14045   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14046     FD = FunTmpl->getTemplatedDecl();
14047   else
14048     FD = cast<FunctionDecl>(D);
14049 
14050   // Do not push if it is a lambda because one is already pushed when building
14051   // the lambda in ActOnStartOfLambdaDefinition().
14052   if (!isLambdaCallOperator(FD))
14053     PushExpressionEvaluationContext(
14054         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14055                           : ExprEvalContexts.back().Context);
14056 
14057   // Check for defining attributes before the check for redefinition.
14058   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14059     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14060     FD->dropAttr<AliasAttr>();
14061     FD->setInvalidDecl();
14062   }
14063   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14064     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14065     FD->dropAttr<IFuncAttr>();
14066     FD->setInvalidDecl();
14067   }
14068 
14069   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14070     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14071         Ctor->isDefaultConstructor() &&
14072         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14073       // If this is an MS ABI dllexport default constructor, instantiate any
14074       // default arguments.
14075       InstantiateDefaultCtorDefaultArgs(Ctor);
14076     }
14077   }
14078 
14079   // See if this is a redefinition. If 'will have body' (or similar) is already
14080   // set, then these checks were already performed when it was set.
14081   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14082       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14083     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14084 
14085     // If we're skipping the body, we're done. Don't enter the scope.
14086     if (SkipBody && SkipBody->ShouldSkip)
14087       return D;
14088   }
14089 
14090   // Mark this function as "will have a body eventually".  This lets users to
14091   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14092   // this function.
14093   FD->setWillHaveBody();
14094 
14095   // If we are instantiating a generic lambda call operator, push
14096   // a LambdaScopeInfo onto the function stack.  But use the information
14097   // that's already been calculated (ActOnLambdaExpr) to prime the current
14098   // LambdaScopeInfo.
14099   // When the template operator is being specialized, the LambdaScopeInfo,
14100   // has to be properly restored so that tryCaptureVariable doesn't try
14101   // and capture any new variables. In addition when calculating potential
14102   // captures during transformation of nested lambdas, it is necessary to
14103   // have the LSI properly restored.
14104   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14105     assert(inTemplateInstantiation() &&
14106            "There should be an active template instantiation on the stack "
14107            "when instantiating a generic lambda!");
14108     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14109   } else {
14110     // Enter a new function scope
14111     PushFunctionScope();
14112   }
14113 
14114   // Builtin functions cannot be defined.
14115   if (unsigned BuiltinID = FD->getBuiltinID()) {
14116     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14117         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14118       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14119       FD->setInvalidDecl();
14120     }
14121   }
14122 
14123   // The return type of a function definition must be complete
14124   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14125   QualType ResultType = FD->getReturnType();
14126   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14127       !FD->isInvalidDecl() &&
14128       RequireCompleteType(FD->getLocation(), ResultType,
14129                           diag::err_func_def_incomplete_result))
14130     FD->setInvalidDecl();
14131 
14132   if (FnBodyScope)
14133     PushDeclContext(FnBodyScope, FD);
14134 
14135   // Check the validity of our function parameters
14136   CheckParmsForFunctionDef(FD->parameters(),
14137                            /*CheckParameterNames=*/true);
14138 
14139   // Add non-parameter declarations already in the function to the current
14140   // scope.
14141   if (FnBodyScope) {
14142     for (Decl *NPD : FD->decls()) {
14143       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14144       if (!NonParmDecl)
14145         continue;
14146       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14147              "parameters should not be in newly created FD yet");
14148 
14149       // If the decl has a name, make it accessible in the current scope.
14150       if (NonParmDecl->getDeclName())
14151         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14152 
14153       // Similarly, dive into enums and fish their constants out, making them
14154       // accessible in this scope.
14155       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14156         for (auto *EI : ED->enumerators())
14157           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14158       }
14159     }
14160   }
14161 
14162   // Introduce our parameters into the function scope
14163   for (auto Param : FD->parameters()) {
14164     Param->setOwningFunction(FD);
14165 
14166     // If this has an identifier, add it to the scope stack.
14167     if (Param->getIdentifier() && FnBodyScope) {
14168       CheckShadow(FnBodyScope, Param);
14169 
14170       PushOnScopeChains(Param, FnBodyScope);
14171     }
14172   }
14173 
14174   // Ensure that the function's exception specification is instantiated.
14175   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14176     ResolveExceptionSpec(D->getLocation(), FPT);
14177 
14178   // dllimport cannot be applied to non-inline function definitions.
14179   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14180       !FD->isTemplateInstantiation()) {
14181     assert(!FD->hasAttr<DLLExportAttr>());
14182     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14183     FD->setInvalidDecl();
14184     return D;
14185   }
14186   // We want to attach documentation to original Decl (which might be
14187   // a function template).
14188   ActOnDocumentableDecl(D);
14189   if (getCurLexicalContext()->isObjCContainer() &&
14190       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14191       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14192     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14193 
14194   return D;
14195 }
14196 
14197 /// Given the set of return statements within a function body,
14198 /// compute the variables that are subject to the named return value
14199 /// optimization.
14200 ///
14201 /// Each of the variables that is subject to the named return value
14202 /// optimization will be marked as NRVO variables in the AST, and any
14203 /// return statement that has a marked NRVO variable as its NRVO candidate can
14204 /// use the named return value optimization.
14205 ///
14206 /// This function applies a very simplistic algorithm for NRVO: if every return
14207 /// statement in the scope of a variable has the same NRVO candidate, that
14208 /// candidate is an NRVO variable.
14209 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14210   ReturnStmt **Returns = Scope->Returns.data();
14211 
14212   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14213     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14214       if (!NRVOCandidate->isNRVOVariable())
14215         Returns[I]->setNRVOCandidate(nullptr);
14216     }
14217   }
14218 }
14219 
14220 bool Sema::canDelayFunctionBody(const Declarator &D) {
14221   // We can't delay parsing the body of a constexpr function template (yet).
14222   if (D.getDeclSpec().hasConstexprSpecifier())
14223     return false;
14224 
14225   // We can't delay parsing the body of a function template with a deduced
14226   // return type (yet).
14227   if (D.getDeclSpec().hasAutoTypeSpec()) {
14228     // If the placeholder introduces a non-deduced trailing return type,
14229     // we can still delay parsing it.
14230     if (D.getNumTypeObjects()) {
14231       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14232       if (Outer.Kind == DeclaratorChunk::Function &&
14233           Outer.Fun.hasTrailingReturnType()) {
14234         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14235         return Ty.isNull() || !Ty->isUndeducedType();
14236       }
14237     }
14238     return false;
14239   }
14240 
14241   return true;
14242 }
14243 
14244 bool Sema::canSkipFunctionBody(Decl *D) {
14245   // We cannot skip the body of a function (or function template) which is
14246   // constexpr, since we may need to evaluate its body in order to parse the
14247   // rest of the file.
14248   // We cannot skip the body of a function with an undeduced return type,
14249   // because any callers of that function need to know the type.
14250   if (const FunctionDecl *FD = D->getAsFunction()) {
14251     if (FD->isConstexpr())
14252       return false;
14253     // We can't simply call Type::isUndeducedType here, because inside template
14254     // auto can be deduced to a dependent type, which is not considered
14255     // "undeduced".
14256     if (FD->getReturnType()->getContainedDeducedType())
14257       return false;
14258   }
14259   return Consumer.shouldSkipFunctionBody(D);
14260 }
14261 
14262 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14263   if (!Decl)
14264     return nullptr;
14265   if (FunctionDecl *FD = Decl->getAsFunction())
14266     FD->setHasSkippedBody();
14267   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14268     MD->setHasSkippedBody();
14269   return Decl;
14270 }
14271 
14272 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14273   return ActOnFinishFunctionBody(D, BodyArg, false);
14274 }
14275 
14276 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14277 /// body.
14278 class ExitFunctionBodyRAII {
14279 public:
14280   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14281   ~ExitFunctionBodyRAII() {
14282     if (!IsLambda)
14283       S.PopExpressionEvaluationContext();
14284   }
14285 
14286 private:
14287   Sema &S;
14288   bool IsLambda = false;
14289 };
14290 
14291 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14292   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14293 
14294   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14295     if (EscapeInfo.count(BD))
14296       return EscapeInfo[BD];
14297 
14298     bool R = false;
14299     const BlockDecl *CurBD = BD;
14300 
14301     do {
14302       R = !CurBD->doesNotEscape();
14303       if (R)
14304         break;
14305       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14306     } while (CurBD);
14307 
14308     return EscapeInfo[BD] = R;
14309   };
14310 
14311   // If the location where 'self' is implicitly retained is inside a escaping
14312   // block, emit a diagnostic.
14313   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14314        S.ImplicitlyRetainedSelfLocs)
14315     if (IsOrNestedInEscapingBlock(P.second))
14316       S.Diag(P.first, diag::warn_implicitly_retains_self)
14317           << FixItHint::CreateInsertion(P.first, "self->");
14318 }
14319 
14320 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14321                                     bool IsInstantiation) {
14322   FunctionScopeInfo *FSI = getCurFunction();
14323   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14324 
14325   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14326     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14327 
14328   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14329   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14330 
14331   if (getLangOpts().Coroutines && FSI->isCoroutine())
14332     CheckCompletedCoroutineBody(FD, Body);
14333 
14334   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14335   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14336   // meant to pop the context added in ActOnStartOfFunctionDef().
14337   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14338 
14339   if (FD) {
14340     FD->setBody(Body);
14341     FD->setWillHaveBody(false);
14342 
14343     if (getLangOpts().CPlusPlus14) {
14344       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14345           FD->getReturnType()->isUndeducedType()) {
14346         // If the function has a deduced result type but contains no 'return'
14347         // statements, the result type as written must be exactly 'auto', and
14348         // the deduced result type is 'void'.
14349         if (!FD->getReturnType()->getAs<AutoType>()) {
14350           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14351               << FD->getReturnType();
14352           FD->setInvalidDecl();
14353         } else {
14354           // Substitute 'void' for the 'auto' in the type.
14355           TypeLoc ResultType = getReturnTypeLoc(FD);
14356           Context.adjustDeducedFunctionResultType(
14357               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14358         }
14359       }
14360     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14361       // In C++11, we don't use 'auto' deduction rules for lambda call
14362       // operators because we don't support return type deduction.
14363       auto *LSI = getCurLambda();
14364       if (LSI->HasImplicitReturnType) {
14365         deduceClosureReturnType(*LSI);
14366 
14367         // C++11 [expr.prim.lambda]p4:
14368         //   [...] if there are no return statements in the compound-statement
14369         //   [the deduced type is] the type void
14370         QualType RetType =
14371             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14372 
14373         // Update the return type to the deduced type.
14374         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14375         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14376                                             Proto->getExtProtoInfo()));
14377       }
14378     }
14379 
14380     // If the function implicitly returns zero (like 'main') or is naked,
14381     // don't complain about missing return statements.
14382     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14383       WP.disableCheckFallThrough();
14384 
14385     // MSVC permits the use of pure specifier (=0) on function definition,
14386     // defined at class scope, warn about this non-standard construct.
14387     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14388       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14389 
14390     if (!FD->isInvalidDecl()) {
14391       // Don't diagnose unused parameters of defaulted or deleted functions.
14392       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14393         DiagnoseUnusedParameters(FD->parameters());
14394       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14395                                              FD->getReturnType(), FD);
14396 
14397       // If this is a structor, we need a vtable.
14398       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14399         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14400       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14401         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14402 
14403       // Try to apply the named return value optimization. We have to check
14404       // if we can do this here because lambdas keep return statements around
14405       // to deduce an implicit return type.
14406       if (FD->getReturnType()->isRecordType() &&
14407           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14408         computeNRVO(Body, FSI);
14409     }
14410 
14411     // GNU warning -Wmissing-prototypes:
14412     //   Warn if a global function is defined without a previous
14413     //   prototype declaration. This warning is issued even if the
14414     //   definition itself provides a prototype. The aim is to detect
14415     //   global functions that fail to be declared in header files.
14416     const FunctionDecl *PossiblePrototype = nullptr;
14417     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14418       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14419 
14420       if (PossiblePrototype) {
14421         // We found a declaration that is not a prototype,
14422         // but that could be a zero-parameter prototype
14423         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14424           TypeLoc TL = TI->getTypeLoc();
14425           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14426             Diag(PossiblePrototype->getLocation(),
14427                  diag::note_declaration_not_a_prototype)
14428                 << (FD->getNumParams() != 0)
14429                 << (FD->getNumParams() == 0
14430                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14431                         : FixItHint{});
14432         }
14433       } else {
14434         // Returns true if the token beginning at this Loc is `const`.
14435         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14436                                 const LangOptions &LangOpts) {
14437           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14438           if (LocInfo.first.isInvalid())
14439             return false;
14440 
14441           bool Invalid = false;
14442           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14443           if (Invalid)
14444             return false;
14445 
14446           if (LocInfo.second > Buffer.size())
14447             return false;
14448 
14449           const char *LexStart = Buffer.data() + LocInfo.second;
14450           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14451 
14452           return StartTok.consume_front("const") &&
14453                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14454                   StartTok.startswith("/*") || StartTok.startswith("//"));
14455         };
14456 
14457         auto findBeginLoc = [&]() {
14458           // If the return type has `const` qualifier, we want to insert
14459           // `static` before `const` (and not before the typename).
14460           if ((FD->getReturnType()->isAnyPointerType() &&
14461                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14462               FD->getReturnType().isConstQualified()) {
14463             // But only do this if we can determine where the `const` is.
14464 
14465             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14466                              getLangOpts()))
14467 
14468               return FD->getBeginLoc();
14469           }
14470           return FD->getTypeSpecStartLoc();
14471         };
14472         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14473             << /* function */ 1
14474             << (FD->getStorageClass() == SC_None
14475                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14476                     : FixItHint{});
14477       }
14478 
14479       // GNU warning -Wstrict-prototypes
14480       //   Warn if K&R function is defined without a previous declaration.
14481       //   This warning is issued only if the definition itself does not provide
14482       //   a prototype. Only K&R definitions do not provide a prototype.
14483       if (!FD->hasWrittenPrototype()) {
14484         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14485         TypeLoc TL = TI->getTypeLoc();
14486         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14487         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14488       }
14489     }
14490 
14491     // Warn on CPUDispatch with an actual body.
14492     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14493       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14494         if (!CmpndBody->body_empty())
14495           Diag(CmpndBody->body_front()->getBeginLoc(),
14496                diag::warn_dispatch_body_ignored);
14497 
14498     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14499       const CXXMethodDecl *KeyFunction;
14500       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14501           MD->isVirtual() &&
14502           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14503           MD == KeyFunction->getCanonicalDecl()) {
14504         // Update the key-function state if necessary for this ABI.
14505         if (FD->isInlined() &&
14506             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14507           Context.setNonKeyFunction(MD);
14508 
14509           // If the newly-chosen key function is already defined, then we
14510           // need to mark the vtable as used retroactively.
14511           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14512           const FunctionDecl *Definition;
14513           if (KeyFunction && KeyFunction->isDefined(Definition))
14514             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14515         } else {
14516           // We just defined they key function; mark the vtable as used.
14517           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14518         }
14519       }
14520     }
14521 
14522     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14523            "Function parsing confused");
14524   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14525     assert(MD == getCurMethodDecl() && "Method parsing confused");
14526     MD->setBody(Body);
14527     if (!MD->isInvalidDecl()) {
14528       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14529                                              MD->getReturnType(), MD);
14530 
14531       if (Body)
14532         computeNRVO(Body, FSI);
14533     }
14534     if (FSI->ObjCShouldCallSuper) {
14535       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14536           << MD->getSelector().getAsString();
14537       FSI->ObjCShouldCallSuper = false;
14538     }
14539     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14540       const ObjCMethodDecl *InitMethod = nullptr;
14541       bool isDesignated =
14542           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14543       assert(isDesignated && InitMethod);
14544       (void)isDesignated;
14545 
14546       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14547         auto IFace = MD->getClassInterface();
14548         if (!IFace)
14549           return false;
14550         auto SuperD = IFace->getSuperClass();
14551         if (!SuperD)
14552           return false;
14553         return SuperD->getIdentifier() ==
14554             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14555       };
14556       // Don't issue this warning for unavailable inits or direct subclasses
14557       // of NSObject.
14558       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14559         Diag(MD->getLocation(),
14560              diag::warn_objc_designated_init_missing_super_call);
14561         Diag(InitMethod->getLocation(),
14562              diag::note_objc_designated_init_marked_here);
14563       }
14564       FSI->ObjCWarnForNoDesignatedInitChain = false;
14565     }
14566     if (FSI->ObjCWarnForNoInitDelegation) {
14567       // Don't issue this warning for unavaialable inits.
14568       if (!MD->isUnavailable())
14569         Diag(MD->getLocation(),
14570              diag::warn_objc_secondary_init_missing_init_call);
14571       FSI->ObjCWarnForNoInitDelegation = false;
14572     }
14573 
14574     diagnoseImplicitlyRetainedSelf(*this);
14575   } else {
14576     // Parsing the function declaration failed in some way. Pop the fake scope
14577     // we pushed on.
14578     PopFunctionScopeInfo(ActivePolicy, dcl);
14579     return nullptr;
14580   }
14581 
14582   if (Body && FSI->HasPotentialAvailabilityViolations)
14583     DiagnoseUnguardedAvailabilityViolations(dcl);
14584 
14585   assert(!FSI->ObjCShouldCallSuper &&
14586          "This should only be set for ObjC methods, which should have been "
14587          "handled in the block above.");
14588 
14589   // Verify and clean out per-function state.
14590   if (Body && (!FD || !FD->isDefaulted())) {
14591     // C++ constructors that have function-try-blocks can't have return
14592     // statements in the handlers of that block. (C++ [except.handle]p14)
14593     // Verify this.
14594     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14595       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14596 
14597     // Verify that gotos and switch cases don't jump into scopes illegally.
14598     if (FSI->NeedsScopeChecking() &&
14599         !PP.isCodeCompletionEnabled())
14600       DiagnoseInvalidJumps(Body);
14601 
14602     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14603       if (!Destructor->getParent()->isDependentType())
14604         CheckDestructor(Destructor);
14605 
14606       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14607                                              Destructor->getParent());
14608     }
14609 
14610     // If any errors have occurred, clear out any temporaries that may have
14611     // been leftover. This ensures that these temporaries won't be picked up for
14612     // deletion in some later function.
14613     if (hasUncompilableErrorOccurred() ||
14614         getDiagnostics().getSuppressAllDiagnostics()) {
14615       DiscardCleanupsInEvaluationContext();
14616     }
14617     if (!hasUncompilableErrorOccurred() &&
14618         !isa<FunctionTemplateDecl>(dcl)) {
14619       // Since the body is valid, issue any analysis-based warnings that are
14620       // enabled.
14621       ActivePolicy = &WP;
14622     }
14623 
14624     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14625         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14626       FD->setInvalidDecl();
14627 
14628     if (FD && FD->hasAttr<NakedAttr>()) {
14629       for (const Stmt *S : Body->children()) {
14630         // Allow local register variables without initializer as they don't
14631         // require prologue.
14632         bool RegisterVariables = false;
14633         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14634           for (const auto *Decl : DS->decls()) {
14635             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14636               RegisterVariables =
14637                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14638               if (!RegisterVariables)
14639                 break;
14640             }
14641           }
14642         }
14643         if (RegisterVariables)
14644           continue;
14645         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14646           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14647           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14648           FD->setInvalidDecl();
14649           break;
14650         }
14651       }
14652     }
14653 
14654     assert(ExprCleanupObjects.size() ==
14655                ExprEvalContexts.back().NumCleanupObjects &&
14656            "Leftover temporaries in function");
14657     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14658     assert(MaybeODRUseExprs.empty() &&
14659            "Leftover expressions for odr-use checking");
14660   }
14661 
14662   if (!IsInstantiation)
14663     PopDeclContext();
14664 
14665   PopFunctionScopeInfo(ActivePolicy, dcl);
14666   // If any errors have occurred, clear out any temporaries that may have
14667   // been leftover. This ensures that these temporaries won't be picked up for
14668   // deletion in some later function.
14669   if (hasUncompilableErrorOccurred()) {
14670     DiscardCleanupsInEvaluationContext();
14671   }
14672 
14673   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14674     auto ES = getEmissionStatus(FD);
14675     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14676         ES == Sema::FunctionEmissionStatus::Unknown)
14677       DeclsToCheckForDeferredDiags.push_back(FD);
14678   }
14679 
14680   return dcl;
14681 }
14682 
14683 /// When we finish delayed parsing of an attribute, we must attach it to the
14684 /// relevant Decl.
14685 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14686                                        ParsedAttributes &Attrs) {
14687   // Always attach attributes to the underlying decl.
14688   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14689     D = TD->getTemplatedDecl();
14690   ProcessDeclAttributeList(S, D, Attrs);
14691 
14692   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14693     if (Method->isStatic())
14694       checkThisInStaticMemberFunctionAttributes(Method);
14695 }
14696 
14697 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14698 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14699 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14700                                           IdentifierInfo &II, Scope *S) {
14701   // Find the scope in which the identifier is injected and the corresponding
14702   // DeclContext.
14703   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14704   // In that case, we inject the declaration into the translation unit scope
14705   // instead.
14706   Scope *BlockScope = S;
14707   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14708     BlockScope = BlockScope->getParent();
14709 
14710   Scope *ContextScope = BlockScope;
14711   while (!ContextScope->getEntity())
14712     ContextScope = ContextScope->getParent();
14713   ContextRAII SavedContext(*this, ContextScope->getEntity());
14714 
14715   // Before we produce a declaration for an implicitly defined
14716   // function, see whether there was a locally-scoped declaration of
14717   // this name as a function or variable. If so, use that
14718   // (non-visible) declaration, and complain about it.
14719   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14720   if (ExternCPrev) {
14721     // We still need to inject the function into the enclosing block scope so
14722     // that later (non-call) uses can see it.
14723     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14724 
14725     // C89 footnote 38:
14726     //   If in fact it is not defined as having type "function returning int",
14727     //   the behavior is undefined.
14728     if (!isa<FunctionDecl>(ExternCPrev) ||
14729         !Context.typesAreCompatible(
14730             cast<FunctionDecl>(ExternCPrev)->getType(),
14731             Context.getFunctionNoProtoType(Context.IntTy))) {
14732       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14733           << ExternCPrev << !getLangOpts().C99;
14734       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14735       return ExternCPrev;
14736     }
14737   }
14738 
14739   // Extension in C99.  Legal in C90, but warn about it.
14740   unsigned diag_id;
14741   if (II.getName().startswith("__builtin_"))
14742     diag_id = diag::warn_builtin_unknown;
14743   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14744   else if (getLangOpts().OpenCL)
14745     diag_id = diag::err_opencl_implicit_function_decl;
14746   else if (getLangOpts().C99)
14747     diag_id = diag::ext_implicit_function_decl;
14748   else
14749     diag_id = diag::warn_implicit_function_decl;
14750   Diag(Loc, diag_id) << &II;
14751 
14752   // If we found a prior declaration of this function, don't bother building
14753   // another one. We've already pushed that one into scope, so there's nothing
14754   // more to do.
14755   if (ExternCPrev)
14756     return ExternCPrev;
14757 
14758   // Because typo correction is expensive, only do it if the implicit
14759   // function declaration is going to be treated as an error.
14760   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14761     TypoCorrection Corrected;
14762     DeclFilterCCC<FunctionDecl> CCC{};
14763     if (S && (Corrected =
14764                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14765                               S, nullptr, CCC, CTK_NonError)))
14766       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14767                    /*ErrorRecovery*/false);
14768   }
14769 
14770   // Set a Declarator for the implicit definition: int foo();
14771   const char *Dummy;
14772   AttributeFactory attrFactory;
14773   DeclSpec DS(attrFactory);
14774   unsigned DiagID;
14775   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14776                                   Context.getPrintingPolicy());
14777   (void)Error; // Silence warning.
14778   assert(!Error && "Error setting up implicit decl!");
14779   SourceLocation NoLoc;
14780   Declarator D(DS, DeclaratorContext::Block);
14781   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14782                                              /*IsAmbiguous=*/false,
14783                                              /*LParenLoc=*/NoLoc,
14784                                              /*Params=*/nullptr,
14785                                              /*NumParams=*/0,
14786                                              /*EllipsisLoc=*/NoLoc,
14787                                              /*RParenLoc=*/NoLoc,
14788                                              /*RefQualifierIsLvalueRef=*/true,
14789                                              /*RefQualifierLoc=*/NoLoc,
14790                                              /*MutableLoc=*/NoLoc, EST_None,
14791                                              /*ESpecRange=*/SourceRange(),
14792                                              /*Exceptions=*/nullptr,
14793                                              /*ExceptionRanges=*/nullptr,
14794                                              /*NumExceptions=*/0,
14795                                              /*NoexceptExpr=*/nullptr,
14796                                              /*ExceptionSpecTokens=*/nullptr,
14797                                              /*DeclsInPrototype=*/None, Loc,
14798                                              Loc, D),
14799                 std::move(DS.getAttributes()), SourceLocation());
14800   D.SetIdentifier(&II, Loc);
14801 
14802   // Insert this function into the enclosing block scope.
14803   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14804   FD->setImplicit();
14805 
14806   AddKnownFunctionAttributes(FD);
14807 
14808   return FD;
14809 }
14810 
14811 /// If this function is a C++ replaceable global allocation function
14812 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14813 /// adds any function attributes that we know a priori based on the standard.
14814 ///
14815 /// We need to check for duplicate attributes both here and where user-written
14816 /// attributes are applied to declarations.
14817 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14818     FunctionDecl *FD) {
14819   if (FD->isInvalidDecl())
14820     return;
14821 
14822   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14823       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14824     return;
14825 
14826   Optional<unsigned> AlignmentParam;
14827   bool IsNothrow = false;
14828   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14829     return;
14830 
14831   // C++2a [basic.stc.dynamic.allocation]p4:
14832   //   An allocation function that has a non-throwing exception specification
14833   //   indicates failure by returning a null pointer value. Any other allocation
14834   //   function never returns a null pointer value and indicates failure only by
14835   //   throwing an exception [...]
14836   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14837     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14838 
14839   // C++2a [basic.stc.dynamic.allocation]p2:
14840   //   An allocation function attempts to allocate the requested amount of
14841   //   storage. [...] If the request succeeds, the value returned by a
14842   //   replaceable allocation function is a [...] pointer value p0 different
14843   //   from any previously returned value p1 [...]
14844   //
14845   // However, this particular information is being added in codegen,
14846   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14847 
14848   // C++2a [basic.stc.dynamic.allocation]p2:
14849   //   An allocation function attempts to allocate the requested amount of
14850   //   storage. If it is successful, it returns the address of the start of a
14851   //   block of storage whose length in bytes is at least as large as the
14852   //   requested size.
14853   if (!FD->hasAttr<AllocSizeAttr>()) {
14854     FD->addAttr(AllocSizeAttr::CreateImplicit(
14855         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14856         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14857   }
14858 
14859   // C++2a [basic.stc.dynamic.allocation]p3:
14860   //   For an allocation function [...], the pointer returned on a successful
14861   //   call shall represent the address of storage that is aligned as follows:
14862   //   (3.1) If the allocation function takes an argument of type
14863   //         std​::​align_­val_­t, the storage will have the alignment
14864   //         specified by the value of this argument.
14865   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14866     FD->addAttr(AllocAlignAttr::CreateImplicit(
14867         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14868   }
14869 
14870   // FIXME:
14871   // C++2a [basic.stc.dynamic.allocation]p3:
14872   //   For an allocation function [...], the pointer returned on a successful
14873   //   call shall represent the address of storage that is aligned as follows:
14874   //   (3.2) Otherwise, if the allocation function is named operator new[],
14875   //         the storage is aligned for any object that does not have
14876   //         new-extended alignment ([basic.align]) and is no larger than the
14877   //         requested size.
14878   //   (3.3) Otherwise, the storage is aligned for any object that does not
14879   //         have new-extended alignment and is of the requested size.
14880 }
14881 
14882 /// Adds any function attributes that we know a priori based on
14883 /// the declaration of this function.
14884 ///
14885 /// These attributes can apply both to implicitly-declared builtins
14886 /// (like __builtin___printf_chk) or to library-declared functions
14887 /// like NSLog or printf.
14888 ///
14889 /// We need to check for duplicate attributes both here and where user-written
14890 /// attributes are applied to declarations.
14891 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14892   if (FD->isInvalidDecl())
14893     return;
14894 
14895   // If this is a built-in function, map its builtin attributes to
14896   // actual attributes.
14897   if (unsigned BuiltinID = FD->getBuiltinID()) {
14898     // Handle printf-formatting attributes.
14899     unsigned FormatIdx;
14900     bool HasVAListArg;
14901     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14902       if (!FD->hasAttr<FormatAttr>()) {
14903         const char *fmt = "printf";
14904         unsigned int NumParams = FD->getNumParams();
14905         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14906             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14907           fmt = "NSString";
14908         FD->addAttr(FormatAttr::CreateImplicit(Context,
14909                                                &Context.Idents.get(fmt),
14910                                                FormatIdx+1,
14911                                                HasVAListArg ? 0 : FormatIdx+2,
14912                                                FD->getLocation()));
14913       }
14914     }
14915     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14916                                              HasVAListArg)) {
14917      if (!FD->hasAttr<FormatAttr>())
14918        FD->addAttr(FormatAttr::CreateImplicit(Context,
14919                                               &Context.Idents.get("scanf"),
14920                                               FormatIdx+1,
14921                                               HasVAListArg ? 0 : FormatIdx+2,
14922                                               FD->getLocation()));
14923     }
14924 
14925     // Handle automatically recognized callbacks.
14926     SmallVector<int, 4> Encoding;
14927     if (!FD->hasAttr<CallbackAttr>() &&
14928         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14929       FD->addAttr(CallbackAttr::CreateImplicit(
14930           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14931 
14932     // Mark const if we don't care about errno and that is the only thing
14933     // preventing the function from being const. This allows IRgen to use LLVM
14934     // intrinsics for such functions.
14935     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14936         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14937       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14938 
14939     // We make "fma" on some platforms const because we know it does not set
14940     // errno in those environments even though it could set errno based on the
14941     // C standard.
14942     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14943     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14944         !FD->hasAttr<ConstAttr>()) {
14945       switch (BuiltinID) {
14946       case Builtin::BI__builtin_fma:
14947       case Builtin::BI__builtin_fmaf:
14948       case Builtin::BI__builtin_fmal:
14949       case Builtin::BIfma:
14950       case Builtin::BIfmaf:
14951       case Builtin::BIfmal:
14952         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14953         break;
14954       default:
14955         break;
14956       }
14957     }
14958 
14959     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14960         !FD->hasAttr<ReturnsTwiceAttr>())
14961       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14962                                          FD->getLocation()));
14963     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14964       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14965     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14966       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14967     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14968       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14969     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14970         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14971       // Add the appropriate attribute, depending on the CUDA compilation mode
14972       // and which target the builtin belongs to. For example, during host
14973       // compilation, aux builtins are __device__, while the rest are __host__.
14974       if (getLangOpts().CUDAIsDevice !=
14975           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14976         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14977       else
14978         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14979     }
14980   }
14981 
14982   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14983 
14984   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14985   // throw, add an implicit nothrow attribute to any extern "C" function we come
14986   // across.
14987   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14988       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14989     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14990     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14991       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14992   }
14993 
14994   IdentifierInfo *Name = FD->getIdentifier();
14995   if (!Name)
14996     return;
14997   if ((!getLangOpts().CPlusPlus &&
14998        FD->getDeclContext()->isTranslationUnit()) ||
14999       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15000        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15001        LinkageSpecDecl::lang_c)) {
15002     // Okay: this could be a libc/libm/Objective-C function we know
15003     // about.
15004   } else
15005     return;
15006 
15007   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15008     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15009     // target-specific builtins, perhaps?
15010     if (!FD->hasAttr<FormatAttr>())
15011       FD->addAttr(FormatAttr::CreateImplicit(Context,
15012                                              &Context.Idents.get("printf"), 2,
15013                                              Name->isStr("vasprintf") ? 0 : 3,
15014                                              FD->getLocation()));
15015   }
15016 
15017   if (Name->isStr("__CFStringMakeConstantString")) {
15018     // We already have a __builtin___CFStringMakeConstantString,
15019     // but builds that use -fno-constant-cfstrings don't go through that.
15020     if (!FD->hasAttr<FormatArgAttr>())
15021       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15022                                                 FD->getLocation()));
15023   }
15024 }
15025 
15026 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15027                                     TypeSourceInfo *TInfo) {
15028   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15029   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15030 
15031   if (!TInfo) {
15032     assert(D.isInvalidType() && "no declarator info for valid type");
15033     TInfo = Context.getTrivialTypeSourceInfo(T);
15034   }
15035 
15036   // Scope manipulation handled by caller.
15037   TypedefDecl *NewTD =
15038       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15039                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15040 
15041   // Bail out immediately if we have an invalid declaration.
15042   if (D.isInvalidType()) {
15043     NewTD->setInvalidDecl();
15044     return NewTD;
15045   }
15046 
15047   if (D.getDeclSpec().isModulePrivateSpecified()) {
15048     if (CurContext->isFunctionOrMethod())
15049       Diag(NewTD->getLocation(), diag::err_module_private_local)
15050           << 2 << NewTD
15051           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15052           << FixItHint::CreateRemoval(
15053                  D.getDeclSpec().getModulePrivateSpecLoc());
15054     else
15055       NewTD->setModulePrivate();
15056   }
15057 
15058   // C++ [dcl.typedef]p8:
15059   //   If the typedef declaration defines an unnamed class (or
15060   //   enum), the first typedef-name declared by the declaration
15061   //   to be that class type (or enum type) is used to denote the
15062   //   class type (or enum type) for linkage purposes only.
15063   // We need to check whether the type was declared in the declaration.
15064   switch (D.getDeclSpec().getTypeSpecType()) {
15065   case TST_enum:
15066   case TST_struct:
15067   case TST_interface:
15068   case TST_union:
15069   case TST_class: {
15070     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15071     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15072     break;
15073   }
15074 
15075   default:
15076     break;
15077   }
15078 
15079   return NewTD;
15080 }
15081 
15082 /// Check that this is a valid underlying type for an enum declaration.
15083 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15084   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15085   QualType T = TI->getType();
15086 
15087   if (T->isDependentType())
15088     return false;
15089 
15090   // This doesn't use 'isIntegralType' despite the error message mentioning
15091   // integral type because isIntegralType would also allow enum types in C.
15092   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15093     if (BT->isInteger())
15094       return false;
15095 
15096   if (T->isExtIntType())
15097     return false;
15098 
15099   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15100 }
15101 
15102 /// Check whether this is a valid redeclaration of a previous enumeration.
15103 /// \return true if the redeclaration was invalid.
15104 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15105                                   QualType EnumUnderlyingTy, bool IsFixed,
15106                                   const EnumDecl *Prev) {
15107   if (IsScoped != Prev->isScoped()) {
15108     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15109       << Prev->isScoped();
15110     Diag(Prev->getLocation(), diag::note_previous_declaration);
15111     return true;
15112   }
15113 
15114   if (IsFixed && Prev->isFixed()) {
15115     if (!EnumUnderlyingTy->isDependentType() &&
15116         !Prev->getIntegerType()->isDependentType() &&
15117         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15118                                         Prev->getIntegerType())) {
15119       // TODO: Highlight the underlying type of the redeclaration.
15120       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15121         << EnumUnderlyingTy << Prev->getIntegerType();
15122       Diag(Prev->getLocation(), diag::note_previous_declaration)
15123           << Prev->getIntegerTypeRange();
15124       return true;
15125     }
15126   } else if (IsFixed != Prev->isFixed()) {
15127     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15128       << Prev->isFixed();
15129     Diag(Prev->getLocation(), diag::note_previous_declaration);
15130     return true;
15131   }
15132 
15133   return false;
15134 }
15135 
15136 /// Get diagnostic %select index for tag kind for
15137 /// redeclaration diagnostic message.
15138 /// WARNING: Indexes apply to particular diagnostics only!
15139 ///
15140 /// \returns diagnostic %select index.
15141 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15142   switch (Tag) {
15143   case TTK_Struct: return 0;
15144   case TTK_Interface: return 1;
15145   case TTK_Class:  return 2;
15146   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15147   }
15148 }
15149 
15150 /// Determine if tag kind is a class-key compatible with
15151 /// class for redeclaration (class, struct, or __interface).
15152 ///
15153 /// \returns true iff the tag kind is compatible.
15154 static bool isClassCompatTagKind(TagTypeKind Tag)
15155 {
15156   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15157 }
15158 
15159 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15160                                              TagTypeKind TTK) {
15161   if (isa<TypedefDecl>(PrevDecl))
15162     return NTK_Typedef;
15163   else if (isa<TypeAliasDecl>(PrevDecl))
15164     return NTK_TypeAlias;
15165   else if (isa<ClassTemplateDecl>(PrevDecl))
15166     return NTK_Template;
15167   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15168     return NTK_TypeAliasTemplate;
15169   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15170     return NTK_TemplateTemplateArgument;
15171   switch (TTK) {
15172   case TTK_Struct:
15173   case TTK_Interface:
15174   case TTK_Class:
15175     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15176   case TTK_Union:
15177     return NTK_NonUnion;
15178   case TTK_Enum:
15179     return NTK_NonEnum;
15180   }
15181   llvm_unreachable("invalid TTK");
15182 }
15183 
15184 /// Determine whether a tag with a given kind is acceptable
15185 /// as a redeclaration of the given tag declaration.
15186 ///
15187 /// \returns true if the new tag kind is acceptable, false otherwise.
15188 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15189                                         TagTypeKind NewTag, bool isDefinition,
15190                                         SourceLocation NewTagLoc,
15191                                         const IdentifierInfo *Name) {
15192   // C++ [dcl.type.elab]p3:
15193   //   The class-key or enum keyword present in the
15194   //   elaborated-type-specifier shall agree in kind with the
15195   //   declaration to which the name in the elaborated-type-specifier
15196   //   refers. This rule also applies to the form of
15197   //   elaborated-type-specifier that declares a class-name or
15198   //   friend class since it can be construed as referring to the
15199   //   definition of the class. Thus, in any
15200   //   elaborated-type-specifier, the enum keyword shall be used to
15201   //   refer to an enumeration (7.2), the union class-key shall be
15202   //   used to refer to a union (clause 9), and either the class or
15203   //   struct class-key shall be used to refer to a class (clause 9)
15204   //   declared using the class or struct class-key.
15205   TagTypeKind OldTag = Previous->getTagKind();
15206   if (OldTag != NewTag &&
15207       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15208     return false;
15209 
15210   // Tags are compatible, but we might still want to warn on mismatched tags.
15211   // Non-class tags can't be mismatched at this point.
15212   if (!isClassCompatTagKind(NewTag))
15213     return true;
15214 
15215   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15216   // by our warning analysis. We don't want to warn about mismatches with (eg)
15217   // declarations in system headers that are designed to be specialized, but if
15218   // a user asks us to warn, we should warn if their code contains mismatched
15219   // declarations.
15220   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15221     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15222                                       Loc);
15223   };
15224   if (IsIgnoredLoc(NewTagLoc))
15225     return true;
15226 
15227   auto IsIgnored = [&](const TagDecl *Tag) {
15228     return IsIgnoredLoc(Tag->getLocation());
15229   };
15230   while (IsIgnored(Previous)) {
15231     Previous = Previous->getPreviousDecl();
15232     if (!Previous)
15233       return true;
15234     OldTag = Previous->getTagKind();
15235   }
15236 
15237   bool isTemplate = false;
15238   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15239     isTemplate = Record->getDescribedClassTemplate();
15240 
15241   if (inTemplateInstantiation()) {
15242     if (OldTag != NewTag) {
15243       // In a template instantiation, do not offer fix-its for tag mismatches
15244       // since they usually mess up the template instead of fixing the problem.
15245       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15246         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15247         << getRedeclDiagFromTagKind(OldTag);
15248       // FIXME: Note previous location?
15249     }
15250     return true;
15251   }
15252 
15253   if (isDefinition) {
15254     // On definitions, check all previous tags and issue a fix-it for each
15255     // one that doesn't match the current tag.
15256     if (Previous->getDefinition()) {
15257       // Don't suggest fix-its for redefinitions.
15258       return true;
15259     }
15260 
15261     bool previousMismatch = false;
15262     for (const TagDecl *I : Previous->redecls()) {
15263       if (I->getTagKind() != NewTag) {
15264         // Ignore previous declarations for which the warning was disabled.
15265         if (IsIgnored(I))
15266           continue;
15267 
15268         if (!previousMismatch) {
15269           previousMismatch = true;
15270           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15271             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15272             << getRedeclDiagFromTagKind(I->getTagKind());
15273         }
15274         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15275           << getRedeclDiagFromTagKind(NewTag)
15276           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15277                TypeWithKeyword::getTagTypeKindName(NewTag));
15278       }
15279     }
15280     return true;
15281   }
15282 
15283   // Identify the prevailing tag kind: this is the kind of the definition (if
15284   // there is a non-ignored definition), or otherwise the kind of the prior
15285   // (non-ignored) declaration.
15286   const TagDecl *PrevDef = Previous->getDefinition();
15287   if (PrevDef && IsIgnored(PrevDef))
15288     PrevDef = nullptr;
15289   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15290   if (Redecl->getTagKind() != NewTag) {
15291     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15292       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15293       << getRedeclDiagFromTagKind(OldTag);
15294     Diag(Redecl->getLocation(), diag::note_previous_use);
15295 
15296     // If there is a previous definition, suggest a fix-it.
15297     if (PrevDef) {
15298       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15299         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15300         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15301              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15302     }
15303   }
15304 
15305   return true;
15306 }
15307 
15308 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15309 /// from an outer enclosing namespace or file scope inside a friend declaration.
15310 /// This should provide the commented out code in the following snippet:
15311 ///   namespace N {
15312 ///     struct X;
15313 ///     namespace M {
15314 ///       struct Y { friend struct /*N::*/ X; };
15315 ///     }
15316 ///   }
15317 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15318                                          SourceLocation NameLoc) {
15319   // While the decl is in a namespace, do repeated lookup of that name and see
15320   // if we get the same namespace back.  If we do not, continue until
15321   // translation unit scope, at which point we have a fully qualified NNS.
15322   SmallVector<IdentifierInfo *, 4> Namespaces;
15323   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15324   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15325     // This tag should be declared in a namespace, which can only be enclosed by
15326     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15327     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15328     if (!Namespace || Namespace->isAnonymousNamespace())
15329       return FixItHint();
15330     IdentifierInfo *II = Namespace->getIdentifier();
15331     Namespaces.push_back(II);
15332     NamedDecl *Lookup = SemaRef.LookupSingleName(
15333         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15334     if (Lookup == Namespace)
15335       break;
15336   }
15337 
15338   // Once we have all the namespaces, reverse them to go outermost first, and
15339   // build an NNS.
15340   SmallString<64> Insertion;
15341   llvm::raw_svector_ostream OS(Insertion);
15342   if (DC->isTranslationUnit())
15343     OS << "::";
15344   std::reverse(Namespaces.begin(), Namespaces.end());
15345   for (auto *II : Namespaces)
15346     OS << II->getName() << "::";
15347   return FixItHint::CreateInsertion(NameLoc, Insertion);
15348 }
15349 
15350 /// Determine whether a tag originally declared in context \p OldDC can
15351 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15352 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15353 /// using-declaration).
15354 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15355                                          DeclContext *NewDC) {
15356   OldDC = OldDC->getRedeclContext();
15357   NewDC = NewDC->getRedeclContext();
15358 
15359   if (OldDC->Equals(NewDC))
15360     return true;
15361 
15362   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15363   // encloses the other).
15364   if (S.getLangOpts().MSVCCompat &&
15365       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15366     return true;
15367 
15368   return false;
15369 }
15370 
15371 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15372 /// former case, Name will be non-null.  In the later case, Name will be null.
15373 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15374 /// reference/declaration/definition of a tag.
15375 ///
15376 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15377 /// trailing-type-specifier) other than one in an alias-declaration.
15378 ///
15379 /// \param SkipBody If non-null, will be set to indicate if the caller should
15380 /// skip the definition of this tag and treat it as if it were a declaration.
15381 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15382                      SourceLocation KWLoc, CXXScopeSpec &SS,
15383                      IdentifierInfo *Name, SourceLocation NameLoc,
15384                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15385                      SourceLocation ModulePrivateLoc,
15386                      MultiTemplateParamsArg TemplateParameterLists,
15387                      bool &OwnedDecl, bool &IsDependent,
15388                      SourceLocation ScopedEnumKWLoc,
15389                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15390                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15391                      SkipBodyInfo *SkipBody) {
15392   // If this is not a definition, it must have a name.
15393   IdentifierInfo *OrigName = Name;
15394   assert((Name != nullptr || TUK == TUK_Definition) &&
15395          "Nameless record must be a definition!");
15396   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15397 
15398   OwnedDecl = false;
15399   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15400   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15401 
15402   // FIXME: Check member specializations more carefully.
15403   bool isMemberSpecialization = false;
15404   bool Invalid = false;
15405 
15406   // We only need to do this matching if we have template parameters
15407   // or a scope specifier, which also conveniently avoids this work
15408   // for non-C++ cases.
15409   if (TemplateParameterLists.size() > 0 ||
15410       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15411     if (TemplateParameterList *TemplateParams =
15412             MatchTemplateParametersToScopeSpecifier(
15413                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15414                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15415       if (Kind == TTK_Enum) {
15416         Diag(KWLoc, diag::err_enum_template);
15417         return nullptr;
15418       }
15419 
15420       if (TemplateParams->size() > 0) {
15421         // This is a declaration or definition of a class template (which may
15422         // be a member of another template).
15423 
15424         if (Invalid)
15425           return nullptr;
15426 
15427         OwnedDecl = false;
15428         DeclResult Result = CheckClassTemplate(
15429             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15430             AS, ModulePrivateLoc,
15431             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15432             TemplateParameterLists.data(), SkipBody);
15433         return Result.get();
15434       } else {
15435         // The "template<>" header is extraneous.
15436         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15437           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15438         isMemberSpecialization = true;
15439       }
15440     }
15441 
15442     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15443         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15444       return nullptr;
15445   }
15446 
15447   // Figure out the underlying type if this a enum declaration. We need to do
15448   // this early, because it's needed to detect if this is an incompatible
15449   // redeclaration.
15450   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15451   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15452 
15453   if (Kind == TTK_Enum) {
15454     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15455       // No underlying type explicitly specified, or we failed to parse the
15456       // type, default to int.
15457       EnumUnderlying = Context.IntTy.getTypePtr();
15458     } else if (UnderlyingType.get()) {
15459       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15460       // integral type; any cv-qualification is ignored.
15461       TypeSourceInfo *TI = nullptr;
15462       GetTypeFromParser(UnderlyingType.get(), &TI);
15463       EnumUnderlying = TI;
15464 
15465       if (CheckEnumUnderlyingType(TI))
15466         // Recover by falling back to int.
15467         EnumUnderlying = Context.IntTy.getTypePtr();
15468 
15469       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15470                                           UPPC_FixedUnderlyingType))
15471         EnumUnderlying = Context.IntTy.getTypePtr();
15472 
15473     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15474       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15475       // of 'int'. However, if this is an unfixed forward declaration, don't set
15476       // the underlying type unless the user enables -fms-compatibility. This
15477       // makes unfixed forward declared enums incomplete and is more conforming.
15478       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15479         EnumUnderlying = Context.IntTy.getTypePtr();
15480     }
15481   }
15482 
15483   DeclContext *SearchDC = CurContext;
15484   DeclContext *DC = CurContext;
15485   bool isStdBadAlloc = false;
15486   bool isStdAlignValT = false;
15487 
15488   RedeclarationKind Redecl = forRedeclarationInCurContext();
15489   if (TUK == TUK_Friend || TUK == TUK_Reference)
15490     Redecl = NotForRedeclaration;
15491 
15492   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15493   /// implemented asks for structural equivalence checking, the returned decl
15494   /// here is passed back to the parser, allowing the tag body to be parsed.
15495   auto createTagFromNewDecl = [&]() -> TagDecl * {
15496     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15497     // If there is an identifier, use the location of the identifier as the
15498     // location of the decl, otherwise use the location of the struct/union
15499     // keyword.
15500     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15501     TagDecl *New = nullptr;
15502 
15503     if (Kind == TTK_Enum) {
15504       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15505                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15506       // If this is an undefined enum, bail.
15507       if (TUK != TUK_Definition && !Invalid)
15508         return nullptr;
15509       if (EnumUnderlying) {
15510         EnumDecl *ED = cast<EnumDecl>(New);
15511         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15512           ED->setIntegerTypeSourceInfo(TI);
15513         else
15514           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15515         ED->setPromotionType(ED->getIntegerType());
15516       }
15517     } else { // struct/union
15518       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15519                                nullptr);
15520     }
15521 
15522     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15523       // Add alignment attributes if necessary; these attributes are checked
15524       // when the ASTContext lays out the structure.
15525       //
15526       // It is important for implementing the correct semantics that this
15527       // happen here (in ActOnTag). The #pragma pack stack is
15528       // maintained as a result of parser callbacks which can occur at
15529       // many points during the parsing of a struct declaration (because
15530       // the #pragma tokens are effectively skipped over during the
15531       // parsing of the struct).
15532       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15533         AddAlignmentAttributesForRecord(RD);
15534         AddMsStructLayoutForRecord(RD);
15535       }
15536     }
15537     New->setLexicalDeclContext(CurContext);
15538     return New;
15539   };
15540 
15541   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15542   if (Name && SS.isNotEmpty()) {
15543     // We have a nested-name tag ('struct foo::bar').
15544 
15545     // Check for invalid 'foo::'.
15546     if (SS.isInvalid()) {
15547       Name = nullptr;
15548       goto CreateNewDecl;
15549     }
15550 
15551     // If this is a friend or a reference to a class in a dependent
15552     // context, don't try to make a decl for it.
15553     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15554       DC = computeDeclContext(SS, false);
15555       if (!DC) {
15556         IsDependent = true;
15557         return nullptr;
15558       }
15559     } else {
15560       DC = computeDeclContext(SS, true);
15561       if (!DC) {
15562         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15563           << SS.getRange();
15564         return nullptr;
15565       }
15566     }
15567 
15568     if (RequireCompleteDeclContext(SS, DC))
15569       return nullptr;
15570 
15571     SearchDC = DC;
15572     // Look-up name inside 'foo::'.
15573     LookupQualifiedName(Previous, DC);
15574 
15575     if (Previous.isAmbiguous())
15576       return nullptr;
15577 
15578     if (Previous.empty()) {
15579       // Name lookup did not find anything. However, if the
15580       // nested-name-specifier refers to the current instantiation,
15581       // and that current instantiation has any dependent base
15582       // classes, we might find something at instantiation time: treat
15583       // this as a dependent elaborated-type-specifier.
15584       // But this only makes any sense for reference-like lookups.
15585       if (Previous.wasNotFoundInCurrentInstantiation() &&
15586           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15587         IsDependent = true;
15588         return nullptr;
15589       }
15590 
15591       // A tag 'foo::bar' must already exist.
15592       Diag(NameLoc, diag::err_not_tag_in_scope)
15593         << Kind << Name << DC << SS.getRange();
15594       Name = nullptr;
15595       Invalid = true;
15596       goto CreateNewDecl;
15597     }
15598   } else if (Name) {
15599     // C++14 [class.mem]p14:
15600     //   If T is the name of a class, then each of the following shall have a
15601     //   name different from T:
15602     //    -- every member of class T that is itself a type
15603     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15604         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15605       return nullptr;
15606 
15607     // If this is a named struct, check to see if there was a previous forward
15608     // declaration or definition.
15609     // FIXME: We're looking into outer scopes here, even when we
15610     // shouldn't be. Doing so can result in ambiguities that we
15611     // shouldn't be diagnosing.
15612     LookupName(Previous, S);
15613 
15614     // When declaring or defining a tag, ignore ambiguities introduced
15615     // by types using'ed into this scope.
15616     if (Previous.isAmbiguous() &&
15617         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15618       LookupResult::Filter F = Previous.makeFilter();
15619       while (F.hasNext()) {
15620         NamedDecl *ND = F.next();
15621         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15622                 SearchDC->getRedeclContext()))
15623           F.erase();
15624       }
15625       F.done();
15626     }
15627 
15628     // C++11 [namespace.memdef]p3:
15629     //   If the name in a friend declaration is neither qualified nor
15630     //   a template-id and the declaration is a function or an
15631     //   elaborated-type-specifier, the lookup to determine whether
15632     //   the entity has been previously declared shall not consider
15633     //   any scopes outside the innermost enclosing namespace.
15634     //
15635     // MSVC doesn't implement the above rule for types, so a friend tag
15636     // declaration may be a redeclaration of a type declared in an enclosing
15637     // scope.  They do implement this rule for friend functions.
15638     //
15639     // Does it matter that this should be by scope instead of by
15640     // semantic context?
15641     if (!Previous.empty() && TUK == TUK_Friend) {
15642       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15643       LookupResult::Filter F = Previous.makeFilter();
15644       bool FriendSawTagOutsideEnclosingNamespace = false;
15645       while (F.hasNext()) {
15646         NamedDecl *ND = F.next();
15647         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15648         if (DC->isFileContext() &&
15649             !EnclosingNS->Encloses(ND->getDeclContext())) {
15650           if (getLangOpts().MSVCCompat)
15651             FriendSawTagOutsideEnclosingNamespace = true;
15652           else
15653             F.erase();
15654         }
15655       }
15656       F.done();
15657 
15658       // Diagnose this MSVC extension in the easy case where lookup would have
15659       // unambiguously found something outside the enclosing namespace.
15660       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15661         NamedDecl *ND = Previous.getFoundDecl();
15662         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15663             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15664       }
15665     }
15666 
15667     // Note:  there used to be some attempt at recovery here.
15668     if (Previous.isAmbiguous())
15669       return nullptr;
15670 
15671     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15672       // FIXME: This makes sure that we ignore the contexts associated
15673       // with C structs, unions, and enums when looking for a matching
15674       // tag declaration or definition. See the similar lookup tweak
15675       // in Sema::LookupName; is there a better way to deal with this?
15676       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15677         SearchDC = SearchDC->getParent();
15678     }
15679   }
15680 
15681   if (Previous.isSingleResult() &&
15682       Previous.getFoundDecl()->isTemplateParameter()) {
15683     // Maybe we will complain about the shadowed template parameter.
15684     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15685     // Just pretend that we didn't see the previous declaration.
15686     Previous.clear();
15687   }
15688 
15689   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15690       DC->Equals(getStdNamespace())) {
15691     if (Name->isStr("bad_alloc")) {
15692       // This is a declaration of or a reference to "std::bad_alloc".
15693       isStdBadAlloc = true;
15694 
15695       // If std::bad_alloc has been implicitly declared (but made invisible to
15696       // name lookup), fill in this implicit declaration as the previous
15697       // declaration, so that the declarations get chained appropriately.
15698       if (Previous.empty() && StdBadAlloc)
15699         Previous.addDecl(getStdBadAlloc());
15700     } else if (Name->isStr("align_val_t")) {
15701       isStdAlignValT = true;
15702       if (Previous.empty() && StdAlignValT)
15703         Previous.addDecl(getStdAlignValT());
15704     }
15705   }
15706 
15707   // If we didn't find a previous declaration, and this is a reference
15708   // (or friend reference), move to the correct scope.  In C++, we
15709   // also need to do a redeclaration lookup there, just in case
15710   // there's a shadow friend decl.
15711   if (Name && Previous.empty() &&
15712       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15713     if (Invalid) goto CreateNewDecl;
15714     assert(SS.isEmpty());
15715 
15716     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15717       // C++ [basic.scope.pdecl]p5:
15718       //   -- for an elaborated-type-specifier of the form
15719       //
15720       //          class-key identifier
15721       //
15722       //      if the elaborated-type-specifier is used in the
15723       //      decl-specifier-seq or parameter-declaration-clause of a
15724       //      function defined in namespace scope, the identifier is
15725       //      declared as a class-name in the namespace that contains
15726       //      the declaration; otherwise, except as a friend
15727       //      declaration, the identifier is declared in the smallest
15728       //      non-class, non-function-prototype scope that contains the
15729       //      declaration.
15730       //
15731       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15732       // C structs and unions.
15733       //
15734       // It is an error in C++ to declare (rather than define) an enum
15735       // type, including via an elaborated type specifier.  We'll
15736       // diagnose that later; for now, declare the enum in the same
15737       // scope as we would have picked for any other tag type.
15738       //
15739       // GNU C also supports this behavior as part of its incomplete
15740       // enum types extension, while GNU C++ does not.
15741       //
15742       // Find the context where we'll be declaring the tag.
15743       // FIXME: We would like to maintain the current DeclContext as the
15744       // lexical context,
15745       SearchDC = getTagInjectionContext(SearchDC);
15746 
15747       // Find the scope where we'll be declaring the tag.
15748       S = getTagInjectionScope(S, getLangOpts());
15749     } else {
15750       assert(TUK == TUK_Friend);
15751       // C++ [namespace.memdef]p3:
15752       //   If a friend declaration in a non-local class first declares a
15753       //   class or function, the friend class or function is a member of
15754       //   the innermost enclosing namespace.
15755       SearchDC = SearchDC->getEnclosingNamespaceContext();
15756     }
15757 
15758     // In C++, we need to do a redeclaration lookup to properly
15759     // diagnose some problems.
15760     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15761     // hidden declaration so that we don't get ambiguity errors when using a
15762     // type declared by an elaborated-type-specifier.  In C that is not correct
15763     // and we should instead merge compatible types found by lookup.
15764     if (getLangOpts().CPlusPlus) {
15765       // FIXME: This can perform qualified lookups into function contexts,
15766       // which are meaningless.
15767       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15768       LookupQualifiedName(Previous, SearchDC);
15769     } else {
15770       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15771       LookupName(Previous, S);
15772     }
15773   }
15774 
15775   // If we have a known previous declaration to use, then use it.
15776   if (Previous.empty() && SkipBody && SkipBody->Previous)
15777     Previous.addDecl(SkipBody->Previous);
15778 
15779   if (!Previous.empty()) {
15780     NamedDecl *PrevDecl = Previous.getFoundDecl();
15781     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15782 
15783     // It's okay to have a tag decl in the same scope as a typedef
15784     // which hides a tag decl in the same scope.  Finding this
15785     // insanity with a redeclaration lookup can only actually happen
15786     // in C++.
15787     //
15788     // This is also okay for elaborated-type-specifiers, which is
15789     // technically forbidden by the current standard but which is
15790     // okay according to the likely resolution of an open issue;
15791     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15792     if (getLangOpts().CPlusPlus) {
15793       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15794         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15795           TagDecl *Tag = TT->getDecl();
15796           if (Tag->getDeclName() == Name &&
15797               Tag->getDeclContext()->getRedeclContext()
15798                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15799             PrevDecl = Tag;
15800             Previous.clear();
15801             Previous.addDecl(Tag);
15802             Previous.resolveKind();
15803           }
15804         }
15805       }
15806     }
15807 
15808     // If this is a redeclaration of a using shadow declaration, it must
15809     // declare a tag in the same context. In MSVC mode, we allow a
15810     // redefinition if either context is within the other.
15811     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15812       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15813       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15814           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15815           !(OldTag && isAcceptableTagRedeclContext(
15816                           *this, OldTag->getDeclContext(), SearchDC))) {
15817         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15818         Diag(Shadow->getTargetDecl()->getLocation(),
15819              diag::note_using_decl_target);
15820         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15821             << 0;
15822         // Recover by ignoring the old declaration.
15823         Previous.clear();
15824         goto CreateNewDecl;
15825       }
15826     }
15827 
15828     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15829       // If this is a use of a previous tag, or if the tag is already declared
15830       // in the same scope (so that the definition/declaration completes or
15831       // rementions the tag), reuse the decl.
15832       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15833           isDeclInScope(DirectPrevDecl, SearchDC, S,
15834                         SS.isNotEmpty() || isMemberSpecialization)) {
15835         // Make sure that this wasn't declared as an enum and now used as a
15836         // struct or something similar.
15837         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15838                                           TUK == TUK_Definition, KWLoc,
15839                                           Name)) {
15840           bool SafeToContinue
15841             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15842                Kind != TTK_Enum);
15843           if (SafeToContinue)
15844             Diag(KWLoc, diag::err_use_with_wrong_tag)
15845               << Name
15846               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15847                                               PrevTagDecl->getKindName());
15848           else
15849             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15850           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15851 
15852           if (SafeToContinue)
15853             Kind = PrevTagDecl->getTagKind();
15854           else {
15855             // Recover by making this an anonymous redefinition.
15856             Name = nullptr;
15857             Previous.clear();
15858             Invalid = true;
15859           }
15860         }
15861 
15862         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15863           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15864           if (TUK == TUK_Reference || TUK == TUK_Friend)
15865             return PrevTagDecl;
15866 
15867           QualType EnumUnderlyingTy;
15868           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15869             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15870           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15871             EnumUnderlyingTy = QualType(T, 0);
15872 
15873           // All conflicts with previous declarations are recovered by
15874           // returning the previous declaration, unless this is a definition,
15875           // in which case we want the caller to bail out.
15876           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15877                                      ScopedEnum, EnumUnderlyingTy,
15878                                      IsFixed, PrevEnum))
15879             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15880         }
15881 
15882         // C++11 [class.mem]p1:
15883         //   A member shall not be declared twice in the member-specification,
15884         //   except that a nested class or member class template can be declared
15885         //   and then later defined.
15886         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15887             S->isDeclScope(PrevDecl)) {
15888           Diag(NameLoc, diag::ext_member_redeclared);
15889           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15890         }
15891 
15892         if (!Invalid) {
15893           // If this is a use, just return the declaration we found, unless
15894           // we have attributes.
15895           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15896             if (!Attrs.empty()) {
15897               // FIXME: Diagnose these attributes. For now, we create a new
15898               // declaration to hold them.
15899             } else if (TUK == TUK_Reference &&
15900                        (PrevTagDecl->getFriendObjectKind() ==
15901                             Decl::FOK_Undeclared ||
15902                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15903                        SS.isEmpty()) {
15904               // This declaration is a reference to an existing entity, but
15905               // has different visibility from that entity: it either makes
15906               // a friend visible or it makes a type visible in a new module.
15907               // In either case, create a new declaration. We only do this if
15908               // the declaration would have meant the same thing if no prior
15909               // declaration were found, that is, if it was found in the same
15910               // scope where we would have injected a declaration.
15911               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15912                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15913                 return PrevTagDecl;
15914               // This is in the injected scope, create a new declaration in
15915               // that scope.
15916               S = getTagInjectionScope(S, getLangOpts());
15917             } else {
15918               return PrevTagDecl;
15919             }
15920           }
15921 
15922           // Diagnose attempts to redefine a tag.
15923           if (TUK == TUK_Definition) {
15924             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15925               // If we're defining a specialization and the previous definition
15926               // is from an implicit instantiation, don't emit an error
15927               // here; we'll catch this in the general case below.
15928               bool IsExplicitSpecializationAfterInstantiation = false;
15929               if (isMemberSpecialization) {
15930                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15931                   IsExplicitSpecializationAfterInstantiation =
15932                     RD->getTemplateSpecializationKind() !=
15933                     TSK_ExplicitSpecialization;
15934                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15935                   IsExplicitSpecializationAfterInstantiation =
15936                     ED->getTemplateSpecializationKind() !=
15937                     TSK_ExplicitSpecialization;
15938               }
15939 
15940               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15941               // not keep more that one definition around (merge them). However,
15942               // ensure the decl passes the structural compatibility check in
15943               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15944               NamedDecl *Hidden = nullptr;
15945               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15946                 // There is a definition of this tag, but it is not visible. We
15947                 // explicitly make use of C++'s one definition rule here, and
15948                 // assume that this definition is identical to the hidden one
15949                 // we already have. Make the existing definition visible and
15950                 // use it in place of this one.
15951                 if (!getLangOpts().CPlusPlus) {
15952                   // Postpone making the old definition visible until after we
15953                   // complete parsing the new one and do the structural
15954                   // comparison.
15955                   SkipBody->CheckSameAsPrevious = true;
15956                   SkipBody->New = createTagFromNewDecl();
15957                   SkipBody->Previous = Def;
15958                   return Def;
15959                 } else {
15960                   SkipBody->ShouldSkip = true;
15961                   SkipBody->Previous = Def;
15962                   makeMergedDefinitionVisible(Hidden);
15963                   // Carry on and handle it like a normal definition. We'll
15964                   // skip starting the definitiion later.
15965                 }
15966               } else if (!IsExplicitSpecializationAfterInstantiation) {
15967                 // A redeclaration in function prototype scope in C isn't
15968                 // visible elsewhere, so merely issue a warning.
15969                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15970                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15971                 else
15972                   Diag(NameLoc, diag::err_redefinition) << Name;
15973                 notePreviousDefinition(Def,
15974                                        NameLoc.isValid() ? NameLoc : KWLoc);
15975                 // If this is a redefinition, recover by making this
15976                 // struct be anonymous, which will make any later
15977                 // references get the previous definition.
15978                 Name = nullptr;
15979                 Previous.clear();
15980                 Invalid = true;
15981               }
15982             } else {
15983               // If the type is currently being defined, complain
15984               // about a nested redefinition.
15985               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15986               if (TD->isBeingDefined()) {
15987                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15988                 Diag(PrevTagDecl->getLocation(),
15989                      diag::note_previous_definition);
15990                 Name = nullptr;
15991                 Previous.clear();
15992                 Invalid = true;
15993               }
15994             }
15995 
15996             // Okay, this is definition of a previously declared or referenced
15997             // tag. We're going to create a new Decl for it.
15998           }
15999 
16000           // Okay, we're going to make a redeclaration.  If this is some kind
16001           // of reference, make sure we build the redeclaration in the same DC
16002           // as the original, and ignore the current access specifier.
16003           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16004             SearchDC = PrevTagDecl->getDeclContext();
16005             AS = AS_none;
16006           }
16007         }
16008         // If we get here we have (another) forward declaration or we
16009         // have a definition.  Just create a new decl.
16010 
16011       } else {
16012         // If we get here, this is a definition of a new tag type in a nested
16013         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16014         // new decl/type.  We set PrevDecl to NULL so that the entities
16015         // have distinct types.
16016         Previous.clear();
16017       }
16018       // If we get here, we're going to create a new Decl. If PrevDecl
16019       // is non-NULL, it's a definition of the tag declared by
16020       // PrevDecl. If it's NULL, we have a new definition.
16021 
16022     // Otherwise, PrevDecl is not a tag, but was found with tag
16023     // lookup.  This is only actually possible in C++, where a few
16024     // things like templates still live in the tag namespace.
16025     } else {
16026       // Use a better diagnostic if an elaborated-type-specifier
16027       // found the wrong kind of type on the first
16028       // (non-redeclaration) lookup.
16029       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16030           !Previous.isForRedeclaration()) {
16031         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16032         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16033                                                        << Kind;
16034         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16035         Invalid = true;
16036 
16037       // Otherwise, only diagnose if the declaration is in scope.
16038       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16039                                 SS.isNotEmpty() || isMemberSpecialization)) {
16040         // do nothing
16041 
16042       // Diagnose implicit declarations introduced by elaborated types.
16043       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16044         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16045         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16046         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16047         Invalid = true;
16048 
16049       // Otherwise it's a declaration.  Call out a particularly common
16050       // case here.
16051       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16052         unsigned Kind = 0;
16053         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16054         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16055           << Name << Kind << TND->getUnderlyingType();
16056         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16057         Invalid = true;
16058 
16059       // Otherwise, diagnose.
16060       } else {
16061         // The tag name clashes with something else in the target scope,
16062         // issue an error and recover by making this tag be anonymous.
16063         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16064         notePreviousDefinition(PrevDecl, NameLoc);
16065         Name = nullptr;
16066         Invalid = true;
16067       }
16068 
16069       // The existing declaration isn't relevant to us; we're in a
16070       // new scope, so clear out the previous declaration.
16071       Previous.clear();
16072     }
16073   }
16074 
16075 CreateNewDecl:
16076 
16077   TagDecl *PrevDecl = nullptr;
16078   if (Previous.isSingleResult())
16079     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16080 
16081   // If there is an identifier, use the location of the identifier as the
16082   // location of the decl, otherwise use the location of the struct/union
16083   // keyword.
16084   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16085 
16086   // Otherwise, create a new declaration. If there is a previous
16087   // declaration of the same entity, the two will be linked via
16088   // PrevDecl.
16089   TagDecl *New;
16090 
16091   if (Kind == TTK_Enum) {
16092     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16093     // enum X { A, B, C } D;    D should chain to X.
16094     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16095                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16096                            ScopedEnumUsesClassTag, IsFixed);
16097 
16098     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16099       StdAlignValT = cast<EnumDecl>(New);
16100 
16101     // If this is an undefined enum, warn.
16102     if (TUK != TUK_Definition && !Invalid) {
16103       TagDecl *Def;
16104       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16105         // C++0x: 7.2p2: opaque-enum-declaration.
16106         // Conflicts are diagnosed above. Do nothing.
16107       }
16108       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16109         Diag(Loc, diag::ext_forward_ref_enum_def)
16110           << New;
16111         Diag(Def->getLocation(), diag::note_previous_definition);
16112       } else {
16113         unsigned DiagID = diag::ext_forward_ref_enum;
16114         if (getLangOpts().MSVCCompat)
16115           DiagID = diag::ext_ms_forward_ref_enum;
16116         else if (getLangOpts().CPlusPlus)
16117           DiagID = diag::err_forward_ref_enum;
16118         Diag(Loc, DiagID);
16119       }
16120     }
16121 
16122     if (EnumUnderlying) {
16123       EnumDecl *ED = cast<EnumDecl>(New);
16124       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16125         ED->setIntegerTypeSourceInfo(TI);
16126       else
16127         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16128       ED->setPromotionType(ED->getIntegerType());
16129       assert(ED->isComplete() && "enum with type should be complete");
16130     }
16131   } else {
16132     // struct/union/class
16133 
16134     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16135     // struct X { int A; } D;    D should chain to X.
16136     if (getLangOpts().CPlusPlus) {
16137       // FIXME: Look for a way to use RecordDecl for simple structs.
16138       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16139                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16140 
16141       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16142         StdBadAlloc = cast<CXXRecordDecl>(New);
16143     } else
16144       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16145                                cast_or_null<RecordDecl>(PrevDecl));
16146   }
16147 
16148   // C++11 [dcl.type]p3:
16149   //   A type-specifier-seq shall not define a class or enumeration [...].
16150   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16151       TUK == TUK_Definition) {
16152     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16153       << Context.getTagDeclType(New);
16154     Invalid = true;
16155   }
16156 
16157   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16158       DC->getDeclKind() == Decl::Enum) {
16159     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16160       << Context.getTagDeclType(New);
16161     Invalid = true;
16162   }
16163 
16164   // Maybe add qualifier info.
16165   if (SS.isNotEmpty()) {
16166     if (SS.isSet()) {
16167       // If this is either a declaration or a definition, check the
16168       // nested-name-specifier against the current context.
16169       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16170           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16171                                        isMemberSpecialization))
16172         Invalid = true;
16173 
16174       New->setQualifierInfo(SS.getWithLocInContext(Context));
16175       if (TemplateParameterLists.size() > 0) {
16176         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16177       }
16178     }
16179     else
16180       Invalid = true;
16181   }
16182 
16183   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16184     // Add alignment attributes if necessary; these attributes are checked when
16185     // the ASTContext lays out the structure.
16186     //
16187     // It is important for implementing the correct semantics that this
16188     // happen here (in ActOnTag). The #pragma pack stack is
16189     // maintained as a result of parser callbacks which can occur at
16190     // many points during the parsing of a struct declaration (because
16191     // the #pragma tokens are effectively skipped over during the
16192     // parsing of the struct).
16193     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16194       AddAlignmentAttributesForRecord(RD);
16195       AddMsStructLayoutForRecord(RD);
16196     }
16197   }
16198 
16199   if (ModulePrivateLoc.isValid()) {
16200     if (isMemberSpecialization)
16201       Diag(New->getLocation(), diag::err_module_private_specialization)
16202         << 2
16203         << FixItHint::CreateRemoval(ModulePrivateLoc);
16204     // __module_private__ does not apply to local classes. However, we only
16205     // diagnose this as an error when the declaration specifiers are
16206     // freestanding. Here, we just ignore the __module_private__.
16207     else if (!SearchDC->isFunctionOrMethod())
16208       New->setModulePrivate();
16209   }
16210 
16211   // If this is a specialization of a member class (of a class template),
16212   // check the specialization.
16213   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16214     Invalid = true;
16215 
16216   // If we're declaring or defining a tag in function prototype scope in C,
16217   // note that this type can only be used within the function and add it to
16218   // the list of decls to inject into the function definition scope.
16219   if ((Name || Kind == TTK_Enum) &&
16220       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16221     if (getLangOpts().CPlusPlus) {
16222       // C++ [dcl.fct]p6:
16223       //   Types shall not be defined in return or parameter types.
16224       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16225         Diag(Loc, diag::err_type_defined_in_param_type)
16226             << Name;
16227         Invalid = true;
16228       }
16229     } else if (!PrevDecl) {
16230       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16231     }
16232   }
16233 
16234   if (Invalid)
16235     New->setInvalidDecl();
16236 
16237   // Set the lexical context. If the tag has a C++ scope specifier, the
16238   // lexical context will be different from the semantic context.
16239   New->setLexicalDeclContext(CurContext);
16240 
16241   // Mark this as a friend decl if applicable.
16242   // In Microsoft mode, a friend declaration also acts as a forward
16243   // declaration so we always pass true to setObjectOfFriendDecl to make
16244   // the tag name visible.
16245   if (TUK == TUK_Friend)
16246     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16247 
16248   // Set the access specifier.
16249   if (!Invalid && SearchDC->isRecord())
16250     SetMemberAccessSpecifier(New, PrevDecl, AS);
16251 
16252   if (PrevDecl)
16253     CheckRedeclarationModuleOwnership(New, PrevDecl);
16254 
16255   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16256     New->startDefinition();
16257 
16258   ProcessDeclAttributeList(S, New, Attrs);
16259   AddPragmaAttributes(S, New);
16260 
16261   // If this has an identifier, add it to the scope stack.
16262   if (TUK == TUK_Friend) {
16263     // We might be replacing an existing declaration in the lookup tables;
16264     // if so, borrow its access specifier.
16265     if (PrevDecl)
16266       New->setAccess(PrevDecl->getAccess());
16267 
16268     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16269     DC->makeDeclVisibleInContext(New);
16270     if (Name) // can be null along some error paths
16271       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16272         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16273   } else if (Name) {
16274     S = getNonFieldDeclScope(S);
16275     PushOnScopeChains(New, S, true);
16276   } else {
16277     CurContext->addDecl(New);
16278   }
16279 
16280   // If this is the C FILE type, notify the AST context.
16281   if (IdentifierInfo *II = New->getIdentifier())
16282     if (!New->isInvalidDecl() &&
16283         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16284         II->isStr("FILE"))
16285       Context.setFILEDecl(New);
16286 
16287   if (PrevDecl)
16288     mergeDeclAttributes(New, PrevDecl);
16289 
16290   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16291     inferGslOwnerPointerAttribute(CXXRD);
16292 
16293   // If there's a #pragma GCC visibility in scope, set the visibility of this
16294   // record.
16295   AddPushedVisibilityAttribute(New);
16296 
16297   if (isMemberSpecialization && !New->isInvalidDecl())
16298     CompleteMemberSpecialization(New, Previous);
16299 
16300   OwnedDecl = true;
16301   // In C++, don't return an invalid declaration. We can't recover well from
16302   // the cases where we make the type anonymous.
16303   if (Invalid && getLangOpts().CPlusPlus) {
16304     if (New->isBeingDefined())
16305       if (auto RD = dyn_cast<RecordDecl>(New))
16306         RD->completeDefinition();
16307     return nullptr;
16308   } else if (SkipBody && SkipBody->ShouldSkip) {
16309     return SkipBody->Previous;
16310   } else {
16311     return New;
16312   }
16313 }
16314 
16315 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16316   AdjustDeclIfTemplate(TagD);
16317   TagDecl *Tag = cast<TagDecl>(TagD);
16318 
16319   // Enter the tag context.
16320   PushDeclContext(S, Tag);
16321 
16322   ActOnDocumentableDecl(TagD);
16323 
16324   // If there's a #pragma GCC visibility in scope, set the visibility of this
16325   // record.
16326   AddPushedVisibilityAttribute(Tag);
16327 }
16328 
16329 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16330                                     SkipBodyInfo &SkipBody) {
16331   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16332     return false;
16333 
16334   // Make the previous decl visible.
16335   makeMergedDefinitionVisible(SkipBody.Previous);
16336   return true;
16337 }
16338 
16339 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16340   assert(isa<ObjCContainerDecl>(IDecl) &&
16341          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16342   DeclContext *OCD = cast<DeclContext>(IDecl);
16343   assert(OCD->getLexicalParent() == CurContext &&
16344       "The next DeclContext should be lexically contained in the current one.");
16345   CurContext = OCD;
16346   return IDecl;
16347 }
16348 
16349 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16350                                            SourceLocation FinalLoc,
16351                                            bool IsFinalSpelledSealed,
16352                                            SourceLocation LBraceLoc) {
16353   AdjustDeclIfTemplate(TagD);
16354   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16355 
16356   FieldCollector->StartClass();
16357 
16358   if (!Record->getIdentifier())
16359     return;
16360 
16361   if (FinalLoc.isValid())
16362     Record->addAttr(FinalAttr::Create(
16363         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16364         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16365 
16366   // C++ [class]p2:
16367   //   [...] The class-name is also inserted into the scope of the
16368   //   class itself; this is known as the injected-class-name. For
16369   //   purposes of access checking, the injected-class-name is treated
16370   //   as if it were a public member name.
16371   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16372       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16373       Record->getLocation(), Record->getIdentifier(),
16374       /*PrevDecl=*/nullptr,
16375       /*DelayTypeCreation=*/true);
16376   Context.getTypeDeclType(InjectedClassName, Record);
16377   InjectedClassName->setImplicit();
16378   InjectedClassName->setAccess(AS_public);
16379   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16380       InjectedClassName->setDescribedClassTemplate(Template);
16381   PushOnScopeChains(InjectedClassName, S);
16382   assert(InjectedClassName->isInjectedClassName() &&
16383          "Broken injected-class-name");
16384 }
16385 
16386 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16387                                     SourceRange BraceRange) {
16388   AdjustDeclIfTemplate(TagD);
16389   TagDecl *Tag = cast<TagDecl>(TagD);
16390   Tag->setBraceRange(BraceRange);
16391 
16392   // Make sure we "complete" the definition even it is invalid.
16393   if (Tag->isBeingDefined()) {
16394     assert(Tag->isInvalidDecl() && "We should already have completed it");
16395     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16396       RD->completeDefinition();
16397   }
16398 
16399   if (isa<CXXRecordDecl>(Tag)) {
16400     FieldCollector->FinishClass();
16401   }
16402 
16403   // Exit this scope of this tag's definition.
16404   PopDeclContext();
16405 
16406   if (getCurLexicalContext()->isObjCContainer() &&
16407       Tag->getDeclContext()->isFileContext())
16408     Tag->setTopLevelDeclInObjCContainer();
16409 
16410   // Notify the consumer that we've defined a tag.
16411   if (!Tag->isInvalidDecl())
16412     Consumer.HandleTagDeclDefinition(Tag);
16413 }
16414 
16415 void Sema::ActOnObjCContainerFinishDefinition() {
16416   // Exit this scope of this interface definition.
16417   PopDeclContext();
16418 }
16419 
16420 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16421   assert(DC == CurContext && "Mismatch of container contexts");
16422   OriginalLexicalContext = DC;
16423   ActOnObjCContainerFinishDefinition();
16424 }
16425 
16426 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16427   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16428   OriginalLexicalContext = nullptr;
16429 }
16430 
16431 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16432   AdjustDeclIfTemplate(TagD);
16433   TagDecl *Tag = cast<TagDecl>(TagD);
16434   Tag->setInvalidDecl();
16435 
16436   // Make sure we "complete" the definition even it is invalid.
16437   if (Tag->isBeingDefined()) {
16438     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16439       RD->completeDefinition();
16440   }
16441 
16442   // We're undoing ActOnTagStartDefinition here, not
16443   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16444   // the FieldCollector.
16445 
16446   PopDeclContext();
16447 }
16448 
16449 // Note that FieldName may be null for anonymous bitfields.
16450 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16451                                 IdentifierInfo *FieldName,
16452                                 QualType FieldTy, bool IsMsStruct,
16453                                 Expr *BitWidth, bool *ZeroWidth) {
16454   assert(BitWidth);
16455   if (BitWidth->containsErrors())
16456     return ExprError();
16457 
16458   // Default to true; that shouldn't confuse checks for emptiness
16459   if (ZeroWidth)
16460     *ZeroWidth = true;
16461 
16462   // C99 6.7.2.1p4 - verify the field type.
16463   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16464   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16465     // Handle incomplete and sizeless types with a specific error.
16466     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16467                                  diag::err_field_incomplete_or_sizeless))
16468       return ExprError();
16469     if (FieldName)
16470       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16471         << FieldName << FieldTy << BitWidth->getSourceRange();
16472     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16473       << FieldTy << BitWidth->getSourceRange();
16474   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16475                                              UPPC_BitFieldWidth))
16476     return ExprError();
16477 
16478   // If the bit-width is type- or value-dependent, don't try to check
16479   // it now.
16480   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16481     return BitWidth;
16482 
16483   llvm::APSInt Value;
16484   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16485   if (ICE.isInvalid())
16486     return ICE;
16487   BitWidth = ICE.get();
16488 
16489   if (Value != 0 && ZeroWidth)
16490     *ZeroWidth = false;
16491 
16492   // Zero-width bitfield is ok for anonymous field.
16493   if (Value == 0 && FieldName)
16494     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16495 
16496   if (Value.isSigned() && Value.isNegative()) {
16497     if (FieldName)
16498       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16499                << FieldName << Value.toString(10);
16500     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16501       << Value.toString(10);
16502   }
16503 
16504   // The size of the bit-field must not exceed our maximum permitted object
16505   // size.
16506   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16507     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16508            << !FieldName << FieldName << Value.toString(10);
16509   }
16510 
16511   if (!FieldTy->isDependentType()) {
16512     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16513     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16514     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16515 
16516     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16517     // ABI.
16518     bool CStdConstraintViolation =
16519         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16520     bool MSBitfieldViolation =
16521         Value.ugt(TypeStorageSize) &&
16522         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16523     if (CStdConstraintViolation || MSBitfieldViolation) {
16524       unsigned DiagWidth =
16525           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16526       if (FieldName)
16527         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16528                << FieldName << Value.toString(10)
16529                << !CStdConstraintViolation << DiagWidth;
16530 
16531       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16532              << Value.toString(10) << !CStdConstraintViolation
16533              << DiagWidth;
16534     }
16535 
16536     // Warn on types where the user might conceivably expect to get all
16537     // specified bits as value bits: that's all integral types other than
16538     // 'bool'.
16539     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16540       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16541           << FieldName << Value.toString(10)
16542           << (unsigned)TypeWidth;
16543     }
16544   }
16545 
16546   return BitWidth;
16547 }
16548 
16549 /// ActOnField - Each field of a C struct/union is passed into this in order
16550 /// to create a FieldDecl object for it.
16551 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16552                        Declarator &D, Expr *BitfieldWidth) {
16553   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16554                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16555                                /*InitStyle=*/ICIS_NoInit, AS_public);
16556   return Res;
16557 }
16558 
16559 /// HandleField - Analyze a field of a C struct or a C++ data member.
16560 ///
16561 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16562                              SourceLocation DeclStart,
16563                              Declarator &D, Expr *BitWidth,
16564                              InClassInitStyle InitStyle,
16565                              AccessSpecifier AS) {
16566   if (D.isDecompositionDeclarator()) {
16567     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16568     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16569       << Decomp.getSourceRange();
16570     return nullptr;
16571   }
16572 
16573   IdentifierInfo *II = D.getIdentifier();
16574   SourceLocation Loc = DeclStart;
16575   if (II) Loc = D.getIdentifierLoc();
16576 
16577   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16578   QualType T = TInfo->getType();
16579   if (getLangOpts().CPlusPlus) {
16580     CheckExtraCXXDefaultArguments(D);
16581 
16582     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16583                                         UPPC_DataMemberType)) {
16584       D.setInvalidType();
16585       T = Context.IntTy;
16586       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16587     }
16588   }
16589 
16590   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16591 
16592   if (D.getDeclSpec().isInlineSpecified())
16593     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16594         << getLangOpts().CPlusPlus17;
16595   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16596     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16597          diag::err_invalid_thread)
16598       << DeclSpec::getSpecifierName(TSCS);
16599 
16600   // Check to see if this name was declared as a member previously
16601   NamedDecl *PrevDecl = nullptr;
16602   LookupResult Previous(*this, II, Loc, LookupMemberName,
16603                         ForVisibleRedeclaration);
16604   LookupName(Previous, S);
16605   switch (Previous.getResultKind()) {
16606     case LookupResult::Found:
16607     case LookupResult::FoundUnresolvedValue:
16608       PrevDecl = Previous.getAsSingle<NamedDecl>();
16609       break;
16610 
16611     case LookupResult::FoundOverloaded:
16612       PrevDecl = Previous.getRepresentativeDecl();
16613       break;
16614 
16615     case LookupResult::NotFound:
16616     case LookupResult::NotFoundInCurrentInstantiation:
16617     case LookupResult::Ambiguous:
16618       break;
16619   }
16620   Previous.suppressDiagnostics();
16621 
16622   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16623     // Maybe we will complain about the shadowed template parameter.
16624     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16625     // Just pretend that we didn't see the previous declaration.
16626     PrevDecl = nullptr;
16627   }
16628 
16629   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16630     PrevDecl = nullptr;
16631 
16632   bool Mutable
16633     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16634   SourceLocation TSSL = D.getBeginLoc();
16635   FieldDecl *NewFD
16636     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16637                      TSSL, AS, PrevDecl, &D);
16638 
16639   if (NewFD->isInvalidDecl())
16640     Record->setInvalidDecl();
16641 
16642   if (D.getDeclSpec().isModulePrivateSpecified())
16643     NewFD->setModulePrivate();
16644 
16645   if (NewFD->isInvalidDecl() && PrevDecl) {
16646     // Don't introduce NewFD into scope; there's already something
16647     // with the same name in the same scope.
16648   } else if (II) {
16649     PushOnScopeChains(NewFD, S);
16650   } else
16651     Record->addDecl(NewFD);
16652 
16653   return NewFD;
16654 }
16655 
16656 /// Build a new FieldDecl and check its well-formedness.
16657 ///
16658 /// This routine builds a new FieldDecl given the fields name, type,
16659 /// record, etc. \p PrevDecl should refer to any previous declaration
16660 /// with the same name and in the same scope as the field to be
16661 /// created.
16662 ///
16663 /// \returns a new FieldDecl.
16664 ///
16665 /// \todo The Declarator argument is a hack. It will be removed once
16666 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16667                                 TypeSourceInfo *TInfo,
16668                                 RecordDecl *Record, SourceLocation Loc,
16669                                 bool Mutable, Expr *BitWidth,
16670                                 InClassInitStyle InitStyle,
16671                                 SourceLocation TSSL,
16672                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16673                                 Declarator *D) {
16674   IdentifierInfo *II = Name.getAsIdentifierInfo();
16675   bool InvalidDecl = false;
16676   if (D) InvalidDecl = D->isInvalidType();
16677 
16678   // If we receive a broken type, recover by assuming 'int' and
16679   // marking this declaration as invalid.
16680   if (T.isNull() || T->containsErrors()) {
16681     InvalidDecl = true;
16682     T = Context.IntTy;
16683   }
16684 
16685   QualType EltTy = Context.getBaseElementType(T);
16686   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16687     if (RequireCompleteSizedType(Loc, EltTy,
16688                                  diag::err_field_incomplete_or_sizeless)) {
16689       // Fields of incomplete type force their record to be invalid.
16690       Record->setInvalidDecl();
16691       InvalidDecl = true;
16692     } else {
16693       NamedDecl *Def;
16694       EltTy->isIncompleteType(&Def);
16695       if (Def && Def->isInvalidDecl()) {
16696         Record->setInvalidDecl();
16697         InvalidDecl = true;
16698       }
16699     }
16700   }
16701 
16702   // TR 18037 does not allow fields to be declared with address space
16703   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16704       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16705     Diag(Loc, diag::err_field_with_address_space);
16706     Record->setInvalidDecl();
16707     InvalidDecl = true;
16708   }
16709 
16710   if (LangOpts.OpenCL) {
16711     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16712     // used as structure or union field: image, sampler, event or block types.
16713     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16714         T->isBlockPointerType()) {
16715       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16716       Record->setInvalidDecl();
16717       InvalidDecl = true;
16718     }
16719     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16720     if (BitWidth) {
16721       Diag(Loc, diag::err_opencl_bitfields);
16722       InvalidDecl = true;
16723     }
16724   }
16725 
16726   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16727   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16728       T.hasQualifiers()) {
16729     InvalidDecl = true;
16730     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16731   }
16732 
16733   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16734   // than a variably modified type.
16735   if (!InvalidDecl && T->isVariablyModifiedType()) {
16736     if (!tryToFixVariablyModifiedVarType(
16737             *this, TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16738       InvalidDecl = true;
16739   }
16740 
16741   // Fields can not have abstract class types
16742   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16743                                              diag::err_abstract_type_in_decl,
16744                                              AbstractFieldType))
16745     InvalidDecl = true;
16746 
16747   bool ZeroWidth = false;
16748   if (InvalidDecl)
16749     BitWidth = nullptr;
16750   // If this is declared as a bit-field, check the bit-field.
16751   if (BitWidth) {
16752     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16753                               &ZeroWidth).get();
16754     if (!BitWidth) {
16755       InvalidDecl = true;
16756       BitWidth = nullptr;
16757       ZeroWidth = false;
16758     }
16759   }
16760 
16761   // Check that 'mutable' is consistent with the type of the declaration.
16762   if (!InvalidDecl && Mutable) {
16763     unsigned DiagID = 0;
16764     if (T->isReferenceType())
16765       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16766                                         : diag::err_mutable_reference;
16767     else if (T.isConstQualified())
16768       DiagID = diag::err_mutable_const;
16769 
16770     if (DiagID) {
16771       SourceLocation ErrLoc = Loc;
16772       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16773         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16774       Diag(ErrLoc, DiagID);
16775       if (DiagID != diag::ext_mutable_reference) {
16776         Mutable = false;
16777         InvalidDecl = true;
16778       }
16779     }
16780   }
16781 
16782   // C++11 [class.union]p8 (DR1460):
16783   //   At most one variant member of a union may have a
16784   //   brace-or-equal-initializer.
16785   if (InitStyle != ICIS_NoInit)
16786     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16787 
16788   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16789                                        BitWidth, Mutable, InitStyle);
16790   if (InvalidDecl)
16791     NewFD->setInvalidDecl();
16792 
16793   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16794     Diag(Loc, diag::err_duplicate_member) << II;
16795     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16796     NewFD->setInvalidDecl();
16797   }
16798 
16799   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16800     if (Record->isUnion()) {
16801       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16802         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16803         if (RDecl->getDefinition()) {
16804           // C++ [class.union]p1: An object of a class with a non-trivial
16805           // constructor, a non-trivial copy constructor, a non-trivial
16806           // destructor, or a non-trivial copy assignment operator
16807           // cannot be a member of a union, nor can an array of such
16808           // objects.
16809           if (CheckNontrivialField(NewFD))
16810             NewFD->setInvalidDecl();
16811         }
16812       }
16813 
16814       // C++ [class.union]p1: If a union contains a member of reference type,
16815       // the program is ill-formed, except when compiling with MSVC extensions
16816       // enabled.
16817       if (EltTy->isReferenceType()) {
16818         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16819                                     diag::ext_union_member_of_reference_type :
16820                                     diag::err_union_member_of_reference_type)
16821           << NewFD->getDeclName() << EltTy;
16822         if (!getLangOpts().MicrosoftExt)
16823           NewFD->setInvalidDecl();
16824       }
16825     }
16826   }
16827 
16828   // FIXME: We need to pass in the attributes given an AST
16829   // representation, not a parser representation.
16830   if (D) {
16831     // FIXME: The current scope is almost... but not entirely... correct here.
16832     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16833 
16834     if (NewFD->hasAttrs())
16835       CheckAlignasUnderalignment(NewFD);
16836   }
16837 
16838   // In auto-retain/release, infer strong retension for fields of
16839   // retainable type.
16840   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16841     NewFD->setInvalidDecl();
16842 
16843   if (T.isObjCGCWeak())
16844     Diag(Loc, diag::warn_attribute_weak_on_field);
16845 
16846   // PPC MMA non-pointer types are not allowed as field types.
16847   if (Context.getTargetInfo().getTriple().isPPC64() &&
16848       CheckPPCMMAType(T, NewFD->getLocation()))
16849     NewFD->setInvalidDecl();
16850 
16851   NewFD->setAccess(AS);
16852   return NewFD;
16853 }
16854 
16855 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16856   assert(FD);
16857   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16858 
16859   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16860     return false;
16861 
16862   QualType EltTy = Context.getBaseElementType(FD->getType());
16863   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16864     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16865     if (RDecl->getDefinition()) {
16866       // We check for copy constructors before constructors
16867       // because otherwise we'll never get complaints about
16868       // copy constructors.
16869 
16870       CXXSpecialMember member = CXXInvalid;
16871       // We're required to check for any non-trivial constructors. Since the
16872       // implicit default constructor is suppressed if there are any
16873       // user-declared constructors, we just need to check that there is a
16874       // trivial default constructor and a trivial copy constructor. (We don't
16875       // worry about move constructors here, since this is a C++98 check.)
16876       if (RDecl->hasNonTrivialCopyConstructor())
16877         member = CXXCopyConstructor;
16878       else if (!RDecl->hasTrivialDefaultConstructor())
16879         member = CXXDefaultConstructor;
16880       else if (RDecl->hasNonTrivialCopyAssignment())
16881         member = CXXCopyAssignment;
16882       else if (RDecl->hasNonTrivialDestructor())
16883         member = CXXDestructor;
16884 
16885       if (member != CXXInvalid) {
16886         if (!getLangOpts().CPlusPlus11 &&
16887             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16888           // Objective-C++ ARC: it is an error to have a non-trivial field of
16889           // a union. However, system headers in Objective-C programs
16890           // occasionally have Objective-C lifetime objects within unions,
16891           // and rather than cause the program to fail, we make those
16892           // members unavailable.
16893           SourceLocation Loc = FD->getLocation();
16894           if (getSourceManager().isInSystemHeader(Loc)) {
16895             if (!FD->hasAttr<UnavailableAttr>())
16896               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16897                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16898             return false;
16899           }
16900         }
16901 
16902         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16903                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16904                diag::err_illegal_union_or_anon_struct_member)
16905           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16906         DiagnoseNontrivial(RDecl, member);
16907         return !getLangOpts().CPlusPlus11;
16908       }
16909     }
16910   }
16911 
16912   return false;
16913 }
16914 
16915 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16916 ///  AST enum value.
16917 static ObjCIvarDecl::AccessControl
16918 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16919   switch (ivarVisibility) {
16920   default: llvm_unreachable("Unknown visitibility kind");
16921   case tok::objc_private: return ObjCIvarDecl::Private;
16922   case tok::objc_public: return ObjCIvarDecl::Public;
16923   case tok::objc_protected: return ObjCIvarDecl::Protected;
16924   case tok::objc_package: return ObjCIvarDecl::Package;
16925   }
16926 }
16927 
16928 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16929 /// in order to create an IvarDecl object for it.
16930 Decl *Sema::ActOnIvar(Scope *S,
16931                                 SourceLocation DeclStart,
16932                                 Declarator &D, Expr *BitfieldWidth,
16933                                 tok::ObjCKeywordKind Visibility) {
16934 
16935   IdentifierInfo *II = D.getIdentifier();
16936   Expr *BitWidth = (Expr*)BitfieldWidth;
16937   SourceLocation Loc = DeclStart;
16938   if (II) Loc = D.getIdentifierLoc();
16939 
16940   // FIXME: Unnamed fields can be handled in various different ways, for
16941   // example, unnamed unions inject all members into the struct namespace!
16942 
16943   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16944   QualType T = TInfo->getType();
16945 
16946   if (BitWidth) {
16947     // 6.7.2.1p3, 6.7.2.1p4
16948     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16949     if (!BitWidth)
16950       D.setInvalidType();
16951   } else {
16952     // Not a bitfield.
16953 
16954     // validate II.
16955 
16956   }
16957   if (T->isReferenceType()) {
16958     Diag(Loc, diag::err_ivar_reference_type);
16959     D.setInvalidType();
16960   }
16961   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16962   // than a variably modified type.
16963   else if (T->isVariablyModifiedType()) {
16964     if (!tryToFixVariablyModifiedVarType(
16965             *this, TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
16966       D.setInvalidType();
16967   }
16968 
16969   // Get the visibility (access control) for this ivar.
16970   ObjCIvarDecl::AccessControl ac =
16971     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16972                                         : ObjCIvarDecl::None;
16973   // Must set ivar's DeclContext to its enclosing interface.
16974   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16975   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16976     return nullptr;
16977   ObjCContainerDecl *EnclosingContext;
16978   if (ObjCImplementationDecl *IMPDecl =
16979       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16980     if (LangOpts.ObjCRuntime.isFragile()) {
16981     // Case of ivar declared in an implementation. Context is that of its class.
16982       EnclosingContext = IMPDecl->getClassInterface();
16983       assert(EnclosingContext && "Implementation has no class interface!");
16984     }
16985     else
16986       EnclosingContext = EnclosingDecl;
16987   } else {
16988     if (ObjCCategoryDecl *CDecl =
16989         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16990       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16991         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16992         return nullptr;
16993       }
16994     }
16995     EnclosingContext = EnclosingDecl;
16996   }
16997 
16998   // Construct the decl.
16999   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17000                                              DeclStart, Loc, II, T,
17001                                              TInfo, ac, (Expr *)BitfieldWidth);
17002 
17003   if (II) {
17004     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17005                                            ForVisibleRedeclaration);
17006     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17007         && !isa<TagDecl>(PrevDecl)) {
17008       Diag(Loc, diag::err_duplicate_member) << II;
17009       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17010       NewID->setInvalidDecl();
17011     }
17012   }
17013 
17014   // Process attributes attached to the ivar.
17015   ProcessDeclAttributes(S, NewID, D);
17016 
17017   if (D.isInvalidType())
17018     NewID->setInvalidDecl();
17019 
17020   // In ARC, infer 'retaining' for ivars of retainable type.
17021   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17022     NewID->setInvalidDecl();
17023 
17024   if (D.getDeclSpec().isModulePrivateSpecified())
17025     NewID->setModulePrivate();
17026 
17027   if (II) {
17028     // FIXME: When interfaces are DeclContexts, we'll need to add
17029     // these to the interface.
17030     S->AddDecl(NewID);
17031     IdResolver.AddDecl(NewID);
17032   }
17033 
17034   if (LangOpts.ObjCRuntime.isNonFragile() &&
17035       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17036     Diag(Loc, diag::warn_ivars_in_interface);
17037 
17038   return NewID;
17039 }
17040 
17041 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17042 /// class and class extensions. For every class \@interface and class
17043 /// extension \@interface, if the last ivar is a bitfield of any type,
17044 /// then add an implicit `char :0` ivar to the end of that interface.
17045 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17046                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17047   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17048     return;
17049 
17050   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17051   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17052 
17053   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17054     return;
17055   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17056   if (!ID) {
17057     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17058       if (!CD->IsClassExtension())
17059         return;
17060     }
17061     // No need to add this to end of @implementation.
17062     else
17063       return;
17064   }
17065   // All conditions are met. Add a new bitfield to the tail end of ivars.
17066   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17067   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17068 
17069   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17070                               DeclLoc, DeclLoc, nullptr,
17071                               Context.CharTy,
17072                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17073                                                                DeclLoc),
17074                               ObjCIvarDecl::Private, BW,
17075                               true);
17076   AllIvarDecls.push_back(Ivar);
17077 }
17078 
17079 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17080                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17081                        SourceLocation RBrac,
17082                        const ParsedAttributesView &Attrs) {
17083   assert(EnclosingDecl && "missing record or interface decl");
17084 
17085   // If this is an Objective-C @implementation or category and we have
17086   // new fields here we should reset the layout of the interface since
17087   // it will now change.
17088   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17089     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17090     switch (DC->getKind()) {
17091     default: break;
17092     case Decl::ObjCCategory:
17093       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17094       break;
17095     case Decl::ObjCImplementation:
17096       Context.
17097         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17098       break;
17099     }
17100   }
17101 
17102   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17103   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17104 
17105   // Start counting up the number of named members; make sure to include
17106   // members of anonymous structs and unions in the total.
17107   unsigned NumNamedMembers = 0;
17108   if (Record) {
17109     for (const auto *I : Record->decls()) {
17110       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17111         if (IFD->getDeclName())
17112           ++NumNamedMembers;
17113     }
17114   }
17115 
17116   // Verify that all the fields are okay.
17117   SmallVector<FieldDecl*, 32> RecFields;
17118 
17119   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17120        i != end; ++i) {
17121     FieldDecl *FD = cast<FieldDecl>(*i);
17122 
17123     // Get the type for the field.
17124     const Type *FDTy = FD->getType().getTypePtr();
17125 
17126     if (!FD->isAnonymousStructOrUnion()) {
17127       // Remember all fields written by the user.
17128       RecFields.push_back(FD);
17129     }
17130 
17131     // If the field is already invalid for some reason, don't emit more
17132     // diagnostics about it.
17133     if (FD->isInvalidDecl()) {
17134       EnclosingDecl->setInvalidDecl();
17135       continue;
17136     }
17137 
17138     // C99 6.7.2.1p2:
17139     //   A structure or union shall not contain a member with
17140     //   incomplete or function type (hence, a structure shall not
17141     //   contain an instance of itself, but may contain a pointer to
17142     //   an instance of itself), except that the last member of a
17143     //   structure with more than one named member may have incomplete
17144     //   array type; such a structure (and any union containing,
17145     //   possibly recursively, a member that is such a structure)
17146     //   shall not be a member of a structure or an element of an
17147     //   array.
17148     bool IsLastField = (i + 1 == Fields.end());
17149     if (FDTy->isFunctionType()) {
17150       // Field declared as a function.
17151       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17152         << FD->getDeclName();
17153       FD->setInvalidDecl();
17154       EnclosingDecl->setInvalidDecl();
17155       continue;
17156     } else if (FDTy->isIncompleteArrayType() &&
17157                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17158       if (Record) {
17159         // Flexible array member.
17160         // Microsoft and g++ is more permissive regarding flexible array.
17161         // It will accept flexible array in union and also
17162         // as the sole element of a struct/class.
17163         unsigned DiagID = 0;
17164         if (!Record->isUnion() && !IsLastField) {
17165           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17166             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17167           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17168           FD->setInvalidDecl();
17169           EnclosingDecl->setInvalidDecl();
17170           continue;
17171         } else if (Record->isUnion())
17172           DiagID = getLangOpts().MicrosoftExt
17173                        ? diag::ext_flexible_array_union_ms
17174                        : getLangOpts().CPlusPlus
17175                              ? diag::ext_flexible_array_union_gnu
17176                              : diag::err_flexible_array_union;
17177         else if (NumNamedMembers < 1)
17178           DiagID = getLangOpts().MicrosoftExt
17179                        ? diag::ext_flexible_array_empty_aggregate_ms
17180                        : getLangOpts().CPlusPlus
17181                              ? diag::ext_flexible_array_empty_aggregate_gnu
17182                              : diag::err_flexible_array_empty_aggregate;
17183 
17184         if (DiagID)
17185           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17186                                           << Record->getTagKind();
17187         // While the layout of types that contain virtual bases is not specified
17188         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17189         // virtual bases after the derived members.  This would make a flexible
17190         // array member declared at the end of an object not adjacent to the end
17191         // of the type.
17192         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17193           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17194               << FD->getDeclName() << Record->getTagKind();
17195         if (!getLangOpts().C99)
17196           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17197             << FD->getDeclName() << Record->getTagKind();
17198 
17199         // If the element type has a non-trivial destructor, we would not
17200         // implicitly destroy the elements, so disallow it for now.
17201         //
17202         // FIXME: GCC allows this. We should probably either implicitly delete
17203         // the destructor of the containing class, or just allow this.
17204         QualType BaseElem = Context.getBaseElementType(FD->getType());
17205         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17206           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17207             << FD->getDeclName() << FD->getType();
17208           FD->setInvalidDecl();
17209           EnclosingDecl->setInvalidDecl();
17210           continue;
17211         }
17212         // Okay, we have a legal flexible array member at the end of the struct.
17213         Record->setHasFlexibleArrayMember(true);
17214       } else {
17215         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17216         // unless they are followed by another ivar. That check is done
17217         // elsewhere, after synthesized ivars are known.
17218       }
17219     } else if (!FDTy->isDependentType() &&
17220                RequireCompleteSizedType(
17221                    FD->getLocation(), FD->getType(),
17222                    diag::err_field_incomplete_or_sizeless)) {
17223       // Incomplete type
17224       FD->setInvalidDecl();
17225       EnclosingDecl->setInvalidDecl();
17226       continue;
17227     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17228       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17229         // A type which contains a flexible array member is considered to be a
17230         // flexible array member.
17231         Record->setHasFlexibleArrayMember(true);
17232         if (!Record->isUnion()) {
17233           // If this is a struct/class and this is not the last element, reject
17234           // it.  Note that GCC supports variable sized arrays in the middle of
17235           // structures.
17236           if (!IsLastField)
17237             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17238               << FD->getDeclName() << FD->getType();
17239           else {
17240             // We support flexible arrays at the end of structs in
17241             // other structs as an extension.
17242             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17243               << FD->getDeclName();
17244           }
17245         }
17246       }
17247       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17248           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17249                                  diag::err_abstract_type_in_decl,
17250                                  AbstractIvarType)) {
17251         // Ivars can not have abstract class types
17252         FD->setInvalidDecl();
17253       }
17254       if (Record && FDTTy->getDecl()->hasObjectMember())
17255         Record->setHasObjectMember(true);
17256       if (Record && FDTTy->getDecl()->hasVolatileMember())
17257         Record->setHasVolatileMember(true);
17258     } else if (FDTy->isObjCObjectType()) {
17259       /// A field cannot be an Objective-c object
17260       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17261         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17262       QualType T = Context.getObjCObjectPointerType(FD->getType());
17263       FD->setType(T);
17264     } else if (Record && Record->isUnion() &&
17265                FD->getType().hasNonTrivialObjCLifetime() &&
17266                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17267                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17268                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17269                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17270       // For backward compatibility, fields of C unions declared in system
17271       // headers that have non-trivial ObjC ownership qualifications are marked
17272       // as unavailable unless the qualifier is explicit and __strong. This can
17273       // break ABI compatibility between programs compiled with ARC and MRR, but
17274       // is a better option than rejecting programs using those unions under
17275       // ARC.
17276       FD->addAttr(UnavailableAttr::CreateImplicit(
17277           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17278           FD->getLocation()));
17279     } else if (getLangOpts().ObjC &&
17280                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17281                !Record->hasObjectMember()) {
17282       if (FD->getType()->isObjCObjectPointerType() ||
17283           FD->getType().isObjCGCStrong())
17284         Record->setHasObjectMember(true);
17285       else if (Context.getAsArrayType(FD->getType())) {
17286         QualType BaseType = Context.getBaseElementType(FD->getType());
17287         if (BaseType->isRecordType() &&
17288             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17289           Record->setHasObjectMember(true);
17290         else if (BaseType->isObjCObjectPointerType() ||
17291                  BaseType.isObjCGCStrong())
17292                Record->setHasObjectMember(true);
17293       }
17294     }
17295 
17296     if (Record && !getLangOpts().CPlusPlus &&
17297         !shouldIgnoreForRecordTriviality(FD)) {
17298       QualType FT = FD->getType();
17299       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17300         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17301         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17302             Record->isUnion())
17303           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17304       }
17305       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17306       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17307         Record->setNonTrivialToPrimitiveCopy(true);
17308         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17309           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17310       }
17311       if (FT.isDestructedType()) {
17312         Record->setNonTrivialToPrimitiveDestroy(true);
17313         Record->setParamDestroyedInCallee(true);
17314         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17315           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17316       }
17317 
17318       if (const auto *RT = FT->getAs<RecordType>()) {
17319         if (RT->getDecl()->getArgPassingRestrictions() ==
17320             RecordDecl::APK_CanNeverPassInRegs)
17321           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17322       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17323         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17324     }
17325 
17326     if (Record && FD->getType().isVolatileQualified())
17327       Record->setHasVolatileMember(true);
17328     // Keep track of the number of named members.
17329     if (FD->getIdentifier())
17330       ++NumNamedMembers;
17331   }
17332 
17333   // Okay, we successfully defined 'Record'.
17334   if (Record) {
17335     bool Completed = false;
17336     if (CXXRecord) {
17337       if (!CXXRecord->isInvalidDecl()) {
17338         // Set access bits correctly on the directly-declared conversions.
17339         for (CXXRecordDecl::conversion_iterator
17340                I = CXXRecord->conversion_begin(),
17341                E = CXXRecord->conversion_end(); I != E; ++I)
17342           I.setAccess((*I)->getAccess());
17343       }
17344 
17345       // Add any implicitly-declared members to this class.
17346       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17347 
17348       if (!CXXRecord->isDependentType()) {
17349         if (!CXXRecord->isInvalidDecl()) {
17350           // If we have virtual base classes, we may end up finding multiple
17351           // final overriders for a given virtual function. Check for this
17352           // problem now.
17353           if (CXXRecord->getNumVBases()) {
17354             CXXFinalOverriderMap FinalOverriders;
17355             CXXRecord->getFinalOverriders(FinalOverriders);
17356 
17357             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17358                                              MEnd = FinalOverriders.end();
17359                  M != MEnd; ++M) {
17360               for (OverridingMethods::iterator SO = M->second.begin(),
17361                                             SOEnd = M->second.end();
17362                    SO != SOEnd; ++SO) {
17363                 assert(SO->second.size() > 0 &&
17364                        "Virtual function without overriding functions?");
17365                 if (SO->second.size() == 1)
17366                   continue;
17367 
17368                 // C++ [class.virtual]p2:
17369                 //   In a derived class, if a virtual member function of a base
17370                 //   class subobject has more than one final overrider the
17371                 //   program is ill-formed.
17372                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17373                   << (const NamedDecl *)M->first << Record;
17374                 Diag(M->first->getLocation(),
17375                      diag::note_overridden_virtual_function);
17376                 for (OverridingMethods::overriding_iterator
17377                           OM = SO->second.begin(),
17378                        OMEnd = SO->second.end();
17379                      OM != OMEnd; ++OM)
17380                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17381                     << (const NamedDecl *)M->first << OM->Method->getParent();
17382 
17383                 Record->setInvalidDecl();
17384               }
17385             }
17386             CXXRecord->completeDefinition(&FinalOverriders);
17387             Completed = true;
17388           }
17389         }
17390       }
17391     }
17392 
17393     if (!Completed)
17394       Record->completeDefinition();
17395 
17396     // Handle attributes before checking the layout.
17397     ProcessDeclAttributeList(S, Record, Attrs);
17398 
17399     // We may have deferred checking for a deleted destructor. Check now.
17400     if (CXXRecord) {
17401       auto *Dtor = CXXRecord->getDestructor();
17402       if (Dtor && Dtor->isImplicit() &&
17403           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17404         CXXRecord->setImplicitDestructorIsDeleted();
17405         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17406       }
17407     }
17408 
17409     if (Record->hasAttrs()) {
17410       CheckAlignasUnderalignment(Record);
17411 
17412       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17413         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17414                                            IA->getRange(), IA->getBestCase(),
17415                                            IA->getInheritanceModel());
17416     }
17417 
17418     // Check if the structure/union declaration is a type that can have zero
17419     // size in C. For C this is a language extension, for C++ it may cause
17420     // compatibility problems.
17421     bool CheckForZeroSize;
17422     if (!getLangOpts().CPlusPlus) {
17423       CheckForZeroSize = true;
17424     } else {
17425       // For C++ filter out types that cannot be referenced in C code.
17426       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17427       CheckForZeroSize =
17428           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17429           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17430           CXXRecord->isCLike();
17431     }
17432     if (CheckForZeroSize) {
17433       bool ZeroSize = true;
17434       bool IsEmpty = true;
17435       unsigned NonBitFields = 0;
17436       for (RecordDecl::field_iterator I = Record->field_begin(),
17437                                       E = Record->field_end();
17438            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17439         IsEmpty = false;
17440         if (I->isUnnamedBitfield()) {
17441           if (!I->isZeroLengthBitField(Context))
17442             ZeroSize = false;
17443         } else {
17444           ++NonBitFields;
17445           QualType FieldType = I->getType();
17446           if (FieldType->isIncompleteType() ||
17447               !Context.getTypeSizeInChars(FieldType).isZero())
17448             ZeroSize = false;
17449         }
17450       }
17451 
17452       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17453       // allowed in C++, but warn if its declaration is inside
17454       // extern "C" block.
17455       if (ZeroSize) {
17456         Diag(RecLoc, getLangOpts().CPlusPlus ?
17457                          diag::warn_zero_size_struct_union_in_extern_c :
17458                          diag::warn_zero_size_struct_union_compat)
17459           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17460       }
17461 
17462       // Structs without named members are extension in C (C99 6.7.2.1p7),
17463       // but are accepted by GCC.
17464       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17465         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17466                                diag::ext_no_named_members_in_struct_union)
17467           << Record->isUnion();
17468       }
17469     }
17470   } else {
17471     ObjCIvarDecl **ClsFields =
17472       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17473     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17474       ID->setEndOfDefinitionLoc(RBrac);
17475       // Add ivar's to class's DeclContext.
17476       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17477         ClsFields[i]->setLexicalDeclContext(ID);
17478         ID->addDecl(ClsFields[i]);
17479       }
17480       // Must enforce the rule that ivars in the base classes may not be
17481       // duplicates.
17482       if (ID->getSuperClass())
17483         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17484     } else if (ObjCImplementationDecl *IMPDecl =
17485                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17486       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17487       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17488         // Ivar declared in @implementation never belongs to the implementation.
17489         // Only it is in implementation's lexical context.
17490         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17491       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17492       IMPDecl->setIvarLBraceLoc(LBrac);
17493       IMPDecl->setIvarRBraceLoc(RBrac);
17494     } else if (ObjCCategoryDecl *CDecl =
17495                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17496       // case of ivars in class extension; all other cases have been
17497       // reported as errors elsewhere.
17498       // FIXME. Class extension does not have a LocEnd field.
17499       // CDecl->setLocEnd(RBrac);
17500       // Add ivar's to class extension's DeclContext.
17501       // Diagnose redeclaration of private ivars.
17502       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17503       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17504         if (IDecl) {
17505           if (const ObjCIvarDecl *ClsIvar =
17506               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17507             Diag(ClsFields[i]->getLocation(),
17508                  diag::err_duplicate_ivar_declaration);
17509             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17510             continue;
17511           }
17512           for (const auto *Ext : IDecl->known_extensions()) {
17513             if (const ObjCIvarDecl *ClsExtIvar
17514                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17515               Diag(ClsFields[i]->getLocation(),
17516                    diag::err_duplicate_ivar_declaration);
17517               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17518               continue;
17519             }
17520           }
17521         }
17522         ClsFields[i]->setLexicalDeclContext(CDecl);
17523         CDecl->addDecl(ClsFields[i]);
17524       }
17525       CDecl->setIvarLBraceLoc(LBrac);
17526       CDecl->setIvarRBraceLoc(RBrac);
17527     }
17528   }
17529 }
17530 
17531 /// Determine whether the given integral value is representable within
17532 /// the given type T.
17533 static bool isRepresentableIntegerValue(ASTContext &Context,
17534                                         llvm::APSInt &Value,
17535                                         QualType T) {
17536   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17537          "Integral type required!");
17538   unsigned BitWidth = Context.getIntWidth(T);
17539 
17540   if (Value.isUnsigned() || Value.isNonNegative()) {
17541     if (T->isSignedIntegerOrEnumerationType())
17542       --BitWidth;
17543     return Value.getActiveBits() <= BitWidth;
17544   }
17545   return Value.getMinSignedBits() <= BitWidth;
17546 }
17547 
17548 // Given an integral type, return the next larger integral type
17549 // (or a NULL type of no such type exists).
17550 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17551   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17552   // enum checking below.
17553   assert((T->isIntegralType(Context) ||
17554          T->isEnumeralType()) && "Integral type required!");
17555   const unsigned NumTypes = 4;
17556   QualType SignedIntegralTypes[NumTypes] = {
17557     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17558   };
17559   QualType UnsignedIntegralTypes[NumTypes] = {
17560     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17561     Context.UnsignedLongLongTy
17562   };
17563 
17564   unsigned BitWidth = Context.getTypeSize(T);
17565   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17566                                                         : UnsignedIntegralTypes;
17567   for (unsigned I = 0; I != NumTypes; ++I)
17568     if (Context.getTypeSize(Types[I]) > BitWidth)
17569       return Types[I];
17570 
17571   return QualType();
17572 }
17573 
17574 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17575                                           EnumConstantDecl *LastEnumConst,
17576                                           SourceLocation IdLoc,
17577                                           IdentifierInfo *Id,
17578                                           Expr *Val) {
17579   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17580   llvm::APSInt EnumVal(IntWidth);
17581   QualType EltTy;
17582 
17583   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17584     Val = nullptr;
17585 
17586   if (Val)
17587     Val = DefaultLvalueConversion(Val).get();
17588 
17589   if (Val) {
17590     if (Enum->isDependentType() || Val->isTypeDependent())
17591       EltTy = Context.DependentTy;
17592     else {
17593       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17594       // underlying type, but do allow it in all other contexts.
17595       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17596         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17597         // constant-expression in the enumerator-definition shall be a converted
17598         // constant expression of the underlying type.
17599         EltTy = Enum->getIntegerType();
17600         ExprResult Converted =
17601           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17602                                            CCEK_Enumerator);
17603         if (Converted.isInvalid())
17604           Val = nullptr;
17605         else
17606           Val = Converted.get();
17607       } else if (!Val->isValueDependent() &&
17608                  !(Val =
17609                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17610                            .get())) {
17611         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17612       } else {
17613         if (Enum->isComplete()) {
17614           EltTy = Enum->getIntegerType();
17615 
17616           // In Obj-C and Microsoft mode, require the enumeration value to be
17617           // representable in the underlying type of the enumeration. In C++11,
17618           // we perform a non-narrowing conversion as part of converted constant
17619           // expression checking.
17620           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17621             if (Context.getTargetInfo()
17622                     .getTriple()
17623                     .isWindowsMSVCEnvironment()) {
17624               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17625             } else {
17626               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17627             }
17628           }
17629 
17630           // Cast to the underlying type.
17631           Val = ImpCastExprToType(Val, EltTy,
17632                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17633                                                          : CK_IntegralCast)
17634                     .get();
17635         } else if (getLangOpts().CPlusPlus) {
17636           // C++11 [dcl.enum]p5:
17637           //   If the underlying type is not fixed, the type of each enumerator
17638           //   is the type of its initializing value:
17639           //     - If an initializer is specified for an enumerator, the
17640           //       initializing value has the same type as the expression.
17641           EltTy = Val->getType();
17642         } else {
17643           // C99 6.7.2.2p2:
17644           //   The expression that defines the value of an enumeration constant
17645           //   shall be an integer constant expression that has a value
17646           //   representable as an int.
17647 
17648           // Complain if the value is not representable in an int.
17649           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17650             Diag(IdLoc, diag::ext_enum_value_not_int)
17651               << EnumVal.toString(10) << Val->getSourceRange()
17652               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17653           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17654             // Force the type of the expression to 'int'.
17655             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17656           }
17657           EltTy = Val->getType();
17658         }
17659       }
17660     }
17661   }
17662 
17663   if (!Val) {
17664     if (Enum->isDependentType())
17665       EltTy = Context.DependentTy;
17666     else if (!LastEnumConst) {
17667       // C++0x [dcl.enum]p5:
17668       //   If the underlying type is not fixed, the type of each enumerator
17669       //   is the type of its initializing value:
17670       //     - If no initializer is specified for the first enumerator, the
17671       //       initializing value has an unspecified integral type.
17672       //
17673       // GCC uses 'int' for its unspecified integral type, as does
17674       // C99 6.7.2.2p3.
17675       if (Enum->isFixed()) {
17676         EltTy = Enum->getIntegerType();
17677       }
17678       else {
17679         EltTy = Context.IntTy;
17680       }
17681     } else {
17682       // Assign the last value + 1.
17683       EnumVal = LastEnumConst->getInitVal();
17684       ++EnumVal;
17685       EltTy = LastEnumConst->getType();
17686 
17687       // Check for overflow on increment.
17688       if (EnumVal < LastEnumConst->getInitVal()) {
17689         // C++0x [dcl.enum]p5:
17690         //   If the underlying type is not fixed, the type of each enumerator
17691         //   is the type of its initializing value:
17692         //
17693         //     - Otherwise the type of the initializing value is the same as
17694         //       the type of the initializing value of the preceding enumerator
17695         //       unless the incremented value is not representable in that type,
17696         //       in which case the type is an unspecified integral type
17697         //       sufficient to contain the incremented value. If no such type
17698         //       exists, the program is ill-formed.
17699         QualType T = getNextLargerIntegralType(Context, EltTy);
17700         if (T.isNull() || Enum->isFixed()) {
17701           // There is no integral type larger enough to represent this
17702           // value. Complain, then allow the value to wrap around.
17703           EnumVal = LastEnumConst->getInitVal();
17704           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17705           ++EnumVal;
17706           if (Enum->isFixed())
17707             // When the underlying type is fixed, this is ill-formed.
17708             Diag(IdLoc, diag::err_enumerator_wrapped)
17709               << EnumVal.toString(10)
17710               << EltTy;
17711           else
17712             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17713               << EnumVal.toString(10);
17714         } else {
17715           EltTy = T;
17716         }
17717 
17718         // Retrieve the last enumerator's value, extent that type to the
17719         // type that is supposed to be large enough to represent the incremented
17720         // value, then increment.
17721         EnumVal = LastEnumConst->getInitVal();
17722         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17723         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17724         ++EnumVal;
17725 
17726         // If we're not in C++, diagnose the overflow of enumerator values,
17727         // which in C99 means that the enumerator value is not representable in
17728         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17729         // permits enumerator values that are representable in some larger
17730         // integral type.
17731         if (!getLangOpts().CPlusPlus && !T.isNull())
17732           Diag(IdLoc, diag::warn_enum_value_overflow);
17733       } else if (!getLangOpts().CPlusPlus &&
17734                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17735         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17736         Diag(IdLoc, diag::ext_enum_value_not_int)
17737           << EnumVal.toString(10) << 1;
17738       }
17739     }
17740   }
17741 
17742   if (!EltTy->isDependentType()) {
17743     // Make the enumerator value match the signedness and size of the
17744     // enumerator's type.
17745     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17746     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17747   }
17748 
17749   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17750                                   Val, EnumVal);
17751 }
17752 
17753 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17754                                                 SourceLocation IILoc) {
17755   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17756       !getLangOpts().CPlusPlus)
17757     return SkipBodyInfo();
17758 
17759   // We have an anonymous enum definition. Look up the first enumerator to
17760   // determine if we should merge the definition with an existing one and
17761   // skip the body.
17762   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17763                                          forRedeclarationInCurContext());
17764   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17765   if (!PrevECD)
17766     return SkipBodyInfo();
17767 
17768   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17769   NamedDecl *Hidden;
17770   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17771     SkipBodyInfo Skip;
17772     Skip.Previous = Hidden;
17773     return Skip;
17774   }
17775 
17776   return SkipBodyInfo();
17777 }
17778 
17779 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17780                               SourceLocation IdLoc, IdentifierInfo *Id,
17781                               const ParsedAttributesView &Attrs,
17782                               SourceLocation EqualLoc, Expr *Val) {
17783   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17784   EnumConstantDecl *LastEnumConst =
17785     cast_or_null<EnumConstantDecl>(lastEnumConst);
17786 
17787   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17788   // we find one that is.
17789   S = getNonFieldDeclScope(S);
17790 
17791   // Verify that there isn't already something declared with this name in this
17792   // scope.
17793   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17794   LookupName(R, S);
17795   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17796 
17797   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17798     // Maybe we will complain about the shadowed template parameter.
17799     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17800     // Just pretend that we didn't see the previous declaration.
17801     PrevDecl = nullptr;
17802   }
17803 
17804   // C++ [class.mem]p15:
17805   // If T is the name of a class, then each of the following shall have a name
17806   // different from T:
17807   // - every enumerator of every member of class T that is an unscoped
17808   // enumerated type
17809   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17810     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17811                             DeclarationNameInfo(Id, IdLoc));
17812 
17813   EnumConstantDecl *New =
17814     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17815   if (!New)
17816     return nullptr;
17817 
17818   if (PrevDecl) {
17819     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17820       // Check for other kinds of shadowing not already handled.
17821       CheckShadow(New, PrevDecl, R);
17822     }
17823 
17824     // When in C++, we may get a TagDecl with the same name; in this case the
17825     // enum constant will 'hide' the tag.
17826     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17827            "Received TagDecl when not in C++!");
17828     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17829       if (isa<EnumConstantDecl>(PrevDecl))
17830         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17831       else
17832         Diag(IdLoc, diag::err_redefinition) << Id;
17833       notePreviousDefinition(PrevDecl, IdLoc);
17834       return nullptr;
17835     }
17836   }
17837 
17838   // Process attributes.
17839   ProcessDeclAttributeList(S, New, Attrs);
17840   AddPragmaAttributes(S, New);
17841 
17842   // Register this decl in the current scope stack.
17843   New->setAccess(TheEnumDecl->getAccess());
17844   PushOnScopeChains(New, S);
17845 
17846   ActOnDocumentableDecl(New);
17847 
17848   return New;
17849 }
17850 
17851 // Returns true when the enum initial expression does not trigger the
17852 // duplicate enum warning.  A few common cases are exempted as follows:
17853 // Element2 = Element1
17854 // Element2 = Element1 + 1
17855 // Element2 = Element1 - 1
17856 // Where Element2 and Element1 are from the same enum.
17857 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17858   Expr *InitExpr = ECD->getInitExpr();
17859   if (!InitExpr)
17860     return true;
17861   InitExpr = InitExpr->IgnoreImpCasts();
17862 
17863   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17864     if (!BO->isAdditiveOp())
17865       return true;
17866     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17867     if (!IL)
17868       return true;
17869     if (IL->getValue() != 1)
17870       return true;
17871 
17872     InitExpr = BO->getLHS();
17873   }
17874 
17875   // This checks if the elements are from the same enum.
17876   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17877   if (!DRE)
17878     return true;
17879 
17880   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17881   if (!EnumConstant)
17882     return true;
17883 
17884   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17885       Enum)
17886     return true;
17887 
17888   return false;
17889 }
17890 
17891 // Emits a warning when an element is implicitly set a value that
17892 // a previous element has already been set to.
17893 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17894                                         EnumDecl *Enum, QualType EnumType) {
17895   // Avoid anonymous enums
17896   if (!Enum->getIdentifier())
17897     return;
17898 
17899   // Only check for small enums.
17900   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17901     return;
17902 
17903   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17904     return;
17905 
17906   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17907   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17908 
17909   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17910 
17911   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17912   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17913 
17914   // Use int64_t as a key to avoid needing special handling for map keys.
17915   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17916     llvm::APSInt Val = D->getInitVal();
17917     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17918   };
17919 
17920   DuplicatesVector DupVector;
17921   ValueToVectorMap EnumMap;
17922 
17923   // Populate the EnumMap with all values represented by enum constants without
17924   // an initializer.
17925   for (auto *Element : Elements) {
17926     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17927 
17928     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17929     // this constant.  Skip this enum since it may be ill-formed.
17930     if (!ECD) {
17931       return;
17932     }
17933 
17934     // Constants with initalizers are handled in the next loop.
17935     if (ECD->getInitExpr())
17936       continue;
17937 
17938     // Duplicate values are handled in the next loop.
17939     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17940   }
17941 
17942   if (EnumMap.size() == 0)
17943     return;
17944 
17945   // Create vectors for any values that has duplicates.
17946   for (auto *Element : Elements) {
17947     // The last loop returned if any constant was null.
17948     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17949     if (!ValidDuplicateEnum(ECD, Enum))
17950       continue;
17951 
17952     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17953     if (Iter == EnumMap.end())
17954       continue;
17955 
17956     DeclOrVector& Entry = Iter->second;
17957     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17958       // Ensure constants are different.
17959       if (D == ECD)
17960         continue;
17961 
17962       // Create new vector and push values onto it.
17963       auto Vec = std::make_unique<ECDVector>();
17964       Vec->push_back(D);
17965       Vec->push_back(ECD);
17966 
17967       // Update entry to point to the duplicates vector.
17968       Entry = Vec.get();
17969 
17970       // Store the vector somewhere we can consult later for quick emission of
17971       // diagnostics.
17972       DupVector.emplace_back(std::move(Vec));
17973       continue;
17974     }
17975 
17976     ECDVector *Vec = Entry.get<ECDVector*>();
17977     // Make sure constants are not added more than once.
17978     if (*Vec->begin() == ECD)
17979       continue;
17980 
17981     Vec->push_back(ECD);
17982   }
17983 
17984   // Emit diagnostics.
17985   for (const auto &Vec : DupVector) {
17986     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17987 
17988     // Emit warning for one enum constant.
17989     auto *FirstECD = Vec->front();
17990     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17991       << FirstECD << FirstECD->getInitVal().toString(10)
17992       << FirstECD->getSourceRange();
17993 
17994     // Emit one note for each of the remaining enum constants with
17995     // the same value.
17996     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17997       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17998         << ECD << ECD->getInitVal().toString(10)
17999         << ECD->getSourceRange();
18000   }
18001 }
18002 
18003 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18004                              bool AllowMask) const {
18005   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18006   assert(ED->isCompleteDefinition() && "expected enum definition");
18007 
18008   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18009   llvm::APInt &FlagBits = R.first->second;
18010 
18011   if (R.second) {
18012     for (auto *E : ED->enumerators()) {
18013       const auto &EVal = E->getInitVal();
18014       // Only single-bit enumerators introduce new flag values.
18015       if (EVal.isPowerOf2())
18016         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18017     }
18018   }
18019 
18020   // A value is in a flag enum if either its bits are a subset of the enum's
18021   // flag bits (the first condition) or we are allowing masks and the same is
18022   // true of its complement (the second condition). When masks are allowed, we
18023   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18024   //
18025   // While it's true that any value could be used as a mask, the assumption is
18026   // that a mask will have all of the insignificant bits set. Anything else is
18027   // likely a logic error.
18028   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18029   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18030 }
18031 
18032 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18033                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18034                          const ParsedAttributesView &Attrs) {
18035   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18036   QualType EnumType = Context.getTypeDeclType(Enum);
18037 
18038   ProcessDeclAttributeList(S, Enum, Attrs);
18039 
18040   if (Enum->isDependentType()) {
18041     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18042       EnumConstantDecl *ECD =
18043         cast_or_null<EnumConstantDecl>(Elements[i]);
18044       if (!ECD) continue;
18045 
18046       ECD->setType(EnumType);
18047     }
18048 
18049     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18050     return;
18051   }
18052 
18053   // TODO: If the result value doesn't fit in an int, it must be a long or long
18054   // long value.  ISO C does not support this, but GCC does as an extension,
18055   // emit a warning.
18056   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18057   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18058   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18059 
18060   // Verify that all the values are okay, compute the size of the values, and
18061   // reverse the list.
18062   unsigned NumNegativeBits = 0;
18063   unsigned NumPositiveBits = 0;
18064 
18065   // Keep track of whether all elements have type int.
18066   bool AllElementsInt = true;
18067 
18068   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18069     EnumConstantDecl *ECD =
18070       cast_or_null<EnumConstantDecl>(Elements[i]);
18071     if (!ECD) continue;  // Already issued a diagnostic.
18072 
18073     const llvm::APSInt &InitVal = ECD->getInitVal();
18074 
18075     // Keep track of the size of positive and negative values.
18076     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18077       NumPositiveBits = std::max(NumPositiveBits,
18078                                  (unsigned)InitVal.getActiveBits());
18079     else
18080       NumNegativeBits = std::max(NumNegativeBits,
18081                                  (unsigned)InitVal.getMinSignedBits());
18082 
18083     // Keep track of whether every enum element has type int (very common).
18084     if (AllElementsInt)
18085       AllElementsInt = ECD->getType() == Context.IntTy;
18086   }
18087 
18088   // Figure out the type that should be used for this enum.
18089   QualType BestType;
18090   unsigned BestWidth;
18091 
18092   // C++0x N3000 [conv.prom]p3:
18093   //   An rvalue of an unscoped enumeration type whose underlying
18094   //   type is not fixed can be converted to an rvalue of the first
18095   //   of the following types that can represent all the values of
18096   //   the enumeration: int, unsigned int, long int, unsigned long
18097   //   int, long long int, or unsigned long long int.
18098   // C99 6.4.4.3p2:
18099   //   An identifier declared as an enumeration constant has type int.
18100   // The C99 rule is modified by a gcc extension
18101   QualType BestPromotionType;
18102 
18103   bool Packed = Enum->hasAttr<PackedAttr>();
18104   // -fshort-enums is the equivalent to specifying the packed attribute on all
18105   // enum definitions.
18106   if (LangOpts.ShortEnums)
18107     Packed = true;
18108 
18109   // If the enum already has a type because it is fixed or dictated by the
18110   // target, promote that type instead of analyzing the enumerators.
18111   if (Enum->isComplete()) {
18112     BestType = Enum->getIntegerType();
18113     if (BestType->isPromotableIntegerType())
18114       BestPromotionType = Context.getPromotedIntegerType(BestType);
18115     else
18116       BestPromotionType = BestType;
18117 
18118     BestWidth = Context.getIntWidth(BestType);
18119   }
18120   else if (NumNegativeBits) {
18121     // If there is a negative value, figure out the smallest integer type (of
18122     // int/long/longlong) that fits.
18123     // If it's packed, check also if it fits a char or a short.
18124     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18125       BestType = Context.SignedCharTy;
18126       BestWidth = CharWidth;
18127     } else if (Packed && NumNegativeBits <= ShortWidth &&
18128                NumPositiveBits < ShortWidth) {
18129       BestType = Context.ShortTy;
18130       BestWidth = ShortWidth;
18131     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18132       BestType = Context.IntTy;
18133       BestWidth = IntWidth;
18134     } else {
18135       BestWidth = Context.getTargetInfo().getLongWidth();
18136 
18137       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18138         BestType = Context.LongTy;
18139       } else {
18140         BestWidth = Context.getTargetInfo().getLongLongWidth();
18141 
18142         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18143           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18144         BestType = Context.LongLongTy;
18145       }
18146     }
18147     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18148   } else {
18149     // If there is no negative value, figure out the smallest type that fits
18150     // all of the enumerator values.
18151     // If it's packed, check also if it fits a char or a short.
18152     if (Packed && NumPositiveBits <= CharWidth) {
18153       BestType = Context.UnsignedCharTy;
18154       BestPromotionType = Context.IntTy;
18155       BestWidth = CharWidth;
18156     } else if (Packed && NumPositiveBits <= ShortWidth) {
18157       BestType = Context.UnsignedShortTy;
18158       BestPromotionType = Context.IntTy;
18159       BestWidth = ShortWidth;
18160     } else if (NumPositiveBits <= IntWidth) {
18161       BestType = Context.UnsignedIntTy;
18162       BestWidth = IntWidth;
18163       BestPromotionType
18164         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18165                            ? Context.UnsignedIntTy : Context.IntTy;
18166     } else if (NumPositiveBits <=
18167                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18168       BestType = Context.UnsignedLongTy;
18169       BestPromotionType
18170         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18171                            ? Context.UnsignedLongTy : Context.LongTy;
18172     } else {
18173       BestWidth = Context.getTargetInfo().getLongLongWidth();
18174       assert(NumPositiveBits <= BestWidth &&
18175              "How could an initializer get larger than ULL?");
18176       BestType = Context.UnsignedLongLongTy;
18177       BestPromotionType
18178         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18179                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18180     }
18181   }
18182 
18183   // Loop over all of the enumerator constants, changing their types to match
18184   // the type of the enum if needed.
18185   for (auto *D : Elements) {
18186     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18187     if (!ECD) continue;  // Already issued a diagnostic.
18188 
18189     // Standard C says the enumerators have int type, but we allow, as an
18190     // extension, the enumerators to be larger than int size.  If each
18191     // enumerator value fits in an int, type it as an int, otherwise type it the
18192     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18193     // that X has type 'int', not 'unsigned'.
18194 
18195     // Determine whether the value fits into an int.
18196     llvm::APSInt InitVal = ECD->getInitVal();
18197 
18198     // If it fits into an integer type, force it.  Otherwise force it to match
18199     // the enum decl type.
18200     QualType NewTy;
18201     unsigned NewWidth;
18202     bool NewSign;
18203     if (!getLangOpts().CPlusPlus &&
18204         !Enum->isFixed() &&
18205         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18206       NewTy = Context.IntTy;
18207       NewWidth = IntWidth;
18208       NewSign = true;
18209     } else if (ECD->getType() == BestType) {
18210       // Already the right type!
18211       if (getLangOpts().CPlusPlus)
18212         // C++ [dcl.enum]p4: Following the closing brace of an
18213         // enum-specifier, each enumerator has the type of its
18214         // enumeration.
18215         ECD->setType(EnumType);
18216       continue;
18217     } else {
18218       NewTy = BestType;
18219       NewWidth = BestWidth;
18220       NewSign = BestType->isSignedIntegerOrEnumerationType();
18221     }
18222 
18223     // Adjust the APSInt value.
18224     InitVal = InitVal.extOrTrunc(NewWidth);
18225     InitVal.setIsSigned(NewSign);
18226     ECD->setInitVal(InitVal);
18227 
18228     // Adjust the Expr initializer and type.
18229     if (ECD->getInitExpr() &&
18230         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18231       ECD->setInitExpr(ImplicitCastExpr::Create(
18232           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18233           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18234     if (getLangOpts().CPlusPlus)
18235       // C++ [dcl.enum]p4: Following the closing brace of an
18236       // enum-specifier, each enumerator has the type of its
18237       // enumeration.
18238       ECD->setType(EnumType);
18239     else
18240       ECD->setType(NewTy);
18241   }
18242 
18243   Enum->completeDefinition(BestType, BestPromotionType,
18244                            NumPositiveBits, NumNegativeBits);
18245 
18246   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18247 
18248   if (Enum->isClosedFlag()) {
18249     for (Decl *D : Elements) {
18250       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18251       if (!ECD) continue;  // Already issued a diagnostic.
18252 
18253       llvm::APSInt InitVal = ECD->getInitVal();
18254       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18255           !IsValueInFlagEnum(Enum, InitVal, true))
18256         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18257           << ECD << Enum;
18258     }
18259   }
18260 
18261   // Now that the enum type is defined, ensure it's not been underaligned.
18262   if (Enum->hasAttrs())
18263     CheckAlignasUnderalignment(Enum);
18264 }
18265 
18266 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18267                                   SourceLocation StartLoc,
18268                                   SourceLocation EndLoc) {
18269   StringLiteral *AsmString = cast<StringLiteral>(expr);
18270 
18271   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18272                                                    AsmString, StartLoc,
18273                                                    EndLoc);
18274   CurContext->addDecl(New);
18275   return New;
18276 }
18277 
18278 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18279                                       IdentifierInfo* AliasName,
18280                                       SourceLocation PragmaLoc,
18281                                       SourceLocation NameLoc,
18282                                       SourceLocation AliasNameLoc) {
18283   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18284                                          LookupOrdinaryName);
18285   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18286                            AttributeCommonInfo::AS_Pragma);
18287   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18288       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18289 
18290   // If a declaration that:
18291   // 1) declares a function or a variable
18292   // 2) has external linkage
18293   // already exists, add a label attribute to it.
18294   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18295     if (isDeclExternC(PrevDecl))
18296       PrevDecl->addAttr(Attr);
18297     else
18298       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18299           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18300   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18301   } else
18302     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18303 }
18304 
18305 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18306                              SourceLocation PragmaLoc,
18307                              SourceLocation NameLoc) {
18308   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18309 
18310   if (PrevDecl) {
18311     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18312   } else {
18313     (void)WeakUndeclaredIdentifiers.insert(
18314       std::pair<IdentifierInfo*,WeakInfo>
18315         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18316   }
18317 }
18318 
18319 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18320                                 IdentifierInfo* AliasName,
18321                                 SourceLocation PragmaLoc,
18322                                 SourceLocation NameLoc,
18323                                 SourceLocation AliasNameLoc) {
18324   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18325                                     LookupOrdinaryName);
18326   WeakInfo W = WeakInfo(Name, NameLoc);
18327 
18328   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18329     if (!PrevDecl->hasAttr<AliasAttr>())
18330       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18331         DeclApplyPragmaWeak(TUScope, ND, W);
18332   } else {
18333     (void)WeakUndeclaredIdentifiers.insert(
18334       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18335   }
18336 }
18337 
18338 Decl *Sema::getObjCDeclContext() const {
18339   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18340 }
18341 
18342 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18343                                                      bool Final) {
18344   // SYCL functions can be template, so we check if they have appropriate
18345   // attribute prior to checking if it is a template.
18346   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18347     return FunctionEmissionStatus::Emitted;
18348 
18349   // Templates are emitted when they're instantiated.
18350   if (FD->isDependentContext())
18351     return FunctionEmissionStatus::TemplateDiscarded;
18352 
18353   // Check whether this function is an externally visible definition.
18354   auto IsEmittedForExternalSymbol = [this, FD]() {
18355     // We have to check the GVA linkage of the function's *definition* -- if we
18356     // only have a declaration, we don't know whether or not the function will
18357     // be emitted, because (say) the definition could include "inline".
18358     FunctionDecl *Def = FD->getDefinition();
18359 
18360     return Def && !isDiscardableGVALinkage(
18361                       getASTContext().GetGVALinkageForFunction(Def));
18362   };
18363 
18364   if (LangOpts.OpenMPIsDevice) {
18365     // In OpenMP device mode we will not emit host only functions, or functions
18366     // we don't need due to their linkage.
18367     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18368         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18369     // DevTy may be changed later by
18370     //  #pragma omp declare target to(*) device_type(*).
18371     // Therefore DevTyhaving no value does not imply host. The emission status
18372     // will be checked again at the end of compilation unit with Final = true.
18373     if (DevTy.hasValue())
18374       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18375         return FunctionEmissionStatus::OMPDiscarded;
18376     // If we have an explicit value for the device type, or we are in a target
18377     // declare context, we need to emit all extern and used symbols.
18378     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18379       if (IsEmittedForExternalSymbol())
18380         return FunctionEmissionStatus::Emitted;
18381     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18382     // we'll omit it.
18383     if (Final)
18384       return FunctionEmissionStatus::OMPDiscarded;
18385   } else if (LangOpts.OpenMP > 45) {
18386     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18387     // function. In 5.0, no_host was introduced which might cause a function to
18388     // be ommitted.
18389     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18390         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18391     if (DevTy.hasValue())
18392       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18393         return FunctionEmissionStatus::OMPDiscarded;
18394   }
18395 
18396   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18397     return FunctionEmissionStatus::Emitted;
18398 
18399   if (LangOpts.CUDA) {
18400     // When compiling for device, host functions are never emitted.  Similarly,
18401     // when compiling for host, device and global functions are never emitted.
18402     // (Technically, we do emit a host-side stub for global functions, but this
18403     // doesn't count for our purposes here.)
18404     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18405     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18406       return FunctionEmissionStatus::CUDADiscarded;
18407     if (!LangOpts.CUDAIsDevice &&
18408         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18409       return FunctionEmissionStatus::CUDADiscarded;
18410 
18411     if (IsEmittedForExternalSymbol())
18412       return FunctionEmissionStatus::Emitted;
18413   }
18414 
18415   // Otherwise, the function is known-emitted if it's in our set of
18416   // known-emitted functions.
18417   return FunctionEmissionStatus::Unknown;
18418 }
18419 
18420 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18421   // Host-side references to a __global__ function refer to the stub, so the
18422   // function itself is never emitted and therefore should not be marked.
18423   // If we have host fn calls kernel fn calls host+device, the HD function
18424   // does not get instantiated on the host. We model this by omitting at the
18425   // call to the kernel from the callgraph. This ensures that, when compiling
18426   // for host, only HD functions actually called from the host get marked as
18427   // known-emitted.
18428   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18429          IdentifyCUDATarget(Callee) == CFT_Global;
18430 }
18431