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   warnOnReservedIdentifier(D);
1520 }
1521 
1522 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1523                          bool AllowInlineNamespace) {
1524   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1525 }
1526 
1527 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1528   DeclContext *TargetDC = DC->getPrimaryContext();
1529   do {
1530     if (DeclContext *ScopeDC = S->getEntity())
1531       if (ScopeDC->getPrimaryContext() == TargetDC)
1532         return S;
1533   } while ((S = S->getParent()));
1534 
1535   return nullptr;
1536 }
1537 
1538 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1539                                             DeclContext*,
1540                                             ASTContext&);
1541 
1542 /// Filters out lookup results that don't fall within the given scope
1543 /// as determined by isDeclInScope.
1544 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1545                                 bool ConsiderLinkage,
1546                                 bool AllowInlineNamespace) {
1547   LookupResult::Filter F = R.makeFilter();
1548   while (F.hasNext()) {
1549     NamedDecl *D = F.next();
1550 
1551     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1552       continue;
1553 
1554     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1555       continue;
1556 
1557     F.erase();
1558   }
1559 
1560   F.done();
1561 }
1562 
1563 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1564 /// have compatible owning modules.
1565 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1566   // FIXME: The Modules TS is not clear about how friend declarations are
1567   // to be treated. It's not meaningful to have different owning modules for
1568   // linkage in redeclarations of the same entity, so for now allow the
1569   // redeclaration and change the owning modules to match.
1570   if (New->getFriendObjectKind() &&
1571       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1572     New->setLocalOwningModule(Old->getOwningModule());
1573     makeMergedDefinitionVisible(New);
1574     return false;
1575   }
1576 
1577   Module *NewM = New->getOwningModule();
1578   Module *OldM = Old->getOwningModule();
1579 
1580   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1581     NewM = NewM->Parent;
1582   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1583     OldM = OldM->Parent;
1584 
1585   if (NewM == OldM)
1586     return false;
1587 
1588   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1589   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1590   if (NewIsModuleInterface || OldIsModuleInterface) {
1591     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1592     //   if a declaration of D [...] appears in the purview of a module, all
1593     //   other such declarations shall appear in the purview of the same module
1594     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1595       << New
1596       << NewIsModuleInterface
1597       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1598       << OldIsModuleInterface
1599       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1600     Diag(Old->getLocation(), diag::note_previous_declaration);
1601     New->setInvalidDecl();
1602     return true;
1603   }
1604 
1605   return false;
1606 }
1607 
1608 static bool isUsingDecl(NamedDecl *D) {
1609   return isa<UsingShadowDecl>(D) ||
1610          isa<UnresolvedUsingTypenameDecl>(D) ||
1611          isa<UnresolvedUsingValueDecl>(D);
1612 }
1613 
1614 /// Removes using shadow declarations from the lookup results.
1615 static void RemoveUsingDecls(LookupResult &R) {
1616   LookupResult::Filter F = R.makeFilter();
1617   while (F.hasNext())
1618     if (isUsingDecl(F.next()))
1619       F.erase();
1620 
1621   F.done();
1622 }
1623 
1624 /// Check for this common pattern:
1625 /// @code
1626 /// class S {
1627 ///   S(const S&); // DO NOT IMPLEMENT
1628 ///   void operator=(const S&); // DO NOT IMPLEMENT
1629 /// };
1630 /// @endcode
1631 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1632   // FIXME: Should check for private access too but access is set after we get
1633   // the decl here.
1634   if (D->doesThisDeclarationHaveABody())
1635     return false;
1636 
1637   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1638     return CD->isCopyConstructor();
1639   return D->isCopyAssignmentOperator();
1640 }
1641 
1642 // We need this to handle
1643 //
1644 // typedef struct {
1645 //   void *foo() { return 0; }
1646 // } A;
1647 //
1648 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1649 // for example. If 'A', foo will have external linkage. If we have '*A',
1650 // foo will have no linkage. Since we can't know until we get to the end
1651 // of the typedef, this function finds out if D might have non-external linkage.
1652 // Callers should verify at the end of the TU if it D has external linkage or
1653 // not.
1654 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1655   const DeclContext *DC = D->getDeclContext();
1656   while (!DC->isTranslationUnit()) {
1657     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1658       if (!RD->hasNameForLinkage())
1659         return true;
1660     }
1661     DC = DC->getParent();
1662   }
1663 
1664   return !D->isExternallyVisible();
1665 }
1666 
1667 // FIXME: This needs to be refactored; some other isInMainFile users want
1668 // these semantics.
1669 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1670   if (S.TUKind != TU_Complete)
1671     return false;
1672   return S.SourceMgr.isInMainFile(Loc);
1673 }
1674 
1675 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1676   assert(D);
1677 
1678   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1679     return false;
1680 
1681   // Ignore all entities declared within templates, and out-of-line definitions
1682   // of members of class templates.
1683   if (D->getDeclContext()->isDependentContext() ||
1684       D->getLexicalDeclContext()->isDependentContext())
1685     return false;
1686 
1687   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1688     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1689       return false;
1690     // A non-out-of-line declaration of a member specialization was implicitly
1691     // instantiated; it's the out-of-line declaration that we're interested in.
1692     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1693         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1694       return false;
1695 
1696     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1697       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1698         return false;
1699     } else {
1700       // 'static inline' functions are defined in headers; don't warn.
1701       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1702         return false;
1703     }
1704 
1705     if (FD->doesThisDeclarationHaveABody() &&
1706         Context.DeclMustBeEmitted(FD))
1707       return false;
1708   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1709     // Constants and utility variables are defined in headers with internal
1710     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1711     // like "inline".)
1712     if (!isMainFileLoc(*this, VD->getLocation()))
1713       return false;
1714 
1715     if (Context.DeclMustBeEmitted(VD))
1716       return false;
1717 
1718     if (VD->isStaticDataMember() &&
1719         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1720       return false;
1721     if (VD->isStaticDataMember() &&
1722         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1723         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1724       return false;
1725 
1726     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1727       return false;
1728   } else {
1729     return false;
1730   }
1731 
1732   // Only warn for unused decls internal to the translation unit.
1733   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1734   // for inline functions defined in the main source file, for instance.
1735   return mightHaveNonExternalLinkage(D);
1736 }
1737 
1738 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1739   if (!D)
1740     return;
1741 
1742   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1743     const FunctionDecl *First = FD->getFirstDecl();
1744     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1745       return; // First should already be in the vector.
1746   }
1747 
1748   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1749     const VarDecl *First = VD->getFirstDecl();
1750     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1751       return; // First should already be in the vector.
1752   }
1753 
1754   if (ShouldWarnIfUnusedFileScopedDecl(D))
1755     UnusedFileScopedDecls.push_back(D);
1756 }
1757 
1758 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1759   if (D->isInvalidDecl())
1760     return false;
1761 
1762   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1763     // For a decomposition declaration, warn if none of the bindings are
1764     // referenced, instead of if the variable itself is referenced (which
1765     // it is, by the bindings' expressions).
1766     for (auto *BD : DD->bindings())
1767       if (BD->isReferenced())
1768         return false;
1769   } else if (!D->getDeclName()) {
1770     return false;
1771   } else if (D->isReferenced() || D->isUsed()) {
1772     return false;
1773   }
1774 
1775   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1776     return false;
1777 
1778   if (isa<LabelDecl>(D))
1779     return true;
1780 
1781   // Except for labels, we only care about unused decls that are local to
1782   // functions.
1783   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1784   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1785     // For dependent types, the diagnostic is deferred.
1786     WithinFunction =
1787         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1788   if (!WithinFunction)
1789     return false;
1790 
1791   if (isa<TypedefNameDecl>(D))
1792     return true;
1793 
1794   // White-list anything that isn't a local variable.
1795   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1796     return false;
1797 
1798   // Types of valid local variables should be complete, so this should succeed.
1799   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800 
1801     // White-list anything with an __attribute__((unused)) type.
1802     const auto *Ty = VD->getType().getTypePtr();
1803 
1804     // Only look at the outermost level of typedef.
1805     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1806       if (TT->getDecl()->hasAttr<UnusedAttr>())
1807         return false;
1808     }
1809 
1810     // If we failed to complete the type for some reason, or if the type is
1811     // dependent, don't diagnose the variable.
1812     if (Ty->isIncompleteType() || Ty->isDependentType())
1813       return false;
1814 
1815     // Look at the element type to ensure that the warning behaviour is
1816     // consistent for both scalars and arrays.
1817     Ty = Ty->getBaseElementTypeUnsafe();
1818 
1819     if (const TagType *TT = Ty->getAs<TagType>()) {
1820       const TagDecl *Tag = TT->getDecl();
1821       if (Tag->hasAttr<UnusedAttr>())
1822         return false;
1823 
1824       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1825         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1826           return false;
1827 
1828         if (const Expr *Init = VD->getInit()) {
1829           if (const ExprWithCleanups *Cleanups =
1830                   dyn_cast<ExprWithCleanups>(Init))
1831             Init = Cleanups->getSubExpr();
1832           const CXXConstructExpr *Construct =
1833             dyn_cast<CXXConstructExpr>(Init);
1834           if (Construct && !Construct->isElidable()) {
1835             CXXConstructorDecl *CD = Construct->getConstructor();
1836             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1837                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1838               return false;
1839           }
1840 
1841           // Suppress the warning if we don't know how this is constructed, and
1842           // it could possibly be non-trivial constructor.
1843           if (Init->isTypeDependent())
1844             for (const CXXConstructorDecl *Ctor : RD->ctors())
1845               if (!Ctor->isTrivial())
1846                 return false;
1847         }
1848       }
1849     }
1850 
1851     // TODO: __attribute__((unused)) templates?
1852   }
1853 
1854   return true;
1855 }
1856 
1857 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1858                                      FixItHint &Hint) {
1859   if (isa<LabelDecl>(D)) {
1860     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1861         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1862         true);
1863     if (AfterColon.isInvalid())
1864       return;
1865     Hint = FixItHint::CreateRemoval(
1866         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1867   }
1868 }
1869 
1870 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1871   if (D->getTypeForDecl()->isDependentType())
1872     return;
1873 
1874   for (auto *TmpD : D->decls()) {
1875     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1876       DiagnoseUnusedDecl(T);
1877     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1878       DiagnoseUnusedNestedTypedefs(R);
1879   }
1880 }
1881 
1882 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1883 /// unless they are marked attr(unused).
1884 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1885   if (!ShouldDiagnoseUnusedDecl(D))
1886     return;
1887 
1888   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1889     // typedefs can be referenced later on, so the diagnostics are emitted
1890     // at end-of-translation-unit.
1891     UnusedLocalTypedefNameCandidates.insert(TD);
1892     return;
1893   }
1894 
1895   FixItHint Hint;
1896   GenerateFixForUnusedDecl(D, Context, Hint);
1897 
1898   unsigned DiagID;
1899   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1900     DiagID = diag::warn_unused_exception_param;
1901   else if (isa<LabelDecl>(D))
1902     DiagID = diag::warn_unused_label;
1903   else
1904     DiagID = diag::warn_unused_variable;
1905 
1906   Diag(D->getLocation(), DiagID) << D << Hint;
1907 }
1908 
1909 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1910   // Verify that we have no forward references left.  If so, there was a goto
1911   // or address of a label taken, but no definition of it.  Label fwd
1912   // definitions are indicated with a null substmt which is also not a resolved
1913   // MS inline assembly label name.
1914   bool Diagnose = false;
1915   if (L->isMSAsmLabel())
1916     Diagnose = !L->isResolvedMSAsmLabel();
1917   else
1918     Diagnose = L->getStmt() == nullptr;
1919   if (Diagnose)
1920     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1921 }
1922 
1923 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1924   S->mergeNRVOIntoParent();
1925 
1926   if (S->decl_empty()) return;
1927   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1928          "Scope shouldn't contain decls!");
1929 
1930   for (auto *TmpD : S->decls()) {
1931     assert(TmpD && "This decl didn't get pushed??");
1932 
1933     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1934     NamedDecl *D = cast<NamedDecl>(TmpD);
1935 
1936     // Diagnose unused variables in this scope.
1937     if (!S->hasUnrecoverableErrorOccurred()) {
1938       DiagnoseUnusedDecl(D);
1939       if (const auto *RD = dyn_cast<RecordDecl>(D))
1940         DiagnoseUnusedNestedTypedefs(RD);
1941     }
1942 
1943     if (!D->getDeclName()) continue;
1944 
1945     // If this was a forward reference to a label, verify it was defined.
1946     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1947       CheckPoppedLabel(LD, *this);
1948 
1949     // Remove this name from our lexical scope, and warn on it if we haven't
1950     // already.
1951     IdResolver.RemoveDecl(D);
1952     auto ShadowI = ShadowingDecls.find(D);
1953     if (ShadowI != ShadowingDecls.end()) {
1954       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1955         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1956             << D << FD << FD->getParent();
1957         Diag(FD->getLocation(), diag::note_previous_declaration);
1958       }
1959       ShadowingDecls.erase(ShadowI);
1960     }
1961   }
1962 }
1963 
1964 /// Look for an Objective-C class in the translation unit.
1965 ///
1966 /// \param Id The name of the Objective-C class we're looking for. If
1967 /// typo-correction fixes this name, the Id will be updated
1968 /// to the fixed name.
1969 ///
1970 /// \param IdLoc The location of the name in the translation unit.
1971 ///
1972 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1973 /// if there is no class with the given name.
1974 ///
1975 /// \returns The declaration of the named Objective-C class, or NULL if the
1976 /// class could not be found.
1977 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1978                                               SourceLocation IdLoc,
1979                                               bool DoTypoCorrection) {
1980   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1981   // creation from this context.
1982   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1983 
1984   if (!IDecl && DoTypoCorrection) {
1985     // Perform typo correction at the given location, but only if we
1986     // find an Objective-C class name.
1987     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1988     if (TypoCorrection C =
1989             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1990                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1991       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1992       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1993       Id = IDecl->getIdentifier();
1994     }
1995   }
1996   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1997   // This routine must always return a class definition, if any.
1998   if (Def && Def->getDefinition())
1999       Def = Def->getDefinition();
2000   return Def;
2001 }
2002 
2003 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2004 /// from S, where a non-field would be declared. This routine copes
2005 /// with the difference between C and C++ scoping rules in structs and
2006 /// unions. For example, the following code is well-formed in C but
2007 /// ill-formed in C++:
2008 /// @code
2009 /// struct S6 {
2010 ///   enum { BAR } e;
2011 /// };
2012 ///
2013 /// void test_S6() {
2014 ///   struct S6 a;
2015 ///   a.e = BAR;
2016 /// }
2017 /// @endcode
2018 /// For the declaration of BAR, this routine will return a different
2019 /// scope. The scope S will be the scope of the unnamed enumeration
2020 /// within S6. In C++, this routine will return the scope associated
2021 /// with S6, because the enumeration's scope is a transparent
2022 /// context but structures can contain non-field names. In C, this
2023 /// routine will return the translation unit scope, since the
2024 /// enumeration's scope is a transparent context and structures cannot
2025 /// contain non-field names.
2026 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2027   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2028          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2029          (S->isClassScope() && !getLangOpts().CPlusPlus))
2030     S = S->getParent();
2031   return S;
2032 }
2033 
2034 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2035                                ASTContext::GetBuiltinTypeError Error) {
2036   switch (Error) {
2037   case ASTContext::GE_None:
2038     return "";
2039   case ASTContext::GE_Missing_type:
2040     return BuiltinInfo.getHeaderName(ID);
2041   case ASTContext::GE_Missing_stdio:
2042     return "stdio.h";
2043   case ASTContext::GE_Missing_setjmp:
2044     return "setjmp.h";
2045   case ASTContext::GE_Missing_ucontext:
2046     return "ucontext.h";
2047   }
2048   llvm_unreachable("unhandled error kind");
2049 }
2050 
2051 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2052                                   unsigned ID, SourceLocation Loc) {
2053   DeclContext *Parent = Context.getTranslationUnitDecl();
2054 
2055   if (getLangOpts().CPlusPlus) {
2056     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2057         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2058     CLinkageDecl->setImplicit();
2059     Parent->addDecl(CLinkageDecl);
2060     Parent = CLinkageDecl;
2061   }
2062 
2063   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2064                                            /*TInfo=*/nullptr, SC_Extern, false,
2065                                            Type->isFunctionProtoType());
2066   New->setImplicit();
2067   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2068 
2069   // Create Decl objects for each parameter, adding them to the
2070   // FunctionDecl.
2071   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2072     SmallVector<ParmVarDecl *, 16> Params;
2073     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2074       ParmVarDecl *parm = ParmVarDecl::Create(
2075           Context, New, SourceLocation(), SourceLocation(), nullptr,
2076           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2077       parm->setScopeInfo(0, i);
2078       Params.push_back(parm);
2079     }
2080     New->setParams(Params);
2081   }
2082 
2083   AddKnownFunctionAttributes(New);
2084   return New;
2085 }
2086 
2087 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2088 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2089 /// if we're creating this built-in in anticipation of redeclaring the
2090 /// built-in.
2091 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2092                                      Scope *S, bool ForRedeclaration,
2093                                      SourceLocation Loc) {
2094   LookupNecessaryTypesForBuiltin(S, ID);
2095 
2096   ASTContext::GetBuiltinTypeError Error;
2097   QualType R = Context.GetBuiltinType(ID, Error);
2098   if (Error) {
2099     if (!ForRedeclaration)
2100       return nullptr;
2101 
2102     // If we have a builtin without an associated type we should not emit a
2103     // warning when we were not able to find a type for it.
2104     if (Error == ASTContext::GE_Missing_type ||
2105         Context.BuiltinInfo.allowTypeMismatch(ID))
2106       return nullptr;
2107 
2108     // If we could not find a type for setjmp it is because the jmp_buf type was
2109     // not defined prior to the setjmp declaration.
2110     if (Error == ASTContext::GE_Missing_setjmp) {
2111       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2112           << Context.BuiltinInfo.getName(ID);
2113       return nullptr;
2114     }
2115 
2116     // Generally, we emit a warning that the declaration requires the
2117     // appropriate header.
2118     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2119         << getHeaderName(Context.BuiltinInfo, ID, Error)
2120         << Context.BuiltinInfo.getName(ID);
2121     return nullptr;
2122   }
2123 
2124   if (!ForRedeclaration &&
2125       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2126        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2127     Diag(Loc, diag::ext_implicit_lib_function_decl)
2128         << Context.BuiltinInfo.getName(ID) << R;
2129     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2130       Diag(Loc, diag::note_include_header_or_declare)
2131           << Header << Context.BuiltinInfo.getName(ID);
2132   }
2133 
2134   if (R.isNull())
2135     return nullptr;
2136 
2137   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2138   RegisterLocallyScopedExternCDecl(New, S);
2139 
2140   // TUScope is the translation-unit scope to insert this function into.
2141   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2142   // relate Scopes to DeclContexts, and probably eliminate CurContext
2143   // entirely, but we're not there yet.
2144   DeclContext *SavedContext = CurContext;
2145   CurContext = New->getDeclContext();
2146   PushOnScopeChains(New, TUScope);
2147   CurContext = SavedContext;
2148   return New;
2149 }
2150 
2151 /// Typedef declarations don't have linkage, but they still denote the same
2152 /// entity if their types are the same.
2153 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2154 /// isSameEntity.
2155 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2156                                                      TypedefNameDecl *Decl,
2157                                                      LookupResult &Previous) {
2158   // This is only interesting when modules are enabled.
2159   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2160     return;
2161 
2162   // Empty sets are uninteresting.
2163   if (Previous.empty())
2164     return;
2165 
2166   LookupResult::Filter Filter = Previous.makeFilter();
2167   while (Filter.hasNext()) {
2168     NamedDecl *Old = Filter.next();
2169 
2170     // Non-hidden declarations are never ignored.
2171     if (S.isVisible(Old))
2172       continue;
2173 
2174     // Declarations of the same entity are not ignored, even if they have
2175     // different linkages.
2176     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2177       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2178                                 Decl->getUnderlyingType()))
2179         continue;
2180 
2181       // If both declarations give a tag declaration a typedef name for linkage
2182       // purposes, then they declare the same entity.
2183       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2184           Decl->getAnonDeclWithTypedefName())
2185         continue;
2186     }
2187 
2188     Filter.erase();
2189   }
2190 
2191   Filter.done();
2192 }
2193 
2194 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2195   QualType OldType;
2196   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2197     OldType = OldTypedef->getUnderlyingType();
2198   else
2199     OldType = Context.getTypeDeclType(Old);
2200   QualType NewType = New->getUnderlyingType();
2201 
2202   if (NewType->isVariablyModifiedType()) {
2203     // Must not redefine a typedef with a variably-modified type.
2204     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2205     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2206       << Kind << NewType;
2207     if (Old->getLocation().isValid())
2208       notePreviousDefinition(Old, New->getLocation());
2209     New->setInvalidDecl();
2210     return true;
2211   }
2212 
2213   if (OldType != NewType &&
2214       !OldType->isDependentType() &&
2215       !NewType->isDependentType() &&
2216       !Context.hasSameType(OldType, NewType)) {
2217     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2218     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2219       << Kind << NewType << OldType;
2220     if (Old->getLocation().isValid())
2221       notePreviousDefinition(Old, New->getLocation());
2222     New->setInvalidDecl();
2223     return true;
2224   }
2225   return false;
2226 }
2227 
2228 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2229 /// same name and scope as a previous declaration 'Old'.  Figure out
2230 /// how to resolve this situation, merging decls or emitting
2231 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2232 ///
2233 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2234                                 LookupResult &OldDecls) {
2235   // If the new decl is known invalid already, don't bother doing any
2236   // merging checks.
2237   if (New->isInvalidDecl()) return;
2238 
2239   // Allow multiple definitions for ObjC built-in typedefs.
2240   // FIXME: Verify the underlying types are equivalent!
2241   if (getLangOpts().ObjC) {
2242     const IdentifierInfo *TypeID = New->getIdentifier();
2243     switch (TypeID->getLength()) {
2244     default: break;
2245     case 2:
2246       {
2247         if (!TypeID->isStr("id"))
2248           break;
2249         QualType T = New->getUnderlyingType();
2250         if (!T->isPointerType())
2251           break;
2252         if (!T->isVoidPointerType()) {
2253           QualType PT = T->castAs<PointerType>()->getPointeeType();
2254           if (!PT->isStructureType())
2255             break;
2256         }
2257         Context.setObjCIdRedefinitionType(T);
2258         // Install the built-in type for 'id', ignoring the current definition.
2259         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2260         return;
2261       }
2262     case 5:
2263       if (!TypeID->isStr("Class"))
2264         break;
2265       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2266       // Install the built-in type for 'Class', ignoring the current definition.
2267       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2268       return;
2269     case 3:
2270       if (!TypeID->isStr("SEL"))
2271         break;
2272       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2273       // Install the built-in type for 'SEL', ignoring the current definition.
2274       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2275       return;
2276     }
2277     // Fall through - the typedef name was not a builtin type.
2278   }
2279 
2280   // Verify the old decl was also a type.
2281   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2282   if (!Old) {
2283     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2284       << New->getDeclName();
2285 
2286     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2287     if (OldD->getLocation().isValid())
2288       notePreviousDefinition(OldD, New->getLocation());
2289 
2290     return New->setInvalidDecl();
2291   }
2292 
2293   // If the old declaration is invalid, just give up here.
2294   if (Old->isInvalidDecl())
2295     return New->setInvalidDecl();
2296 
2297   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2298     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2299     auto *NewTag = New->getAnonDeclWithTypedefName();
2300     NamedDecl *Hidden = nullptr;
2301     if (OldTag && NewTag &&
2302         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2303         !hasVisibleDefinition(OldTag, &Hidden)) {
2304       // There is a definition of this tag, but it is not visible. Use it
2305       // instead of our tag.
2306       New->setTypeForDecl(OldTD->getTypeForDecl());
2307       if (OldTD->isModed())
2308         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2309                                     OldTD->getUnderlyingType());
2310       else
2311         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2312 
2313       // Make the old tag definition visible.
2314       makeMergedDefinitionVisible(Hidden);
2315 
2316       // If this was an unscoped enumeration, yank all of its enumerators
2317       // out of the scope.
2318       if (isa<EnumDecl>(NewTag)) {
2319         Scope *EnumScope = getNonFieldDeclScope(S);
2320         for (auto *D : NewTag->decls()) {
2321           auto *ED = cast<EnumConstantDecl>(D);
2322           assert(EnumScope->isDeclScope(ED));
2323           EnumScope->RemoveDecl(ED);
2324           IdResolver.RemoveDecl(ED);
2325           ED->getLexicalDeclContext()->removeDecl(ED);
2326         }
2327       }
2328     }
2329   }
2330 
2331   // If the typedef types are not identical, reject them in all languages and
2332   // with any extensions enabled.
2333   if (isIncompatibleTypedef(Old, New))
2334     return;
2335 
2336   // The types match.  Link up the redeclaration chain and merge attributes if
2337   // the old declaration was a typedef.
2338   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2339     New->setPreviousDecl(Typedef);
2340     mergeDeclAttributes(New, Old);
2341   }
2342 
2343   if (getLangOpts().MicrosoftExt)
2344     return;
2345 
2346   if (getLangOpts().CPlusPlus) {
2347     // C++ [dcl.typedef]p2:
2348     //   In a given non-class scope, a typedef specifier can be used to
2349     //   redefine the name of any type declared in that scope to refer
2350     //   to the type to which it already refers.
2351     if (!isa<CXXRecordDecl>(CurContext))
2352       return;
2353 
2354     // C++0x [dcl.typedef]p4:
2355     //   In a given class scope, a typedef specifier can be used to redefine
2356     //   any class-name declared in that scope that is not also a typedef-name
2357     //   to refer to the type to which it already refers.
2358     //
2359     // This wording came in via DR424, which was a correction to the
2360     // wording in DR56, which accidentally banned code like:
2361     //
2362     //   struct S {
2363     //     typedef struct A { } A;
2364     //   };
2365     //
2366     // in the C++03 standard. We implement the C++0x semantics, which
2367     // allow the above but disallow
2368     //
2369     //   struct S {
2370     //     typedef int I;
2371     //     typedef int I;
2372     //   };
2373     //
2374     // since that was the intent of DR56.
2375     if (!isa<TypedefNameDecl>(Old))
2376       return;
2377 
2378     Diag(New->getLocation(), diag::err_redefinition)
2379       << New->getDeclName();
2380     notePreviousDefinition(Old, New->getLocation());
2381     return New->setInvalidDecl();
2382   }
2383 
2384   // Modules always permit redefinition of typedefs, as does C11.
2385   if (getLangOpts().Modules || getLangOpts().C11)
2386     return;
2387 
2388   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2389   // is normally mapped to an error, but can be controlled with
2390   // -Wtypedef-redefinition.  If either the original or the redefinition is
2391   // in a system header, don't emit this for compatibility with GCC.
2392   if (getDiagnostics().getSuppressSystemWarnings() &&
2393       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2394       (Old->isImplicit() ||
2395        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2396        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2397     return;
2398 
2399   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2400     << New->getDeclName();
2401   notePreviousDefinition(Old, New->getLocation());
2402 }
2403 
2404 /// DeclhasAttr - returns true if decl Declaration already has the target
2405 /// attribute.
2406 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2407   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2408   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2409   for (const auto *i : D->attrs())
2410     if (i->getKind() == A->getKind()) {
2411       if (Ann) {
2412         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2413           return true;
2414         continue;
2415       }
2416       // FIXME: Don't hardcode this check
2417       if (OA && isa<OwnershipAttr>(i))
2418         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2419       return true;
2420     }
2421 
2422   return false;
2423 }
2424 
2425 static bool isAttributeTargetADefinition(Decl *D) {
2426   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2427     return VD->isThisDeclarationADefinition();
2428   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2429     return TD->isCompleteDefinition() || TD->isBeingDefined();
2430   return true;
2431 }
2432 
2433 /// Merge alignment attributes from \p Old to \p New, taking into account the
2434 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2435 ///
2436 /// \return \c true if any attributes were added to \p New.
2437 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2438   // Look for alignas attributes on Old, and pick out whichever attribute
2439   // specifies the strictest alignment requirement.
2440   AlignedAttr *OldAlignasAttr = nullptr;
2441   AlignedAttr *OldStrictestAlignAttr = nullptr;
2442   unsigned OldAlign = 0;
2443   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2444     // FIXME: We have no way of representing inherited dependent alignments
2445     // in a case like:
2446     //   template<int A, int B> struct alignas(A) X;
2447     //   template<int A, int B> struct alignas(B) X {};
2448     // For now, we just ignore any alignas attributes which are not on the
2449     // definition in such a case.
2450     if (I->isAlignmentDependent())
2451       return false;
2452 
2453     if (I->isAlignas())
2454       OldAlignasAttr = I;
2455 
2456     unsigned Align = I->getAlignment(S.Context);
2457     if (Align > OldAlign) {
2458       OldAlign = Align;
2459       OldStrictestAlignAttr = I;
2460     }
2461   }
2462 
2463   // Look for alignas attributes on New.
2464   AlignedAttr *NewAlignasAttr = nullptr;
2465   unsigned NewAlign = 0;
2466   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2467     if (I->isAlignmentDependent())
2468       return false;
2469 
2470     if (I->isAlignas())
2471       NewAlignasAttr = I;
2472 
2473     unsigned Align = I->getAlignment(S.Context);
2474     if (Align > NewAlign)
2475       NewAlign = Align;
2476   }
2477 
2478   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2479     // Both declarations have 'alignas' attributes. We require them to match.
2480     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2481     // fall short. (If two declarations both have alignas, they must both match
2482     // every definition, and so must match each other if there is a definition.)
2483 
2484     // If either declaration only contains 'alignas(0)' specifiers, then it
2485     // specifies the natural alignment for the type.
2486     if (OldAlign == 0 || NewAlign == 0) {
2487       QualType Ty;
2488       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2489         Ty = VD->getType();
2490       else
2491         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2492 
2493       if (OldAlign == 0)
2494         OldAlign = S.Context.getTypeAlign(Ty);
2495       if (NewAlign == 0)
2496         NewAlign = S.Context.getTypeAlign(Ty);
2497     }
2498 
2499     if (OldAlign != NewAlign) {
2500       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2501         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2502         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2503       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2504     }
2505   }
2506 
2507   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2508     // C++11 [dcl.align]p6:
2509     //   if any declaration of an entity has an alignment-specifier,
2510     //   every defining declaration of that entity shall specify an
2511     //   equivalent alignment.
2512     // C11 6.7.5/7:
2513     //   If the definition of an object does not have an alignment
2514     //   specifier, any other declaration of that object shall also
2515     //   have no alignment specifier.
2516     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2517       << OldAlignasAttr;
2518     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2519       << OldAlignasAttr;
2520   }
2521 
2522   bool AnyAdded = false;
2523 
2524   // Ensure we have an attribute representing the strictest alignment.
2525   if (OldAlign > NewAlign) {
2526     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2527     Clone->setInherited(true);
2528     New->addAttr(Clone);
2529     AnyAdded = true;
2530   }
2531 
2532   // Ensure we have an alignas attribute if the old declaration had one.
2533   if (OldAlignasAttr && !NewAlignasAttr &&
2534       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2535     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2536     Clone->setInherited(true);
2537     New->addAttr(Clone);
2538     AnyAdded = true;
2539   }
2540 
2541   return AnyAdded;
2542 }
2543 
2544 #define WANT_DECL_MERGE_LOGIC
2545 #include "clang/Sema/AttrParsedAttrImpl.inc"
2546 #undef WANT_DECL_MERGE_LOGIC
2547 
2548 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2549                                const InheritableAttr *Attr,
2550                                Sema::AvailabilityMergeKind AMK) {
2551   // Diagnose any mutual exclusions between the attribute that we want to add
2552   // and attributes that already exist on the declaration.
2553   if (!DiagnoseMutualExclusions(S, D, Attr))
2554     return false;
2555 
2556   // This function copies an attribute Attr from a previous declaration to the
2557   // new declaration D if the new declaration doesn't itself have that attribute
2558   // yet or if that attribute allows duplicates.
2559   // If you're adding a new attribute that requires logic different from
2560   // "use explicit attribute on decl if present, else use attribute from
2561   // previous decl", for example if the attribute needs to be consistent
2562   // between redeclarations, you need to call a custom merge function here.
2563   InheritableAttr *NewAttr = nullptr;
2564   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2565     NewAttr = S.mergeAvailabilityAttr(
2566         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2567         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2568         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2569         AA->getPriority());
2570   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2571     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2572   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2573     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2574   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2575     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2576   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2577     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2578   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2579     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2580                                 FA->getFirstArg());
2581   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2582     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2583   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2584     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2585   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2586     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2587                                        IA->getInheritanceModel());
2588   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2589     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2590                                       &S.Context.Idents.get(AA->getSpelling()));
2591   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2592            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2593             isa<CUDAGlobalAttr>(Attr))) {
2594     // CUDA target attributes are part of function signature for
2595     // overloading purposes and must not be merged.
2596     return false;
2597   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2598     NewAttr = S.mergeMinSizeAttr(D, *MA);
2599   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2600     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2601   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2602     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2603   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2604     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2605   else if (isa<AlignedAttr>(Attr))
2606     // AlignedAttrs are handled separately, because we need to handle all
2607     // such attributes on a declaration at the same time.
2608     NewAttr = nullptr;
2609   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2610            (AMK == Sema::AMK_Override ||
2611             AMK == Sema::AMK_ProtocolImplementation))
2612     NewAttr = nullptr;
2613   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2614     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2615   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2616     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2617   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2618     NewAttr = S.mergeImportNameAttr(D, *INA);
2619   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2620     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2621   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2622     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2623   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2624     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2625 
2626   if (NewAttr) {
2627     NewAttr->setInherited(true);
2628     D->addAttr(NewAttr);
2629     if (isa<MSInheritanceAttr>(NewAttr))
2630       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2631     return true;
2632   }
2633 
2634   return false;
2635 }
2636 
2637 static const NamedDecl *getDefinition(const Decl *D) {
2638   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2639     return TD->getDefinition();
2640   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2641     const VarDecl *Def = VD->getDefinition();
2642     if (Def)
2643       return Def;
2644     return VD->getActingDefinition();
2645   }
2646   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2647     const FunctionDecl *Def = nullptr;
2648     if (FD->isDefined(Def, true))
2649       return Def;
2650   }
2651   return nullptr;
2652 }
2653 
2654 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2655   for (const auto *Attribute : D->attrs())
2656     if (Attribute->getKind() == Kind)
2657       return true;
2658   return false;
2659 }
2660 
2661 /// checkNewAttributesAfterDef - If we already have a definition, check that
2662 /// there are no new attributes in this declaration.
2663 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2664   if (!New->hasAttrs())
2665     return;
2666 
2667   const NamedDecl *Def = getDefinition(Old);
2668   if (!Def || Def == New)
2669     return;
2670 
2671   AttrVec &NewAttributes = New->getAttrs();
2672   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2673     const Attr *NewAttribute = NewAttributes[I];
2674 
2675     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2676       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2677         Sema::SkipBodyInfo SkipBody;
2678         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2679 
2680         // If we're skipping this definition, drop the "alias" attribute.
2681         if (SkipBody.ShouldSkip) {
2682           NewAttributes.erase(NewAttributes.begin() + I);
2683           --E;
2684           continue;
2685         }
2686       } else {
2687         VarDecl *VD = cast<VarDecl>(New);
2688         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2689                                 VarDecl::TentativeDefinition
2690                             ? diag::err_alias_after_tentative
2691                             : diag::err_redefinition;
2692         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2693         if (Diag == diag::err_redefinition)
2694           S.notePreviousDefinition(Def, VD->getLocation());
2695         else
2696           S.Diag(Def->getLocation(), diag::note_previous_definition);
2697         VD->setInvalidDecl();
2698       }
2699       ++I;
2700       continue;
2701     }
2702 
2703     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2704       // Tentative definitions are only interesting for the alias check above.
2705       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2706         ++I;
2707         continue;
2708       }
2709     }
2710 
2711     if (hasAttribute(Def, NewAttribute->getKind())) {
2712       ++I;
2713       continue; // regular attr merging will take care of validating this.
2714     }
2715 
2716     if (isa<C11NoReturnAttr>(NewAttribute)) {
2717       // C's _Noreturn is allowed to be added to a function after it is defined.
2718       ++I;
2719       continue;
2720     } else if (isa<UuidAttr>(NewAttribute)) {
2721       // msvc will allow a subsequent definition to add an uuid to a class
2722       ++I;
2723       continue;
2724     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2725       if (AA->isAlignas()) {
2726         // C++11 [dcl.align]p6:
2727         //   if any declaration of an entity has an alignment-specifier,
2728         //   every defining declaration of that entity shall specify an
2729         //   equivalent alignment.
2730         // C11 6.7.5/7:
2731         //   If the definition of an object does not have an alignment
2732         //   specifier, any other declaration of that object shall also
2733         //   have no alignment specifier.
2734         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2735           << AA;
2736         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2737           << AA;
2738         NewAttributes.erase(NewAttributes.begin() + I);
2739         --E;
2740         continue;
2741       }
2742     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2743       // If there is a C definition followed by a redeclaration with this
2744       // attribute then there are two different definitions. In C++, prefer the
2745       // standard diagnostics.
2746       if (!S.getLangOpts().CPlusPlus) {
2747         S.Diag(NewAttribute->getLocation(),
2748                diag::err_loader_uninitialized_redeclaration);
2749         S.Diag(Def->getLocation(), diag::note_previous_definition);
2750         NewAttributes.erase(NewAttributes.begin() + I);
2751         --E;
2752         continue;
2753       }
2754     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2755                cast<VarDecl>(New)->isInline() &&
2756                !cast<VarDecl>(New)->isInlineSpecified()) {
2757       // Don't warn about applying selectany to implicitly inline variables.
2758       // Older compilers and language modes would require the use of selectany
2759       // to make such variables inline, and it would have no effect if we
2760       // honored it.
2761       ++I;
2762       continue;
2763     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2764       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2765       // declarations after defintions.
2766       ++I;
2767       continue;
2768     }
2769 
2770     S.Diag(NewAttribute->getLocation(),
2771            diag::warn_attribute_precede_definition);
2772     S.Diag(Def->getLocation(), diag::note_previous_definition);
2773     NewAttributes.erase(NewAttributes.begin() + I);
2774     --E;
2775   }
2776 }
2777 
2778 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2779                                      const ConstInitAttr *CIAttr,
2780                                      bool AttrBeforeInit) {
2781   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2782 
2783   // Figure out a good way to write this specifier on the old declaration.
2784   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2785   // enough of the attribute list spelling information to extract that without
2786   // heroics.
2787   std::string SuitableSpelling;
2788   if (S.getLangOpts().CPlusPlus20)
2789     SuitableSpelling = std::string(
2790         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2791   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2792     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2793         InsertLoc, {tok::l_square, tok::l_square,
2794                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2795                     S.PP.getIdentifierInfo("require_constant_initialization"),
2796                     tok::r_square, tok::r_square}));
2797   if (SuitableSpelling.empty())
2798     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2799         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2800                     S.PP.getIdentifierInfo("require_constant_initialization"),
2801                     tok::r_paren, tok::r_paren}));
2802   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2803     SuitableSpelling = "constinit";
2804   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2805     SuitableSpelling = "[[clang::require_constant_initialization]]";
2806   if (SuitableSpelling.empty())
2807     SuitableSpelling = "__attribute__((require_constant_initialization))";
2808   SuitableSpelling += " ";
2809 
2810   if (AttrBeforeInit) {
2811     // extern constinit int a;
2812     // int a = 0; // error (missing 'constinit'), accepted as extension
2813     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2814     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2815         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2816     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2817   } else {
2818     // int a = 0;
2819     // constinit extern int a; // error (missing 'constinit')
2820     S.Diag(CIAttr->getLocation(),
2821            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2822                                  : diag::warn_require_const_init_added_too_late)
2823         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2824     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2825         << CIAttr->isConstinit()
2826         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2827   }
2828 }
2829 
2830 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2831 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2832                                AvailabilityMergeKind AMK) {
2833   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2834     UsedAttr *NewAttr = OldAttr->clone(Context);
2835     NewAttr->setInherited(true);
2836     New->addAttr(NewAttr);
2837   }
2838   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2839     RetainAttr *NewAttr = OldAttr->clone(Context);
2840     NewAttr->setInherited(true);
2841     New->addAttr(NewAttr);
2842   }
2843 
2844   if (!Old->hasAttrs() && !New->hasAttrs())
2845     return;
2846 
2847   // [dcl.constinit]p1:
2848   //   If the [constinit] specifier is applied to any declaration of a
2849   //   variable, it shall be applied to the initializing declaration.
2850   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2851   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2852   if (bool(OldConstInit) != bool(NewConstInit)) {
2853     const auto *OldVD = cast<VarDecl>(Old);
2854     auto *NewVD = cast<VarDecl>(New);
2855 
2856     // Find the initializing declaration. Note that we might not have linked
2857     // the new declaration into the redeclaration chain yet.
2858     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2859     if (!InitDecl &&
2860         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2861       InitDecl = NewVD;
2862 
2863     if (InitDecl == NewVD) {
2864       // This is the initializing declaration. If it would inherit 'constinit',
2865       // that's ill-formed. (Note that we do not apply this to the attribute
2866       // form).
2867       if (OldConstInit && OldConstInit->isConstinit())
2868         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2869                                  /*AttrBeforeInit=*/true);
2870     } else if (NewConstInit) {
2871       // This is the first time we've been told that this declaration should
2872       // have a constant initializer. If we already saw the initializing
2873       // declaration, this is too late.
2874       if (InitDecl && InitDecl != NewVD) {
2875         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2876                                  /*AttrBeforeInit=*/false);
2877         NewVD->dropAttr<ConstInitAttr>();
2878       }
2879     }
2880   }
2881 
2882   // Attributes declared post-definition are currently ignored.
2883   checkNewAttributesAfterDef(*this, New, Old);
2884 
2885   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2886     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2887       if (!OldA->isEquivalent(NewA)) {
2888         // This redeclaration changes __asm__ label.
2889         Diag(New->getLocation(), diag::err_different_asm_label);
2890         Diag(OldA->getLocation(), diag::note_previous_declaration);
2891       }
2892     } else if (Old->isUsed()) {
2893       // This redeclaration adds an __asm__ label to a declaration that has
2894       // already been ODR-used.
2895       Diag(New->getLocation(), diag::err_late_asm_label_name)
2896         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2897     }
2898   }
2899 
2900   // Re-declaration cannot add abi_tag's.
2901   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2902     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2903       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2904         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2905                       NewTag) == OldAbiTagAttr->tags_end()) {
2906           Diag(NewAbiTagAttr->getLocation(),
2907                diag::err_new_abi_tag_on_redeclaration)
2908               << NewTag;
2909           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2910         }
2911       }
2912     } else {
2913       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2914       Diag(Old->getLocation(), diag::note_previous_declaration);
2915     }
2916   }
2917 
2918   // This redeclaration adds a section attribute.
2919   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2920     if (auto *VD = dyn_cast<VarDecl>(New)) {
2921       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2922         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2923         Diag(Old->getLocation(), diag::note_previous_declaration);
2924       }
2925     }
2926   }
2927 
2928   // Redeclaration adds code-seg attribute.
2929   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2930   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2931       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2932     Diag(New->getLocation(), diag::warn_mismatched_section)
2933          << 0 /*codeseg*/;
2934     Diag(Old->getLocation(), diag::note_previous_declaration);
2935   }
2936 
2937   if (!Old->hasAttrs())
2938     return;
2939 
2940   bool foundAny = New->hasAttrs();
2941 
2942   // Ensure that any moving of objects within the allocated map is done before
2943   // we process them.
2944   if (!foundAny) New->setAttrs(AttrVec());
2945 
2946   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2947     // Ignore deprecated/unavailable/availability attributes if requested.
2948     AvailabilityMergeKind LocalAMK = AMK_None;
2949     if (isa<DeprecatedAttr>(I) ||
2950         isa<UnavailableAttr>(I) ||
2951         isa<AvailabilityAttr>(I)) {
2952       switch (AMK) {
2953       case AMK_None:
2954         continue;
2955 
2956       case AMK_Redeclaration:
2957       case AMK_Override:
2958       case AMK_ProtocolImplementation:
2959         LocalAMK = AMK;
2960         break;
2961       }
2962     }
2963 
2964     // Already handled.
2965     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
2966       continue;
2967 
2968     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2969       foundAny = true;
2970   }
2971 
2972   if (mergeAlignedAttrs(*this, New, Old))
2973     foundAny = true;
2974 
2975   if (!foundAny) New->dropAttrs();
2976 }
2977 
2978 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2979 /// to the new one.
2980 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2981                                      const ParmVarDecl *oldDecl,
2982                                      Sema &S) {
2983   // C++11 [dcl.attr.depend]p2:
2984   //   The first declaration of a function shall specify the
2985   //   carries_dependency attribute for its declarator-id if any declaration
2986   //   of the function specifies the carries_dependency attribute.
2987   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2988   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2989     S.Diag(CDA->getLocation(),
2990            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2991     // Find the first declaration of the parameter.
2992     // FIXME: Should we build redeclaration chains for function parameters?
2993     const FunctionDecl *FirstFD =
2994       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2995     const ParmVarDecl *FirstVD =
2996       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2997     S.Diag(FirstVD->getLocation(),
2998            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2999   }
3000 
3001   if (!oldDecl->hasAttrs())
3002     return;
3003 
3004   bool foundAny = newDecl->hasAttrs();
3005 
3006   // Ensure that any moving of objects within the allocated map is
3007   // done before we process them.
3008   if (!foundAny) newDecl->setAttrs(AttrVec());
3009 
3010   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3011     if (!DeclHasAttr(newDecl, I)) {
3012       InheritableAttr *newAttr =
3013         cast<InheritableParamAttr>(I->clone(S.Context));
3014       newAttr->setInherited(true);
3015       newDecl->addAttr(newAttr);
3016       foundAny = true;
3017     }
3018   }
3019 
3020   if (!foundAny) newDecl->dropAttrs();
3021 }
3022 
3023 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3024                                 const ParmVarDecl *OldParam,
3025                                 Sema &S) {
3026   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3027     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3028       if (*Oldnullability != *Newnullability) {
3029         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3030           << DiagNullabilityKind(
3031                *Newnullability,
3032                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3033                 != 0))
3034           << DiagNullabilityKind(
3035                *Oldnullability,
3036                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3037                 != 0));
3038         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3039       }
3040     } else {
3041       QualType NewT = NewParam->getType();
3042       NewT = S.Context.getAttributedType(
3043                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3044                          NewT, NewT);
3045       NewParam->setType(NewT);
3046     }
3047   }
3048 }
3049 
3050 namespace {
3051 
3052 /// Used in MergeFunctionDecl to keep track of function parameters in
3053 /// C.
3054 struct GNUCompatibleParamWarning {
3055   ParmVarDecl *OldParm;
3056   ParmVarDecl *NewParm;
3057   QualType PromotedType;
3058 };
3059 
3060 } // end anonymous namespace
3061 
3062 // Determine whether the previous declaration was a definition, implicit
3063 // declaration, or a declaration.
3064 template <typename T>
3065 static std::pair<diag::kind, SourceLocation>
3066 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3067   diag::kind PrevDiag;
3068   SourceLocation OldLocation = Old->getLocation();
3069   if (Old->isThisDeclarationADefinition())
3070     PrevDiag = diag::note_previous_definition;
3071   else if (Old->isImplicit()) {
3072     PrevDiag = diag::note_previous_implicit_declaration;
3073     if (OldLocation.isInvalid())
3074       OldLocation = New->getLocation();
3075   } else
3076     PrevDiag = diag::note_previous_declaration;
3077   return std::make_pair(PrevDiag, OldLocation);
3078 }
3079 
3080 /// canRedefineFunction - checks if a function can be redefined. Currently,
3081 /// only extern inline functions can be redefined, and even then only in
3082 /// GNU89 mode.
3083 static bool canRedefineFunction(const FunctionDecl *FD,
3084                                 const LangOptions& LangOpts) {
3085   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3086           !LangOpts.CPlusPlus &&
3087           FD->isInlineSpecified() &&
3088           FD->getStorageClass() == SC_Extern);
3089 }
3090 
3091 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3092   const AttributedType *AT = T->getAs<AttributedType>();
3093   while (AT && !AT->isCallingConv())
3094     AT = AT->getModifiedType()->getAs<AttributedType>();
3095   return AT;
3096 }
3097 
3098 template <typename T>
3099 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3100   const DeclContext *DC = Old->getDeclContext();
3101   if (DC->isRecord())
3102     return false;
3103 
3104   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3105   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3106     return true;
3107   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3108     return true;
3109   return false;
3110 }
3111 
3112 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3113 static bool isExternC(VarTemplateDecl *) { return false; }
3114 
3115 /// Check whether a redeclaration of an entity introduced by a
3116 /// using-declaration is valid, given that we know it's not an overload
3117 /// (nor a hidden tag declaration).
3118 template<typename ExpectedDecl>
3119 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3120                                    ExpectedDecl *New) {
3121   // C++11 [basic.scope.declarative]p4:
3122   //   Given a set of declarations in a single declarative region, each of
3123   //   which specifies the same unqualified name,
3124   //   -- they shall all refer to the same entity, or all refer to functions
3125   //      and function templates; or
3126   //   -- exactly one declaration shall declare a class name or enumeration
3127   //      name that is not a typedef name and the other declarations shall all
3128   //      refer to the same variable or enumerator, or all refer to functions
3129   //      and function templates; in this case the class name or enumeration
3130   //      name is hidden (3.3.10).
3131 
3132   // C++11 [namespace.udecl]p14:
3133   //   If a function declaration in namespace scope or block scope has the
3134   //   same name and the same parameter-type-list as a function introduced
3135   //   by a using-declaration, and the declarations do not declare the same
3136   //   function, the program is ill-formed.
3137 
3138   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3139   if (Old &&
3140       !Old->getDeclContext()->getRedeclContext()->Equals(
3141           New->getDeclContext()->getRedeclContext()) &&
3142       !(isExternC(Old) && isExternC(New)))
3143     Old = nullptr;
3144 
3145   if (!Old) {
3146     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3147     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3148     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3149     return true;
3150   }
3151   return false;
3152 }
3153 
3154 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3155                                             const FunctionDecl *B) {
3156   assert(A->getNumParams() == B->getNumParams());
3157 
3158   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3159     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3160     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3161     if (AttrA == AttrB)
3162       return true;
3163     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3164            AttrA->isDynamic() == AttrB->isDynamic();
3165   };
3166 
3167   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3168 }
3169 
3170 /// If necessary, adjust the semantic declaration context for a qualified
3171 /// declaration to name the correct inline namespace within the qualifier.
3172 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3173                                                DeclaratorDecl *OldD) {
3174   // The only case where we need to update the DeclContext is when
3175   // redeclaration lookup for a qualified name finds a declaration
3176   // in an inline namespace within the context named by the qualifier:
3177   //
3178   //   inline namespace N { int f(); }
3179   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3180   //
3181   // For unqualified declarations, the semantic context *can* change
3182   // along the redeclaration chain (for local extern declarations,
3183   // extern "C" declarations, and friend declarations in particular).
3184   if (!NewD->getQualifier())
3185     return;
3186 
3187   // NewD is probably already in the right context.
3188   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3189   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3190   if (NamedDC->Equals(SemaDC))
3191     return;
3192 
3193   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3194           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3195          "unexpected context for redeclaration");
3196 
3197   auto *LexDC = NewD->getLexicalDeclContext();
3198   auto FixSemaDC = [=](NamedDecl *D) {
3199     if (!D)
3200       return;
3201     D->setDeclContext(SemaDC);
3202     D->setLexicalDeclContext(LexDC);
3203   };
3204 
3205   FixSemaDC(NewD);
3206   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3207     FixSemaDC(FD->getDescribedFunctionTemplate());
3208   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3209     FixSemaDC(VD->getDescribedVarTemplate());
3210 }
3211 
3212 /// MergeFunctionDecl - We just parsed a function 'New' from
3213 /// declarator D which has the same name and scope as a previous
3214 /// declaration 'Old'.  Figure out how to resolve this situation,
3215 /// merging decls or emitting diagnostics as appropriate.
3216 ///
3217 /// In C++, New and Old must be declarations that are not
3218 /// overloaded. Use IsOverload to determine whether New and Old are
3219 /// overloaded, and to select the Old declaration that New should be
3220 /// merged with.
3221 ///
3222 /// Returns true if there was an error, false otherwise.
3223 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3224                              Scope *S, bool MergeTypeWithOld) {
3225   // Verify the old decl was also a function.
3226   FunctionDecl *Old = OldD->getAsFunction();
3227   if (!Old) {
3228     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3229       if (New->getFriendObjectKind()) {
3230         Diag(New->getLocation(), diag::err_using_decl_friend);
3231         Diag(Shadow->getTargetDecl()->getLocation(),
3232              diag::note_using_decl_target);
3233         Diag(Shadow->getUsingDecl()->getLocation(),
3234              diag::note_using_decl) << 0;
3235         return true;
3236       }
3237 
3238       // Check whether the two declarations might declare the same function.
3239       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3240         return true;
3241       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3242     } else {
3243       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3244         << New->getDeclName();
3245       notePreviousDefinition(OldD, New->getLocation());
3246       return true;
3247     }
3248   }
3249 
3250   // If the old declaration was found in an inline namespace and the new
3251   // declaration was qualified, update the DeclContext to match.
3252   adjustDeclContextForDeclaratorDecl(New, Old);
3253 
3254   // If the old declaration is invalid, just give up here.
3255   if (Old->isInvalidDecl())
3256     return true;
3257 
3258   // Disallow redeclaration of some builtins.
3259   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3260     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3261     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3262         << Old << Old->getType();
3263     return true;
3264   }
3265 
3266   diag::kind PrevDiag;
3267   SourceLocation OldLocation;
3268   std::tie(PrevDiag, OldLocation) =
3269       getNoteDiagForInvalidRedeclaration(Old, New);
3270 
3271   // Don't complain about this if we're in GNU89 mode and the old function
3272   // is an extern inline function.
3273   // Don't complain about specializations. They are not supposed to have
3274   // storage classes.
3275   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3276       New->getStorageClass() == SC_Static &&
3277       Old->hasExternalFormalLinkage() &&
3278       !New->getTemplateSpecializationInfo() &&
3279       !canRedefineFunction(Old, getLangOpts())) {
3280     if (getLangOpts().MicrosoftExt) {
3281       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3282       Diag(OldLocation, PrevDiag);
3283     } else {
3284       Diag(New->getLocation(), diag::err_static_non_static) << New;
3285       Diag(OldLocation, PrevDiag);
3286       return true;
3287     }
3288   }
3289 
3290   if (New->hasAttr<InternalLinkageAttr>() &&
3291       !Old->hasAttr<InternalLinkageAttr>()) {
3292     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3293         << New->getDeclName();
3294     notePreviousDefinition(Old, New->getLocation());
3295     New->dropAttr<InternalLinkageAttr>();
3296   }
3297 
3298   if (CheckRedeclarationModuleOwnership(New, Old))
3299     return true;
3300 
3301   if (!getLangOpts().CPlusPlus) {
3302     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3303     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3304       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3305         << New << OldOvl;
3306 
3307       // Try our best to find a decl that actually has the overloadable
3308       // attribute for the note. In most cases (e.g. programs with only one
3309       // broken declaration/definition), this won't matter.
3310       //
3311       // FIXME: We could do this if we juggled some extra state in
3312       // OverloadableAttr, rather than just removing it.
3313       const Decl *DiagOld = Old;
3314       if (OldOvl) {
3315         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3316           const auto *A = D->getAttr<OverloadableAttr>();
3317           return A && !A->isImplicit();
3318         });
3319         // If we've implicitly added *all* of the overloadable attrs to this
3320         // chain, emitting a "previous redecl" note is pointless.
3321         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3322       }
3323 
3324       if (DiagOld)
3325         Diag(DiagOld->getLocation(),
3326              diag::note_attribute_overloadable_prev_overload)
3327           << OldOvl;
3328 
3329       if (OldOvl)
3330         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3331       else
3332         New->dropAttr<OverloadableAttr>();
3333     }
3334   }
3335 
3336   // If a function is first declared with a calling convention, but is later
3337   // declared or defined without one, all following decls assume the calling
3338   // convention of the first.
3339   //
3340   // It's OK if a function is first declared without a calling convention,
3341   // but is later declared or defined with the default calling convention.
3342   //
3343   // To test if either decl has an explicit calling convention, we look for
3344   // AttributedType sugar nodes on the type as written.  If they are missing or
3345   // were canonicalized away, we assume the calling convention was implicit.
3346   //
3347   // Note also that we DO NOT return at this point, because we still have
3348   // other tests to run.
3349   QualType OldQType = Context.getCanonicalType(Old->getType());
3350   QualType NewQType = Context.getCanonicalType(New->getType());
3351   const FunctionType *OldType = cast<FunctionType>(OldQType);
3352   const FunctionType *NewType = cast<FunctionType>(NewQType);
3353   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3354   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3355   bool RequiresAdjustment = false;
3356 
3357   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3358     FunctionDecl *First = Old->getFirstDecl();
3359     const FunctionType *FT =
3360         First->getType().getCanonicalType()->castAs<FunctionType>();
3361     FunctionType::ExtInfo FI = FT->getExtInfo();
3362     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3363     if (!NewCCExplicit) {
3364       // Inherit the CC from the previous declaration if it was specified
3365       // there but not here.
3366       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3367       RequiresAdjustment = true;
3368     } else if (Old->getBuiltinID()) {
3369       // Builtin attribute isn't propagated to the new one yet at this point,
3370       // so we check if the old one is a builtin.
3371 
3372       // Calling Conventions on a Builtin aren't really useful and setting a
3373       // default calling convention and cdecl'ing some builtin redeclarations is
3374       // common, so warn and ignore the calling convention on the redeclaration.
3375       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3376           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3377           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3378       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3379       RequiresAdjustment = true;
3380     } else {
3381       // Calling conventions aren't compatible, so complain.
3382       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3383       Diag(New->getLocation(), diag::err_cconv_change)
3384         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3385         << !FirstCCExplicit
3386         << (!FirstCCExplicit ? "" :
3387             FunctionType::getNameForCallConv(FI.getCC()));
3388 
3389       // Put the note on the first decl, since it is the one that matters.
3390       Diag(First->getLocation(), diag::note_previous_declaration);
3391       return true;
3392     }
3393   }
3394 
3395   // FIXME: diagnose the other way around?
3396   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3397     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3398     RequiresAdjustment = true;
3399   }
3400 
3401   // Merge regparm attribute.
3402   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3403       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3404     if (NewTypeInfo.getHasRegParm()) {
3405       Diag(New->getLocation(), diag::err_regparm_mismatch)
3406         << NewType->getRegParmType()
3407         << OldType->getRegParmType();
3408       Diag(OldLocation, diag::note_previous_declaration);
3409       return true;
3410     }
3411 
3412     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3413     RequiresAdjustment = true;
3414   }
3415 
3416   // Merge ns_returns_retained attribute.
3417   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3418     if (NewTypeInfo.getProducesResult()) {
3419       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3420           << "'ns_returns_retained'";
3421       Diag(OldLocation, diag::note_previous_declaration);
3422       return true;
3423     }
3424 
3425     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3426     RequiresAdjustment = true;
3427   }
3428 
3429   if (OldTypeInfo.getNoCallerSavedRegs() !=
3430       NewTypeInfo.getNoCallerSavedRegs()) {
3431     if (NewTypeInfo.getNoCallerSavedRegs()) {
3432       AnyX86NoCallerSavedRegistersAttr *Attr =
3433         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3434       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3435       Diag(OldLocation, diag::note_previous_declaration);
3436       return true;
3437     }
3438 
3439     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3440     RequiresAdjustment = true;
3441   }
3442 
3443   if (RequiresAdjustment) {
3444     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3445     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3446     New->setType(QualType(AdjustedType, 0));
3447     NewQType = Context.getCanonicalType(New->getType());
3448   }
3449 
3450   // If this redeclaration makes the function inline, we may need to add it to
3451   // UndefinedButUsed.
3452   if (!Old->isInlined() && New->isInlined() &&
3453       !New->hasAttr<GNUInlineAttr>() &&
3454       !getLangOpts().GNUInline &&
3455       Old->isUsed(false) &&
3456       !Old->isDefined() && !New->isThisDeclarationADefinition())
3457     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3458                                            SourceLocation()));
3459 
3460   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3461   // about it.
3462   if (New->hasAttr<GNUInlineAttr>() &&
3463       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3464     UndefinedButUsed.erase(Old->getCanonicalDecl());
3465   }
3466 
3467   // If pass_object_size params don't match up perfectly, this isn't a valid
3468   // redeclaration.
3469   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3470       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3471     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3472         << New->getDeclName();
3473     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3474     return true;
3475   }
3476 
3477   if (getLangOpts().CPlusPlus) {
3478     // C++1z [over.load]p2
3479     //   Certain function declarations cannot be overloaded:
3480     //     -- Function declarations that differ only in the return type,
3481     //        the exception specification, or both cannot be overloaded.
3482 
3483     // Check the exception specifications match. This may recompute the type of
3484     // both Old and New if it resolved exception specifications, so grab the
3485     // types again after this. Because this updates the type, we do this before
3486     // any of the other checks below, which may update the "de facto" NewQType
3487     // but do not necessarily update the type of New.
3488     if (CheckEquivalentExceptionSpec(Old, New))
3489       return true;
3490     OldQType = Context.getCanonicalType(Old->getType());
3491     NewQType = Context.getCanonicalType(New->getType());
3492 
3493     // Go back to the type source info to compare the declared return types,
3494     // per C++1y [dcl.type.auto]p13:
3495     //   Redeclarations or specializations of a function or function template
3496     //   with a declared return type that uses a placeholder type shall also
3497     //   use that placeholder, not a deduced type.
3498     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3499     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3500     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3501         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3502                                        OldDeclaredReturnType)) {
3503       QualType ResQT;
3504       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3505           OldDeclaredReturnType->isObjCObjectPointerType())
3506         // FIXME: This does the wrong thing for a deduced return type.
3507         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3508       if (ResQT.isNull()) {
3509         if (New->isCXXClassMember() && New->isOutOfLine())
3510           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3511               << New << New->getReturnTypeSourceRange();
3512         else
3513           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3514               << New->getReturnTypeSourceRange();
3515         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3516                                     << Old->getReturnTypeSourceRange();
3517         return true;
3518       }
3519       else
3520         NewQType = ResQT;
3521     }
3522 
3523     QualType OldReturnType = OldType->getReturnType();
3524     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3525     if (OldReturnType != NewReturnType) {
3526       // If this function has a deduced return type and has already been
3527       // defined, copy the deduced value from the old declaration.
3528       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3529       if (OldAT && OldAT->isDeduced()) {
3530         New->setType(
3531             SubstAutoType(New->getType(),
3532                           OldAT->isDependentType() ? Context.DependentTy
3533                                                    : OldAT->getDeducedType()));
3534         NewQType = Context.getCanonicalType(
3535             SubstAutoType(NewQType,
3536                           OldAT->isDependentType() ? Context.DependentTy
3537                                                    : OldAT->getDeducedType()));
3538       }
3539     }
3540 
3541     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3542     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3543     if (OldMethod && NewMethod) {
3544       // Preserve triviality.
3545       NewMethod->setTrivial(OldMethod->isTrivial());
3546 
3547       // MSVC allows explicit template specialization at class scope:
3548       // 2 CXXMethodDecls referring to the same function will be injected.
3549       // We don't want a redeclaration error.
3550       bool IsClassScopeExplicitSpecialization =
3551                               OldMethod->isFunctionTemplateSpecialization() &&
3552                               NewMethod->isFunctionTemplateSpecialization();
3553       bool isFriend = NewMethod->getFriendObjectKind();
3554 
3555       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3556           !IsClassScopeExplicitSpecialization) {
3557         //    -- Member function declarations with the same name and the
3558         //       same parameter types cannot be overloaded if any of them
3559         //       is a static member function declaration.
3560         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3561           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3562           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3563           return true;
3564         }
3565 
3566         // C++ [class.mem]p1:
3567         //   [...] A member shall not be declared twice in the
3568         //   member-specification, except that a nested class or member
3569         //   class template can be declared and then later defined.
3570         if (!inTemplateInstantiation()) {
3571           unsigned NewDiag;
3572           if (isa<CXXConstructorDecl>(OldMethod))
3573             NewDiag = diag::err_constructor_redeclared;
3574           else if (isa<CXXDestructorDecl>(NewMethod))
3575             NewDiag = diag::err_destructor_redeclared;
3576           else if (isa<CXXConversionDecl>(NewMethod))
3577             NewDiag = diag::err_conv_function_redeclared;
3578           else
3579             NewDiag = diag::err_member_redeclared;
3580 
3581           Diag(New->getLocation(), NewDiag);
3582         } else {
3583           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3584             << New << New->getType();
3585         }
3586         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3587         return true;
3588 
3589       // Complain if this is an explicit declaration of a special
3590       // member that was initially declared implicitly.
3591       //
3592       // As an exception, it's okay to befriend such methods in order
3593       // to permit the implicit constructor/destructor/operator calls.
3594       } else if (OldMethod->isImplicit()) {
3595         if (isFriend) {
3596           NewMethod->setImplicit();
3597         } else {
3598           Diag(NewMethod->getLocation(),
3599                diag::err_definition_of_implicitly_declared_member)
3600             << New << getSpecialMember(OldMethod);
3601           return true;
3602         }
3603       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3604         Diag(NewMethod->getLocation(),
3605              diag::err_definition_of_explicitly_defaulted_member)
3606           << getSpecialMember(OldMethod);
3607         return true;
3608       }
3609     }
3610 
3611     // C++11 [dcl.attr.noreturn]p1:
3612     //   The first declaration of a function shall specify the noreturn
3613     //   attribute if any declaration of that function specifies the noreturn
3614     //   attribute.
3615     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3616     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3617       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3618       Diag(Old->getFirstDecl()->getLocation(),
3619            diag::note_noreturn_missing_first_decl);
3620     }
3621 
3622     // C++11 [dcl.attr.depend]p2:
3623     //   The first declaration of a function shall specify the
3624     //   carries_dependency attribute for its declarator-id if any declaration
3625     //   of the function specifies the carries_dependency attribute.
3626     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3627     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3628       Diag(CDA->getLocation(),
3629            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3630       Diag(Old->getFirstDecl()->getLocation(),
3631            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3632     }
3633 
3634     // (C++98 8.3.5p3):
3635     //   All declarations for a function shall agree exactly in both the
3636     //   return type and the parameter-type-list.
3637     // We also want to respect all the extended bits except noreturn.
3638 
3639     // noreturn should now match unless the old type info didn't have it.
3640     QualType OldQTypeForComparison = OldQType;
3641     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3642       auto *OldType = OldQType->castAs<FunctionProtoType>();
3643       const FunctionType *OldTypeForComparison
3644         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3645       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3646       assert(OldQTypeForComparison.isCanonical());
3647     }
3648 
3649     if (haveIncompatibleLanguageLinkages(Old, New)) {
3650       // As a special case, retain the language linkage from previous
3651       // declarations of a friend function as an extension.
3652       //
3653       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3654       // and is useful because there's otherwise no way to specify language
3655       // linkage within class scope.
3656       //
3657       // Check cautiously as the friend object kind isn't yet complete.
3658       if (New->getFriendObjectKind() != Decl::FOK_None) {
3659         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3660         Diag(OldLocation, PrevDiag);
3661       } else {
3662         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3663         Diag(OldLocation, PrevDiag);
3664         return true;
3665       }
3666     }
3667 
3668     // If the function types are compatible, merge the declarations. Ignore the
3669     // exception specifier because it was already checked above in
3670     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3671     // about incompatible types under -fms-compatibility.
3672     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3673                                                          NewQType))
3674       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3675 
3676     // If the types are imprecise (due to dependent constructs in friends or
3677     // local extern declarations), it's OK if they differ. We'll check again
3678     // during instantiation.
3679     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3680       return false;
3681 
3682     // Fall through for conflicting redeclarations and redefinitions.
3683   }
3684 
3685   // C: Function types need to be compatible, not identical. This handles
3686   // duplicate function decls like "void f(int); void f(enum X);" properly.
3687   if (!getLangOpts().CPlusPlus &&
3688       Context.typesAreCompatible(OldQType, NewQType)) {
3689     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3690     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3691     const FunctionProtoType *OldProto = nullptr;
3692     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3693         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3694       // The old declaration provided a function prototype, but the
3695       // new declaration does not. Merge in the prototype.
3696       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3697       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3698       NewQType =
3699           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3700                                   OldProto->getExtProtoInfo());
3701       New->setType(NewQType);
3702       New->setHasInheritedPrototype();
3703 
3704       // Synthesize parameters with the same types.
3705       SmallVector<ParmVarDecl*, 16> Params;
3706       for (const auto &ParamType : OldProto->param_types()) {
3707         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3708                                                  SourceLocation(), nullptr,
3709                                                  ParamType, /*TInfo=*/nullptr,
3710                                                  SC_None, nullptr);
3711         Param->setScopeInfo(0, Params.size());
3712         Param->setImplicit();
3713         Params.push_back(Param);
3714       }
3715 
3716       New->setParams(Params);
3717     }
3718 
3719     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3720   }
3721 
3722   // Check if the function types are compatible when pointer size address
3723   // spaces are ignored.
3724   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3725     return false;
3726 
3727   // GNU C permits a K&R definition to follow a prototype declaration
3728   // if the declared types of the parameters in the K&R definition
3729   // match the types in the prototype declaration, even when the
3730   // promoted types of the parameters from the K&R definition differ
3731   // from the types in the prototype. GCC then keeps the types from
3732   // the prototype.
3733   //
3734   // If a variadic prototype is followed by a non-variadic K&R definition,
3735   // the K&R definition becomes variadic.  This is sort of an edge case, but
3736   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3737   // C99 6.9.1p8.
3738   if (!getLangOpts().CPlusPlus &&
3739       Old->hasPrototype() && !New->hasPrototype() &&
3740       New->getType()->getAs<FunctionProtoType>() &&
3741       Old->getNumParams() == New->getNumParams()) {
3742     SmallVector<QualType, 16> ArgTypes;
3743     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3744     const FunctionProtoType *OldProto
3745       = Old->getType()->getAs<FunctionProtoType>();
3746     const FunctionProtoType *NewProto
3747       = New->getType()->getAs<FunctionProtoType>();
3748 
3749     // Determine whether this is the GNU C extension.
3750     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3751                                                NewProto->getReturnType());
3752     bool LooseCompatible = !MergedReturn.isNull();
3753     for (unsigned Idx = 0, End = Old->getNumParams();
3754          LooseCompatible && Idx != End; ++Idx) {
3755       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3756       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3757       if (Context.typesAreCompatible(OldParm->getType(),
3758                                      NewProto->getParamType(Idx))) {
3759         ArgTypes.push_back(NewParm->getType());
3760       } else if (Context.typesAreCompatible(OldParm->getType(),
3761                                             NewParm->getType(),
3762                                             /*CompareUnqualified=*/true)) {
3763         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3764                                            NewProto->getParamType(Idx) };
3765         Warnings.push_back(Warn);
3766         ArgTypes.push_back(NewParm->getType());
3767       } else
3768         LooseCompatible = false;
3769     }
3770 
3771     if (LooseCompatible) {
3772       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3773         Diag(Warnings[Warn].NewParm->getLocation(),
3774              diag::ext_param_promoted_not_compatible_with_prototype)
3775           << Warnings[Warn].PromotedType
3776           << Warnings[Warn].OldParm->getType();
3777         if (Warnings[Warn].OldParm->getLocation().isValid())
3778           Diag(Warnings[Warn].OldParm->getLocation(),
3779                diag::note_previous_declaration);
3780       }
3781 
3782       if (MergeTypeWithOld)
3783         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3784                                              OldProto->getExtProtoInfo()));
3785       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3786     }
3787 
3788     // Fall through to diagnose conflicting types.
3789   }
3790 
3791   // A function that has already been declared has been redeclared or
3792   // defined with a different type; show an appropriate diagnostic.
3793 
3794   // If the previous declaration was an implicitly-generated builtin
3795   // declaration, then at the very least we should use a specialized note.
3796   unsigned BuiltinID;
3797   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3798     // If it's actually a library-defined builtin function like 'malloc'
3799     // or 'printf', just warn about the incompatible redeclaration.
3800     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3801       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3802       Diag(OldLocation, diag::note_previous_builtin_declaration)
3803         << Old << Old->getType();
3804       return false;
3805     }
3806 
3807     PrevDiag = diag::note_previous_builtin_declaration;
3808   }
3809 
3810   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3811   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3812   return true;
3813 }
3814 
3815 /// Completes the merge of two function declarations that are
3816 /// known to be compatible.
3817 ///
3818 /// This routine handles the merging of attributes and other
3819 /// properties of function declarations from the old declaration to
3820 /// the new declaration, once we know that New is in fact a
3821 /// redeclaration of Old.
3822 ///
3823 /// \returns false
3824 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3825                                         Scope *S, bool MergeTypeWithOld) {
3826   // Merge the attributes
3827   mergeDeclAttributes(New, Old);
3828 
3829   // Merge "pure" flag.
3830   if (Old->isPure())
3831     New->setPure();
3832 
3833   // Merge "used" flag.
3834   if (Old->getMostRecentDecl()->isUsed(false))
3835     New->setIsUsed();
3836 
3837   // Merge attributes from the parameters.  These can mismatch with K&R
3838   // declarations.
3839   if (New->getNumParams() == Old->getNumParams())
3840       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3841         ParmVarDecl *NewParam = New->getParamDecl(i);
3842         ParmVarDecl *OldParam = Old->getParamDecl(i);
3843         mergeParamDeclAttributes(NewParam, OldParam, *this);
3844         mergeParamDeclTypes(NewParam, OldParam, *this);
3845       }
3846 
3847   if (getLangOpts().CPlusPlus)
3848     return MergeCXXFunctionDecl(New, Old, S);
3849 
3850   // Merge the function types so the we get the composite types for the return
3851   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3852   // was visible.
3853   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3854   if (!Merged.isNull() && MergeTypeWithOld)
3855     New->setType(Merged);
3856 
3857   return false;
3858 }
3859 
3860 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3861                                 ObjCMethodDecl *oldMethod) {
3862   // Merge the attributes, including deprecated/unavailable
3863   AvailabilityMergeKind MergeKind =
3864     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3865       ? AMK_ProtocolImplementation
3866       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3867                                                        : AMK_Override;
3868 
3869   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3870 
3871   // Merge attributes from the parameters.
3872   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3873                                        oe = oldMethod->param_end();
3874   for (ObjCMethodDecl::param_iterator
3875          ni = newMethod->param_begin(), ne = newMethod->param_end();
3876        ni != ne && oi != oe; ++ni, ++oi)
3877     mergeParamDeclAttributes(*ni, *oi, *this);
3878 
3879   CheckObjCMethodOverride(newMethod, oldMethod);
3880 }
3881 
3882 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3883   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3884 
3885   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3886          ? diag::err_redefinition_different_type
3887          : diag::err_redeclaration_different_type)
3888     << New->getDeclName() << New->getType() << Old->getType();
3889 
3890   diag::kind PrevDiag;
3891   SourceLocation OldLocation;
3892   std::tie(PrevDiag, OldLocation)
3893     = getNoteDiagForInvalidRedeclaration(Old, New);
3894   S.Diag(OldLocation, PrevDiag);
3895   New->setInvalidDecl();
3896 }
3897 
3898 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3899 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3900 /// emitting diagnostics as appropriate.
3901 ///
3902 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3903 /// to here in AddInitializerToDecl. We can't check them before the initializer
3904 /// is attached.
3905 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3906                              bool MergeTypeWithOld) {
3907   if (New->isInvalidDecl() || Old->isInvalidDecl())
3908     return;
3909 
3910   QualType MergedT;
3911   if (getLangOpts().CPlusPlus) {
3912     if (New->getType()->isUndeducedType()) {
3913       // We don't know what the new type is until the initializer is attached.
3914       return;
3915     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3916       // These could still be something that needs exception specs checked.
3917       return MergeVarDeclExceptionSpecs(New, Old);
3918     }
3919     // C++ [basic.link]p10:
3920     //   [...] the types specified by all declarations referring to a given
3921     //   object or function shall be identical, except that declarations for an
3922     //   array object can specify array types that differ by the presence or
3923     //   absence of a major array bound (8.3.4).
3924     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3925       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3926       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3927 
3928       // We are merging a variable declaration New into Old. If it has an array
3929       // bound, and that bound differs from Old's bound, we should diagnose the
3930       // mismatch.
3931       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3932         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3933              PrevVD = PrevVD->getPreviousDecl()) {
3934           QualType PrevVDTy = PrevVD->getType();
3935           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3936             continue;
3937 
3938           if (!Context.hasSameType(New->getType(), PrevVDTy))
3939             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3940         }
3941       }
3942 
3943       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3944         if (Context.hasSameType(OldArray->getElementType(),
3945                                 NewArray->getElementType()))
3946           MergedT = New->getType();
3947       }
3948       // FIXME: Check visibility. New is hidden but has a complete type. If New
3949       // has no array bound, it should not inherit one from Old, if Old is not
3950       // visible.
3951       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3952         if (Context.hasSameType(OldArray->getElementType(),
3953                                 NewArray->getElementType()))
3954           MergedT = Old->getType();
3955       }
3956     }
3957     else if (New->getType()->isObjCObjectPointerType() &&
3958                Old->getType()->isObjCObjectPointerType()) {
3959       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3960                                               Old->getType());
3961     }
3962   } else {
3963     // C 6.2.7p2:
3964     //   All declarations that refer to the same object or function shall have
3965     //   compatible type.
3966     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3967   }
3968   if (MergedT.isNull()) {
3969     // It's OK if we couldn't merge types if either type is dependent, for a
3970     // block-scope variable. In other cases (static data members of class
3971     // templates, variable templates, ...), we require the types to be
3972     // equivalent.
3973     // FIXME: The C++ standard doesn't say anything about this.
3974     if ((New->getType()->isDependentType() ||
3975          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3976       // If the old type was dependent, we can't merge with it, so the new type
3977       // becomes dependent for now. We'll reproduce the original type when we
3978       // instantiate the TypeSourceInfo for the variable.
3979       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3980         New->setType(Context.DependentTy);
3981       return;
3982     }
3983     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3984   }
3985 
3986   // Don't actually update the type on the new declaration if the old
3987   // declaration was an extern declaration in a different scope.
3988   if (MergeTypeWithOld)
3989     New->setType(MergedT);
3990 }
3991 
3992 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3993                                   LookupResult &Previous) {
3994   // C11 6.2.7p4:
3995   //   For an identifier with internal or external linkage declared
3996   //   in a scope in which a prior declaration of that identifier is
3997   //   visible, if the prior declaration specifies internal or
3998   //   external linkage, the type of the identifier at the later
3999   //   declaration becomes the composite type.
4000   //
4001   // If the variable isn't visible, we do not merge with its type.
4002   if (Previous.isShadowed())
4003     return false;
4004 
4005   if (S.getLangOpts().CPlusPlus) {
4006     // C++11 [dcl.array]p3:
4007     //   If there is a preceding declaration of the entity in the same
4008     //   scope in which the bound was specified, an omitted array bound
4009     //   is taken to be the same as in that earlier declaration.
4010     return NewVD->isPreviousDeclInSameBlockScope() ||
4011            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4012             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4013   } else {
4014     // If the old declaration was function-local, don't merge with its
4015     // type unless we're in the same function.
4016     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4017            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4018   }
4019 }
4020 
4021 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4022 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4023 /// situation, merging decls or emitting diagnostics as appropriate.
4024 ///
4025 /// Tentative definition rules (C99 6.9.2p2) are checked by
4026 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4027 /// definitions here, since the initializer hasn't been attached.
4028 ///
4029 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4030   // If the new decl is already invalid, don't do any other checking.
4031   if (New->isInvalidDecl())
4032     return;
4033 
4034   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4035     return;
4036 
4037   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4038 
4039   // Verify the old decl was also a variable or variable template.
4040   VarDecl *Old = nullptr;
4041   VarTemplateDecl *OldTemplate = nullptr;
4042   if (Previous.isSingleResult()) {
4043     if (NewTemplate) {
4044       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4045       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4046 
4047       if (auto *Shadow =
4048               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4049         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4050           return New->setInvalidDecl();
4051     } else {
4052       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4053 
4054       if (auto *Shadow =
4055               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4056         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4057           return New->setInvalidDecl();
4058     }
4059   }
4060   if (!Old) {
4061     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4062         << New->getDeclName();
4063     notePreviousDefinition(Previous.getRepresentativeDecl(),
4064                            New->getLocation());
4065     return New->setInvalidDecl();
4066   }
4067 
4068   // If the old declaration was found in an inline namespace and the new
4069   // declaration was qualified, update the DeclContext to match.
4070   adjustDeclContextForDeclaratorDecl(New, Old);
4071 
4072   // Ensure the template parameters are compatible.
4073   if (NewTemplate &&
4074       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4075                                       OldTemplate->getTemplateParameters(),
4076                                       /*Complain=*/true, TPL_TemplateMatch))
4077     return New->setInvalidDecl();
4078 
4079   // C++ [class.mem]p1:
4080   //   A member shall not be declared twice in the member-specification [...]
4081   //
4082   // Here, we need only consider static data members.
4083   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4084     Diag(New->getLocation(), diag::err_duplicate_member)
4085       << New->getIdentifier();
4086     Diag(Old->getLocation(), diag::note_previous_declaration);
4087     New->setInvalidDecl();
4088   }
4089 
4090   mergeDeclAttributes(New, Old);
4091   // Warn if an already-declared variable is made a weak_import in a subsequent
4092   // declaration
4093   if (New->hasAttr<WeakImportAttr>() &&
4094       Old->getStorageClass() == SC_None &&
4095       !Old->hasAttr<WeakImportAttr>()) {
4096     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4097     notePreviousDefinition(Old, New->getLocation());
4098     // Remove weak_import attribute on new declaration.
4099     New->dropAttr<WeakImportAttr>();
4100   }
4101 
4102   if (New->hasAttr<InternalLinkageAttr>() &&
4103       !Old->hasAttr<InternalLinkageAttr>()) {
4104     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4105         << New->getDeclName();
4106     notePreviousDefinition(Old, New->getLocation());
4107     New->dropAttr<InternalLinkageAttr>();
4108   }
4109 
4110   // Merge the types.
4111   VarDecl *MostRecent = Old->getMostRecentDecl();
4112   if (MostRecent != Old) {
4113     MergeVarDeclTypes(New, MostRecent,
4114                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4115     if (New->isInvalidDecl())
4116       return;
4117   }
4118 
4119   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4120   if (New->isInvalidDecl())
4121     return;
4122 
4123   diag::kind PrevDiag;
4124   SourceLocation OldLocation;
4125   std::tie(PrevDiag, OldLocation) =
4126       getNoteDiagForInvalidRedeclaration(Old, New);
4127 
4128   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4129   if (New->getStorageClass() == SC_Static &&
4130       !New->isStaticDataMember() &&
4131       Old->hasExternalFormalLinkage()) {
4132     if (getLangOpts().MicrosoftExt) {
4133       Diag(New->getLocation(), diag::ext_static_non_static)
4134           << New->getDeclName();
4135       Diag(OldLocation, PrevDiag);
4136     } else {
4137       Diag(New->getLocation(), diag::err_static_non_static)
4138           << New->getDeclName();
4139       Diag(OldLocation, PrevDiag);
4140       return New->setInvalidDecl();
4141     }
4142   }
4143   // C99 6.2.2p4:
4144   //   For an identifier declared with the storage-class specifier
4145   //   extern in a scope in which a prior declaration of that
4146   //   identifier is visible,23) if the prior declaration specifies
4147   //   internal or external linkage, the linkage of the identifier at
4148   //   the later declaration is the same as the linkage specified at
4149   //   the prior declaration. If no prior declaration is visible, or
4150   //   if the prior declaration specifies no linkage, then the
4151   //   identifier has external linkage.
4152   if (New->hasExternalStorage() && Old->hasLinkage())
4153     /* Okay */;
4154   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4155            !New->isStaticDataMember() &&
4156            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4157     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4158     Diag(OldLocation, PrevDiag);
4159     return New->setInvalidDecl();
4160   }
4161 
4162   // Check if extern is followed by non-extern and vice-versa.
4163   if (New->hasExternalStorage() &&
4164       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4165     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4166     Diag(OldLocation, PrevDiag);
4167     return New->setInvalidDecl();
4168   }
4169   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4170       !New->hasExternalStorage()) {
4171     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4172     Diag(OldLocation, PrevDiag);
4173     return New->setInvalidDecl();
4174   }
4175 
4176   if (CheckRedeclarationModuleOwnership(New, Old))
4177     return;
4178 
4179   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4180 
4181   // FIXME: The test for external storage here seems wrong? We still
4182   // need to check for mismatches.
4183   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4184       // Don't complain about out-of-line definitions of static members.
4185       !(Old->getLexicalDeclContext()->isRecord() &&
4186         !New->getLexicalDeclContext()->isRecord())) {
4187     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4188     Diag(OldLocation, PrevDiag);
4189     return New->setInvalidDecl();
4190   }
4191 
4192   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4193     if (VarDecl *Def = Old->getDefinition()) {
4194       // C++1z [dcl.fcn.spec]p4:
4195       //   If the definition of a variable appears in a translation unit before
4196       //   its first declaration as inline, the program is ill-formed.
4197       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4198       Diag(Def->getLocation(), diag::note_previous_definition);
4199     }
4200   }
4201 
4202   // If this redeclaration makes the variable inline, we may need to add it to
4203   // UndefinedButUsed.
4204   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4205       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4206     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4207                                            SourceLocation()));
4208 
4209   if (New->getTLSKind() != Old->getTLSKind()) {
4210     if (!Old->getTLSKind()) {
4211       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4212       Diag(OldLocation, PrevDiag);
4213     } else if (!New->getTLSKind()) {
4214       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4215       Diag(OldLocation, PrevDiag);
4216     } else {
4217       // Do not allow redeclaration to change the variable between requiring
4218       // static and dynamic initialization.
4219       // FIXME: GCC allows this, but uses the TLS keyword on the first
4220       // declaration to determine the kind. Do we need to be compatible here?
4221       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4222         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4223       Diag(OldLocation, PrevDiag);
4224     }
4225   }
4226 
4227   // C++ doesn't have tentative definitions, so go right ahead and check here.
4228   if (getLangOpts().CPlusPlus &&
4229       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4230     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4231         Old->getCanonicalDecl()->isConstexpr()) {
4232       // This definition won't be a definition any more once it's been merged.
4233       Diag(New->getLocation(),
4234            diag::warn_deprecated_redundant_constexpr_static_def);
4235     } else if (VarDecl *Def = Old->getDefinition()) {
4236       if (checkVarDeclRedefinition(Def, New))
4237         return;
4238     }
4239   }
4240 
4241   if (haveIncompatibleLanguageLinkages(Old, New)) {
4242     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4243     Diag(OldLocation, PrevDiag);
4244     New->setInvalidDecl();
4245     return;
4246   }
4247 
4248   // Merge "used" flag.
4249   if (Old->getMostRecentDecl()->isUsed(false))
4250     New->setIsUsed();
4251 
4252   // Keep a chain of previous declarations.
4253   New->setPreviousDecl(Old);
4254   if (NewTemplate)
4255     NewTemplate->setPreviousDecl(OldTemplate);
4256 
4257   // Inherit access appropriately.
4258   New->setAccess(Old->getAccess());
4259   if (NewTemplate)
4260     NewTemplate->setAccess(New->getAccess());
4261 
4262   if (Old->isInline())
4263     New->setImplicitlyInline();
4264 }
4265 
4266 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4267   SourceManager &SrcMgr = getSourceManager();
4268   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4269   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4270   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4271   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4272   auto &HSI = PP.getHeaderSearchInfo();
4273   StringRef HdrFilename =
4274       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4275 
4276   auto noteFromModuleOrInclude = [&](Module *Mod,
4277                                      SourceLocation IncLoc) -> bool {
4278     // Redefinition errors with modules are common with non modular mapped
4279     // headers, example: a non-modular header H in module A that also gets
4280     // included directly in a TU. Pointing twice to the same header/definition
4281     // is confusing, try to get better diagnostics when modules is on.
4282     if (IncLoc.isValid()) {
4283       if (Mod) {
4284         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4285             << HdrFilename.str() << Mod->getFullModuleName();
4286         if (!Mod->DefinitionLoc.isInvalid())
4287           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4288               << Mod->getFullModuleName();
4289       } else {
4290         Diag(IncLoc, diag::note_redefinition_include_same_file)
4291             << HdrFilename.str();
4292       }
4293       return true;
4294     }
4295 
4296     return false;
4297   };
4298 
4299   // Is it the same file and same offset? Provide more information on why
4300   // this leads to a redefinition error.
4301   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4302     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4303     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4304     bool EmittedDiag =
4305         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4306     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4307 
4308     // If the header has no guards, emit a note suggesting one.
4309     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4310       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4311 
4312     if (EmittedDiag)
4313       return;
4314   }
4315 
4316   // Redefinition coming from different files or couldn't do better above.
4317   if (Old->getLocation().isValid())
4318     Diag(Old->getLocation(), diag::note_previous_definition);
4319 }
4320 
4321 /// We've just determined that \p Old and \p New both appear to be definitions
4322 /// of the same variable. Either diagnose or fix the problem.
4323 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4324   if (!hasVisibleDefinition(Old) &&
4325       (New->getFormalLinkage() == InternalLinkage ||
4326        New->isInline() ||
4327        New->getDescribedVarTemplate() ||
4328        New->getNumTemplateParameterLists() ||
4329        New->getDeclContext()->isDependentContext())) {
4330     // The previous definition is hidden, and multiple definitions are
4331     // permitted (in separate TUs). Demote this to a declaration.
4332     New->demoteThisDefinitionToDeclaration();
4333 
4334     // Make the canonical definition visible.
4335     if (auto *OldTD = Old->getDescribedVarTemplate())
4336       makeMergedDefinitionVisible(OldTD);
4337     makeMergedDefinitionVisible(Old);
4338     return false;
4339   } else {
4340     Diag(New->getLocation(), diag::err_redefinition) << New;
4341     notePreviousDefinition(Old, New->getLocation());
4342     New->setInvalidDecl();
4343     return true;
4344   }
4345 }
4346 
4347 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4348 /// no declarator (e.g. "struct foo;") is parsed.
4349 Decl *
4350 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4351                                  RecordDecl *&AnonRecord) {
4352   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4353                                     AnonRecord);
4354 }
4355 
4356 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4357 // disambiguate entities defined in different scopes.
4358 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4359 // compatibility.
4360 // We will pick our mangling number depending on which version of MSVC is being
4361 // targeted.
4362 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4363   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4364              ? S->getMSCurManglingNumber()
4365              : S->getMSLastManglingNumber();
4366 }
4367 
4368 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4369   if (!Context.getLangOpts().CPlusPlus)
4370     return;
4371 
4372   if (isa<CXXRecordDecl>(Tag->getParent())) {
4373     // If this tag is the direct child of a class, number it if
4374     // it is anonymous.
4375     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4376       return;
4377     MangleNumberingContext &MCtx =
4378         Context.getManglingNumberContext(Tag->getParent());
4379     Context.setManglingNumber(
4380         Tag, MCtx.getManglingNumber(
4381                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4382     return;
4383   }
4384 
4385   // If this tag isn't a direct child of a class, number it if it is local.
4386   MangleNumberingContext *MCtx;
4387   Decl *ManglingContextDecl;
4388   std::tie(MCtx, ManglingContextDecl) =
4389       getCurrentMangleNumberContext(Tag->getDeclContext());
4390   if (MCtx) {
4391     Context.setManglingNumber(
4392         Tag, MCtx->getManglingNumber(
4393                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4394   }
4395 }
4396 
4397 namespace {
4398 struct NonCLikeKind {
4399   enum {
4400     None,
4401     BaseClass,
4402     DefaultMemberInit,
4403     Lambda,
4404     Friend,
4405     OtherMember,
4406     Invalid,
4407   } Kind = None;
4408   SourceRange Range;
4409 
4410   explicit operator bool() { return Kind != None; }
4411 };
4412 }
4413 
4414 /// Determine whether a class is C-like, according to the rules of C++
4415 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4416 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4417   if (RD->isInvalidDecl())
4418     return {NonCLikeKind::Invalid, {}};
4419 
4420   // C++ [dcl.typedef]p9: [P1766R1]
4421   //   An unnamed class with a typedef name for linkage purposes shall not
4422   //
4423   //    -- have any base classes
4424   if (RD->getNumBases())
4425     return {NonCLikeKind::BaseClass,
4426             SourceRange(RD->bases_begin()->getBeginLoc(),
4427                         RD->bases_end()[-1].getEndLoc())};
4428   bool Invalid = false;
4429   for (Decl *D : RD->decls()) {
4430     // Don't complain about things we already diagnosed.
4431     if (D->isInvalidDecl()) {
4432       Invalid = true;
4433       continue;
4434     }
4435 
4436     //  -- have any [...] default member initializers
4437     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4438       if (FD->hasInClassInitializer()) {
4439         auto *Init = FD->getInClassInitializer();
4440         return {NonCLikeKind::DefaultMemberInit,
4441                 Init ? Init->getSourceRange() : D->getSourceRange()};
4442       }
4443       continue;
4444     }
4445 
4446     // FIXME: We don't allow friend declarations. This violates the wording of
4447     // P1766, but not the intent.
4448     if (isa<FriendDecl>(D))
4449       return {NonCLikeKind::Friend, D->getSourceRange()};
4450 
4451     //  -- declare any members other than non-static data members, member
4452     //     enumerations, or member classes,
4453     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4454         isa<EnumDecl>(D))
4455       continue;
4456     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4457     if (!MemberRD) {
4458       if (D->isImplicit())
4459         continue;
4460       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4461     }
4462 
4463     //  -- contain a lambda-expression,
4464     if (MemberRD->isLambda())
4465       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4466 
4467     //  and all member classes shall also satisfy these requirements
4468     //  (recursively).
4469     if (MemberRD->isThisDeclarationADefinition()) {
4470       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4471         return Kind;
4472     }
4473   }
4474 
4475   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4476 }
4477 
4478 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4479                                         TypedefNameDecl *NewTD) {
4480   if (TagFromDeclSpec->isInvalidDecl())
4481     return;
4482 
4483   // Do nothing if the tag already has a name for linkage purposes.
4484   if (TagFromDeclSpec->hasNameForLinkage())
4485     return;
4486 
4487   // A well-formed anonymous tag must always be a TUK_Definition.
4488   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4489 
4490   // The type must match the tag exactly;  no qualifiers allowed.
4491   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4492                            Context.getTagDeclType(TagFromDeclSpec))) {
4493     if (getLangOpts().CPlusPlus)
4494       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4495     return;
4496   }
4497 
4498   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4499   //   An unnamed class with a typedef name for linkage purposes shall [be
4500   //   C-like].
4501   //
4502   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4503   // shouldn't happen, but there are constructs that the language rule doesn't
4504   // disallow for which we can't reasonably avoid computing linkage early.
4505   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4506   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4507                              : NonCLikeKind();
4508   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4509   if (NonCLike || ChangesLinkage) {
4510     if (NonCLike.Kind == NonCLikeKind::Invalid)
4511       return;
4512 
4513     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4514     if (ChangesLinkage) {
4515       // If the linkage changes, we can't accept this as an extension.
4516       if (NonCLike.Kind == NonCLikeKind::None)
4517         DiagID = diag::err_typedef_changes_linkage;
4518       else
4519         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4520     }
4521 
4522     SourceLocation FixitLoc =
4523         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4524     llvm::SmallString<40> TextToInsert;
4525     TextToInsert += ' ';
4526     TextToInsert += NewTD->getIdentifier()->getName();
4527 
4528     Diag(FixitLoc, DiagID)
4529       << isa<TypeAliasDecl>(NewTD)
4530       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4531     if (NonCLike.Kind != NonCLikeKind::None) {
4532       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4533         << NonCLike.Kind - 1 << NonCLike.Range;
4534     }
4535     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4536       << NewTD << isa<TypeAliasDecl>(NewTD);
4537 
4538     if (ChangesLinkage)
4539       return;
4540   }
4541 
4542   // Otherwise, set this as the anon-decl typedef for the tag.
4543   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4544 }
4545 
4546 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4547   switch (T) {
4548   case DeclSpec::TST_class:
4549     return 0;
4550   case DeclSpec::TST_struct:
4551     return 1;
4552   case DeclSpec::TST_interface:
4553     return 2;
4554   case DeclSpec::TST_union:
4555     return 3;
4556   case DeclSpec::TST_enum:
4557     return 4;
4558   default:
4559     llvm_unreachable("unexpected type specifier");
4560   }
4561 }
4562 
4563 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4564 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4565 /// parameters to cope with template friend declarations.
4566 Decl *
4567 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4568                                  MultiTemplateParamsArg TemplateParams,
4569                                  bool IsExplicitInstantiation,
4570                                  RecordDecl *&AnonRecord) {
4571   Decl *TagD = nullptr;
4572   TagDecl *Tag = nullptr;
4573   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4574       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4575       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4576       DS.getTypeSpecType() == DeclSpec::TST_union ||
4577       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4578     TagD = DS.getRepAsDecl();
4579 
4580     if (!TagD) // We probably had an error
4581       return nullptr;
4582 
4583     // Note that the above type specs guarantee that the
4584     // type rep is a Decl, whereas in many of the others
4585     // it's a Type.
4586     if (isa<TagDecl>(TagD))
4587       Tag = cast<TagDecl>(TagD);
4588     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4589       Tag = CTD->getTemplatedDecl();
4590   }
4591 
4592   if (Tag) {
4593     handleTagNumbering(Tag, S);
4594     Tag->setFreeStanding();
4595     if (Tag->isInvalidDecl())
4596       return Tag;
4597   }
4598 
4599   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4600     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4601     // or incomplete types shall not be restrict-qualified."
4602     if (TypeQuals & DeclSpec::TQ_restrict)
4603       Diag(DS.getRestrictSpecLoc(),
4604            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4605            << DS.getSourceRange();
4606   }
4607 
4608   if (DS.isInlineSpecified())
4609     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4610         << getLangOpts().CPlusPlus17;
4611 
4612   if (DS.hasConstexprSpecifier()) {
4613     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4614     // and definitions of functions and variables.
4615     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4616     // the declaration of a function or function template
4617     if (Tag)
4618       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4619           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4620           << static_cast<int>(DS.getConstexprSpecifier());
4621     else
4622       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4623           << static_cast<int>(DS.getConstexprSpecifier());
4624     // Don't emit warnings after this error.
4625     return TagD;
4626   }
4627 
4628   DiagnoseFunctionSpecifiers(DS);
4629 
4630   if (DS.isFriendSpecified()) {
4631     // If we're dealing with a decl but not a TagDecl, assume that
4632     // whatever routines created it handled the friendship aspect.
4633     if (TagD && !Tag)
4634       return nullptr;
4635     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4636   }
4637 
4638   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4639   bool IsExplicitSpecialization =
4640     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4641   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4642       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4643       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4644     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4645     // nested-name-specifier unless it is an explicit instantiation
4646     // or an explicit specialization.
4647     //
4648     // FIXME: We allow class template partial specializations here too, per the
4649     // obvious intent of DR1819.
4650     //
4651     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4652     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4653         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4654     return nullptr;
4655   }
4656 
4657   // Track whether this decl-specifier declares anything.
4658   bool DeclaresAnything = true;
4659 
4660   // Handle anonymous struct definitions.
4661   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4662     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4663         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4664       if (getLangOpts().CPlusPlus ||
4665           Record->getDeclContext()->isRecord()) {
4666         // If CurContext is a DeclContext that can contain statements,
4667         // RecursiveASTVisitor won't visit the decls that
4668         // BuildAnonymousStructOrUnion() will put into CurContext.
4669         // Also store them here so that they can be part of the
4670         // DeclStmt that gets created in this case.
4671         // FIXME: Also return the IndirectFieldDecls created by
4672         // BuildAnonymousStructOr union, for the same reason?
4673         if (CurContext->isFunctionOrMethod())
4674           AnonRecord = Record;
4675         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4676                                            Context.getPrintingPolicy());
4677       }
4678 
4679       DeclaresAnything = false;
4680     }
4681   }
4682 
4683   // C11 6.7.2.1p2:
4684   //   A struct-declaration that does not declare an anonymous structure or
4685   //   anonymous union shall contain a struct-declarator-list.
4686   //
4687   // This rule also existed in C89 and C99; the grammar for struct-declaration
4688   // did not permit a struct-declaration without a struct-declarator-list.
4689   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4690       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4691     // Check for Microsoft C extension: anonymous struct/union member.
4692     // Handle 2 kinds of anonymous struct/union:
4693     //   struct STRUCT;
4694     //   union UNION;
4695     // and
4696     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4697     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4698     if ((Tag && Tag->getDeclName()) ||
4699         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4700       RecordDecl *Record = nullptr;
4701       if (Tag)
4702         Record = dyn_cast<RecordDecl>(Tag);
4703       else if (const RecordType *RT =
4704                    DS.getRepAsType().get()->getAsStructureType())
4705         Record = RT->getDecl();
4706       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4707         Record = UT->getDecl();
4708 
4709       if (Record && getLangOpts().MicrosoftExt) {
4710         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4711             << Record->isUnion() << DS.getSourceRange();
4712         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4713       }
4714 
4715       DeclaresAnything = false;
4716     }
4717   }
4718 
4719   // Skip all the checks below if we have a type error.
4720   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4721       (TagD && TagD->isInvalidDecl()))
4722     return TagD;
4723 
4724   if (getLangOpts().CPlusPlus &&
4725       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4726     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4727       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4728           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4729         DeclaresAnything = false;
4730 
4731   if (!DS.isMissingDeclaratorOk()) {
4732     // Customize diagnostic for a typedef missing a name.
4733     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4734       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4735           << DS.getSourceRange();
4736     else
4737       DeclaresAnything = false;
4738   }
4739 
4740   if (DS.isModulePrivateSpecified() &&
4741       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4742     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4743       << Tag->getTagKind()
4744       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4745 
4746   ActOnDocumentableDecl(TagD);
4747 
4748   // C 6.7/2:
4749   //   A declaration [...] shall declare at least a declarator [...], a tag,
4750   //   or the members of an enumeration.
4751   // C++ [dcl.dcl]p3:
4752   //   [If there are no declarators], and except for the declaration of an
4753   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4754   //   names into the program, or shall redeclare a name introduced by a
4755   //   previous declaration.
4756   if (!DeclaresAnything) {
4757     // In C, we allow this as a (popular) extension / bug. Don't bother
4758     // producing further diagnostics for redundant qualifiers after this.
4759     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4760                                ? diag::err_no_declarators
4761                                : diag::ext_no_declarators)
4762         << DS.getSourceRange();
4763     return TagD;
4764   }
4765 
4766   // C++ [dcl.stc]p1:
4767   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4768   //   init-declarator-list of the declaration shall not be empty.
4769   // C++ [dcl.fct.spec]p1:
4770   //   If a cv-qualifier appears in a decl-specifier-seq, the
4771   //   init-declarator-list of the declaration shall not be empty.
4772   //
4773   // Spurious qualifiers here appear to be valid in C.
4774   unsigned DiagID = diag::warn_standalone_specifier;
4775   if (getLangOpts().CPlusPlus)
4776     DiagID = diag::ext_standalone_specifier;
4777 
4778   // Note that a linkage-specification sets a storage class, but
4779   // 'extern "C" struct foo;' is actually valid and not theoretically
4780   // useless.
4781   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4782     if (SCS == DeclSpec::SCS_mutable)
4783       // Since mutable is not a viable storage class specifier in C, there is
4784       // no reason to treat it as an extension. Instead, diagnose as an error.
4785       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4786     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4787       Diag(DS.getStorageClassSpecLoc(), DiagID)
4788         << DeclSpec::getSpecifierName(SCS);
4789   }
4790 
4791   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4792     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4793       << DeclSpec::getSpecifierName(TSCS);
4794   if (DS.getTypeQualifiers()) {
4795     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4796       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4797     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4798       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4799     // Restrict is covered above.
4800     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4801       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4802     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4803       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4804   }
4805 
4806   // Warn about ignored type attributes, for example:
4807   // __attribute__((aligned)) struct A;
4808   // Attributes should be placed after tag to apply to type declaration.
4809   if (!DS.getAttributes().empty()) {
4810     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4811     if (TypeSpecType == DeclSpec::TST_class ||
4812         TypeSpecType == DeclSpec::TST_struct ||
4813         TypeSpecType == DeclSpec::TST_interface ||
4814         TypeSpecType == DeclSpec::TST_union ||
4815         TypeSpecType == DeclSpec::TST_enum) {
4816       for (const ParsedAttr &AL : DS.getAttributes())
4817         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4818             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4819     }
4820   }
4821 
4822   return TagD;
4823 }
4824 
4825 /// We are trying to inject an anonymous member into the given scope;
4826 /// check if there's an existing declaration that can't be overloaded.
4827 ///
4828 /// \return true if this is a forbidden redeclaration
4829 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4830                                          Scope *S,
4831                                          DeclContext *Owner,
4832                                          DeclarationName Name,
4833                                          SourceLocation NameLoc,
4834                                          bool IsUnion) {
4835   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4836                  Sema::ForVisibleRedeclaration);
4837   if (!SemaRef.LookupName(R, S)) return false;
4838 
4839   // Pick a representative declaration.
4840   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4841   assert(PrevDecl && "Expected a non-null Decl");
4842 
4843   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4844     return false;
4845 
4846   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4847     << IsUnion << Name;
4848   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4849 
4850   return true;
4851 }
4852 
4853 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4854 /// anonymous struct or union AnonRecord into the owning context Owner
4855 /// and scope S. This routine will be invoked just after we realize
4856 /// that an unnamed union or struct is actually an anonymous union or
4857 /// struct, e.g.,
4858 ///
4859 /// @code
4860 /// union {
4861 ///   int i;
4862 ///   float f;
4863 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4864 ///    // f into the surrounding scope.x
4865 /// @endcode
4866 ///
4867 /// This routine is recursive, injecting the names of nested anonymous
4868 /// structs/unions into the owning context and scope as well.
4869 static bool
4870 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4871                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4872                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4873   bool Invalid = false;
4874 
4875   // Look every FieldDecl and IndirectFieldDecl with a name.
4876   for (auto *D : AnonRecord->decls()) {
4877     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4878         cast<NamedDecl>(D)->getDeclName()) {
4879       ValueDecl *VD = cast<ValueDecl>(D);
4880       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4881                                        VD->getLocation(),
4882                                        AnonRecord->isUnion())) {
4883         // C++ [class.union]p2:
4884         //   The names of the members of an anonymous union shall be
4885         //   distinct from the names of any other entity in the
4886         //   scope in which the anonymous union is declared.
4887         Invalid = true;
4888       } else {
4889         // C++ [class.union]p2:
4890         //   For the purpose of name lookup, after the anonymous union
4891         //   definition, the members of the anonymous union are
4892         //   considered to have been defined in the scope in which the
4893         //   anonymous union is declared.
4894         unsigned OldChainingSize = Chaining.size();
4895         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4896           Chaining.append(IF->chain_begin(), IF->chain_end());
4897         else
4898           Chaining.push_back(VD);
4899 
4900         assert(Chaining.size() >= 2);
4901         NamedDecl **NamedChain =
4902           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4903         for (unsigned i = 0; i < Chaining.size(); i++)
4904           NamedChain[i] = Chaining[i];
4905 
4906         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4907             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4908             VD->getType(), {NamedChain, Chaining.size()});
4909 
4910         for (const auto *Attr : VD->attrs())
4911           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4912 
4913         IndirectField->setAccess(AS);
4914         IndirectField->setImplicit();
4915         SemaRef.PushOnScopeChains(IndirectField, S);
4916 
4917         // That includes picking up the appropriate access specifier.
4918         if (AS != AS_none) IndirectField->setAccess(AS);
4919 
4920         Chaining.resize(OldChainingSize);
4921       }
4922     }
4923   }
4924 
4925   return Invalid;
4926 }
4927 
4928 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4929 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4930 /// illegal input values are mapped to SC_None.
4931 static StorageClass
4932 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4933   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4934   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4935          "Parser allowed 'typedef' as storage class VarDecl.");
4936   switch (StorageClassSpec) {
4937   case DeclSpec::SCS_unspecified:    return SC_None;
4938   case DeclSpec::SCS_extern:
4939     if (DS.isExternInLinkageSpec())
4940       return SC_None;
4941     return SC_Extern;
4942   case DeclSpec::SCS_static:         return SC_Static;
4943   case DeclSpec::SCS_auto:           return SC_Auto;
4944   case DeclSpec::SCS_register:       return SC_Register;
4945   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4946     // Illegal SCSs map to None: error reporting is up to the caller.
4947   case DeclSpec::SCS_mutable:        // Fall through.
4948   case DeclSpec::SCS_typedef:        return SC_None;
4949   }
4950   llvm_unreachable("unknown storage class specifier");
4951 }
4952 
4953 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4954   assert(Record->hasInClassInitializer());
4955 
4956   for (const auto *I : Record->decls()) {
4957     const auto *FD = dyn_cast<FieldDecl>(I);
4958     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4959       FD = IFD->getAnonField();
4960     if (FD && FD->hasInClassInitializer())
4961       return FD->getLocation();
4962   }
4963 
4964   llvm_unreachable("couldn't find in-class initializer");
4965 }
4966 
4967 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4968                                       SourceLocation DefaultInitLoc) {
4969   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4970     return;
4971 
4972   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4973   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4974 }
4975 
4976 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4977                                       CXXRecordDecl *AnonUnion) {
4978   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4979     return;
4980 
4981   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4982 }
4983 
4984 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4985 /// anonymous structure or union. Anonymous unions are a C++ feature
4986 /// (C++ [class.union]) and a C11 feature; anonymous structures
4987 /// are a C11 feature and GNU C++ extension.
4988 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4989                                         AccessSpecifier AS,
4990                                         RecordDecl *Record,
4991                                         const PrintingPolicy &Policy) {
4992   DeclContext *Owner = Record->getDeclContext();
4993 
4994   // Diagnose whether this anonymous struct/union is an extension.
4995   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4996     Diag(Record->getLocation(), diag::ext_anonymous_union);
4997   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4998     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4999   else if (!Record->isUnion() && !getLangOpts().C11)
5000     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5001 
5002   // C and C++ require different kinds of checks for anonymous
5003   // structs/unions.
5004   bool Invalid = false;
5005   if (getLangOpts().CPlusPlus) {
5006     const char *PrevSpec = nullptr;
5007     if (Record->isUnion()) {
5008       // C++ [class.union]p6:
5009       // C++17 [class.union.anon]p2:
5010       //   Anonymous unions declared in a named namespace or in the
5011       //   global namespace shall be declared static.
5012       unsigned DiagID;
5013       DeclContext *OwnerScope = Owner->getRedeclContext();
5014       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5015           (OwnerScope->isTranslationUnit() ||
5016            (OwnerScope->isNamespace() &&
5017             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5018         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5019           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5020 
5021         // Recover by adding 'static'.
5022         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5023                                PrevSpec, DiagID, Policy);
5024       }
5025       // C++ [class.union]p6:
5026       //   A storage class is not allowed in a declaration of an
5027       //   anonymous union in a class scope.
5028       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5029                isa<RecordDecl>(Owner)) {
5030         Diag(DS.getStorageClassSpecLoc(),
5031              diag::err_anonymous_union_with_storage_spec)
5032           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5033 
5034         // Recover by removing the storage specifier.
5035         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5036                                SourceLocation(),
5037                                PrevSpec, DiagID, Context.getPrintingPolicy());
5038       }
5039     }
5040 
5041     // Ignore const/volatile/restrict qualifiers.
5042     if (DS.getTypeQualifiers()) {
5043       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5044         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5045           << Record->isUnion() << "const"
5046           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5047       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5048         Diag(DS.getVolatileSpecLoc(),
5049              diag::ext_anonymous_struct_union_qualified)
5050           << Record->isUnion() << "volatile"
5051           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5052       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5053         Diag(DS.getRestrictSpecLoc(),
5054              diag::ext_anonymous_struct_union_qualified)
5055           << Record->isUnion() << "restrict"
5056           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5057       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5058         Diag(DS.getAtomicSpecLoc(),
5059              diag::ext_anonymous_struct_union_qualified)
5060           << Record->isUnion() << "_Atomic"
5061           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5062       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5063         Diag(DS.getUnalignedSpecLoc(),
5064              diag::ext_anonymous_struct_union_qualified)
5065           << Record->isUnion() << "__unaligned"
5066           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5067 
5068       DS.ClearTypeQualifiers();
5069     }
5070 
5071     // C++ [class.union]p2:
5072     //   The member-specification of an anonymous union shall only
5073     //   define non-static data members. [Note: nested types and
5074     //   functions cannot be declared within an anonymous union. ]
5075     for (auto *Mem : Record->decls()) {
5076       // Ignore invalid declarations; we already diagnosed them.
5077       if (Mem->isInvalidDecl())
5078         continue;
5079 
5080       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5081         // C++ [class.union]p3:
5082         //   An anonymous union shall not have private or protected
5083         //   members (clause 11).
5084         assert(FD->getAccess() != AS_none);
5085         if (FD->getAccess() != AS_public) {
5086           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5087             << Record->isUnion() << (FD->getAccess() == AS_protected);
5088           Invalid = true;
5089         }
5090 
5091         // C++ [class.union]p1
5092         //   An object of a class with a non-trivial constructor, a non-trivial
5093         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5094         //   assignment operator cannot be a member of a union, nor can an
5095         //   array of such objects.
5096         if (CheckNontrivialField(FD))
5097           Invalid = true;
5098       } else if (Mem->isImplicit()) {
5099         // Any implicit members are fine.
5100       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5101         // This is a type that showed up in an
5102         // elaborated-type-specifier inside the anonymous struct or
5103         // union, but which actually declares a type outside of the
5104         // anonymous struct or union. It's okay.
5105       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5106         if (!MemRecord->isAnonymousStructOrUnion() &&
5107             MemRecord->getDeclName()) {
5108           // Visual C++ allows type definition in anonymous struct or union.
5109           if (getLangOpts().MicrosoftExt)
5110             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5111               << Record->isUnion();
5112           else {
5113             // This is a nested type declaration.
5114             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5115               << Record->isUnion();
5116             Invalid = true;
5117           }
5118         } else {
5119           // This is an anonymous type definition within another anonymous type.
5120           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5121           // not part of standard C++.
5122           Diag(MemRecord->getLocation(),
5123                diag::ext_anonymous_record_with_anonymous_type)
5124             << Record->isUnion();
5125         }
5126       } else if (isa<AccessSpecDecl>(Mem)) {
5127         // Any access specifier is fine.
5128       } else if (isa<StaticAssertDecl>(Mem)) {
5129         // In C++1z, static_assert declarations are also fine.
5130       } else {
5131         // We have something that isn't a non-static data
5132         // member. Complain about it.
5133         unsigned DK = diag::err_anonymous_record_bad_member;
5134         if (isa<TypeDecl>(Mem))
5135           DK = diag::err_anonymous_record_with_type;
5136         else if (isa<FunctionDecl>(Mem))
5137           DK = diag::err_anonymous_record_with_function;
5138         else if (isa<VarDecl>(Mem))
5139           DK = diag::err_anonymous_record_with_static;
5140 
5141         // Visual C++ allows type definition in anonymous struct or union.
5142         if (getLangOpts().MicrosoftExt &&
5143             DK == diag::err_anonymous_record_with_type)
5144           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5145             << Record->isUnion();
5146         else {
5147           Diag(Mem->getLocation(), DK) << Record->isUnion();
5148           Invalid = true;
5149         }
5150       }
5151     }
5152 
5153     // C++11 [class.union]p8 (DR1460):
5154     //   At most one variant member of a union may have a
5155     //   brace-or-equal-initializer.
5156     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5157         Owner->isRecord())
5158       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5159                                 cast<CXXRecordDecl>(Record));
5160   }
5161 
5162   if (!Record->isUnion() && !Owner->isRecord()) {
5163     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5164       << getLangOpts().CPlusPlus;
5165     Invalid = true;
5166   }
5167 
5168   // C++ [dcl.dcl]p3:
5169   //   [If there are no declarators], and except for the declaration of an
5170   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5171   //   names into the program
5172   // C++ [class.mem]p2:
5173   //   each such member-declaration shall either declare at least one member
5174   //   name of the class or declare at least one unnamed bit-field
5175   //
5176   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5177   if (getLangOpts().CPlusPlus && Record->field_empty())
5178     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5179 
5180   // Mock up a declarator.
5181   Declarator Dc(DS, DeclaratorContext::Member);
5182   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5183   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5184 
5185   // Create a declaration for this anonymous struct/union.
5186   NamedDecl *Anon = nullptr;
5187   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5188     Anon = FieldDecl::Create(
5189         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5190         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5191         /*BitWidth=*/nullptr, /*Mutable=*/false,
5192         /*InitStyle=*/ICIS_NoInit);
5193     Anon->setAccess(AS);
5194     ProcessDeclAttributes(S, Anon, Dc);
5195 
5196     if (getLangOpts().CPlusPlus)
5197       FieldCollector->Add(cast<FieldDecl>(Anon));
5198   } else {
5199     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5200     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5201     if (SCSpec == DeclSpec::SCS_mutable) {
5202       // mutable can only appear on non-static class members, so it's always
5203       // an error here
5204       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5205       Invalid = true;
5206       SC = SC_None;
5207     }
5208 
5209     assert(DS.getAttributes().empty() && "No attribute expected");
5210     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5211                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5212                            Context.getTypeDeclType(Record), TInfo, SC);
5213 
5214     // Default-initialize the implicit variable. This initialization will be
5215     // trivial in almost all cases, except if a union member has an in-class
5216     // initializer:
5217     //   union { int n = 0; };
5218     if (!Invalid)
5219       ActOnUninitializedDecl(Anon);
5220   }
5221   Anon->setImplicit();
5222 
5223   // Mark this as an anonymous struct/union type.
5224   Record->setAnonymousStructOrUnion(true);
5225 
5226   // Add the anonymous struct/union object to the current
5227   // context. We'll be referencing this object when we refer to one of
5228   // its members.
5229   Owner->addDecl(Anon);
5230 
5231   // Inject the members of the anonymous struct/union into the owning
5232   // context and into the identifier resolver chain for name lookup
5233   // purposes.
5234   SmallVector<NamedDecl*, 2> Chain;
5235   Chain.push_back(Anon);
5236 
5237   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5238     Invalid = true;
5239 
5240   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5241     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5242       MangleNumberingContext *MCtx;
5243       Decl *ManglingContextDecl;
5244       std::tie(MCtx, ManglingContextDecl) =
5245           getCurrentMangleNumberContext(NewVD->getDeclContext());
5246       if (MCtx) {
5247         Context.setManglingNumber(
5248             NewVD, MCtx->getManglingNumber(
5249                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5250         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5251       }
5252     }
5253   }
5254 
5255   if (Invalid)
5256     Anon->setInvalidDecl();
5257 
5258   return Anon;
5259 }
5260 
5261 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5262 /// Microsoft C anonymous structure.
5263 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5264 /// Example:
5265 ///
5266 /// struct A { int a; };
5267 /// struct B { struct A; int b; };
5268 ///
5269 /// void foo() {
5270 ///   B var;
5271 ///   var.a = 3;
5272 /// }
5273 ///
5274 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5275                                            RecordDecl *Record) {
5276   assert(Record && "expected a record!");
5277 
5278   // Mock up a declarator.
5279   Declarator Dc(DS, DeclaratorContext::TypeName);
5280   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5281   assert(TInfo && "couldn't build declarator info for anonymous struct");
5282 
5283   auto *ParentDecl = cast<RecordDecl>(CurContext);
5284   QualType RecTy = Context.getTypeDeclType(Record);
5285 
5286   // Create a declaration for this anonymous struct.
5287   NamedDecl *Anon =
5288       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5289                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5290                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5291                         /*InitStyle=*/ICIS_NoInit);
5292   Anon->setImplicit();
5293 
5294   // Add the anonymous struct object to the current context.
5295   CurContext->addDecl(Anon);
5296 
5297   // Inject the members of the anonymous struct into the current
5298   // context and into the identifier resolver chain for name lookup
5299   // purposes.
5300   SmallVector<NamedDecl*, 2> Chain;
5301   Chain.push_back(Anon);
5302 
5303   RecordDecl *RecordDef = Record->getDefinition();
5304   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5305                                diag::err_field_incomplete_or_sizeless) ||
5306       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5307                                           AS_none, Chain)) {
5308     Anon->setInvalidDecl();
5309     ParentDecl->setInvalidDecl();
5310   }
5311 
5312   return Anon;
5313 }
5314 
5315 /// GetNameForDeclarator - Determine the full declaration name for the
5316 /// given Declarator.
5317 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5318   return GetNameFromUnqualifiedId(D.getName());
5319 }
5320 
5321 /// Retrieves the declaration name from a parsed unqualified-id.
5322 DeclarationNameInfo
5323 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5324   DeclarationNameInfo NameInfo;
5325   NameInfo.setLoc(Name.StartLocation);
5326 
5327   switch (Name.getKind()) {
5328 
5329   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5330   case UnqualifiedIdKind::IK_Identifier:
5331     NameInfo.setName(Name.Identifier);
5332     return NameInfo;
5333 
5334   case UnqualifiedIdKind::IK_DeductionGuideName: {
5335     // C++ [temp.deduct.guide]p3:
5336     //   The simple-template-id shall name a class template specialization.
5337     //   The template-name shall be the same identifier as the template-name
5338     //   of the simple-template-id.
5339     // These together intend to imply that the template-name shall name a
5340     // class template.
5341     // FIXME: template<typename T> struct X {};
5342     //        template<typename T> using Y = X<T>;
5343     //        Y(int) -> Y<int>;
5344     //   satisfies these rules but does not name a class template.
5345     TemplateName TN = Name.TemplateName.get().get();
5346     auto *Template = TN.getAsTemplateDecl();
5347     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5348       Diag(Name.StartLocation,
5349            diag::err_deduction_guide_name_not_class_template)
5350         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5351       if (Template)
5352         Diag(Template->getLocation(), diag::note_template_decl_here);
5353       return DeclarationNameInfo();
5354     }
5355 
5356     NameInfo.setName(
5357         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5358     return NameInfo;
5359   }
5360 
5361   case UnqualifiedIdKind::IK_OperatorFunctionId:
5362     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5363                                            Name.OperatorFunctionId.Operator));
5364     NameInfo.setCXXOperatorNameRange(SourceRange(
5365         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5366     return NameInfo;
5367 
5368   case UnqualifiedIdKind::IK_LiteralOperatorId:
5369     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5370                                                            Name.Identifier));
5371     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5372     return NameInfo;
5373 
5374   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5375     TypeSourceInfo *TInfo;
5376     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5377     if (Ty.isNull())
5378       return DeclarationNameInfo();
5379     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5380                                                Context.getCanonicalType(Ty)));
5381     NameInfo.setNamedTypeInfo(TInfo);
5382     return NameInfo;
5383   }
5384 
5385   case UnqualifiedIdKind::IK_ConstructorName: {
5386     TypeSourceInfo *TInfo;
5387     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5388     if (Ty.isNull())
5389       return DeclarationNameInfo();
5390     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5391                                               Context.getCanonicalType(Ty)));
5392     NameInfo.setNamedTypeInfo(TInfo);
5393     return NameInfo;
5394   }
5395 
5396   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5397     // In well-formed code, we can only have a constructor
5398     // template-id that refers to the current context, so go there
5399     // to find the actual type being constructed.
5400     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5401     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5402       return DeclarationNameInfo();
5403 
5404     // Determine the type of the class being constructed.
5405     QualType CurClassType = Context.getTypeDeclType(CurClass);
5406 
5407     // FIXME: Check two things: that the template-id names the same type as
5408     // CurClassType, and that the template-id does not occur when the name
5409     // was qualified.
5410 
5411     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5412                                     Context.getCanonicalType(CurClassType)));
5413     // FIXME: should we retrieve TypeSourceInfo?
5414     NameInfo.setNamedTypeInfo(nullptr);
5415     return NameInfo;
5416   }
5417 
5418   case UnqualifiedIdKind::IK_DestructorName: {
5419     TypeSourceInfo *TInfo;
5420     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5421     if (Ty.isNull())
5422       return DeclarationNameInfo();
5423     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5424                                               Context.getCanonicalType(Ty)));
5425     NameInfo.setNamedTypeInfo(TInfo);
5426     return NameInfo;
5427   }
5428 
5429   case UnqualifiedIdKind::IK_TemplateId: {
5430     TemplateName TName = Name.TemplateId->Template.get();
5431     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5432     return Context.getNameForTemplate(TName, TNameLoc);
5433   }
5434 
5435   } // switch (Name.getKind())
5436 
5437   llvm_unreachable("Unknown name kind");
5438 }
5439 
5440 static QualType getCoreType(QualType Ty) {
5441   do {
5442     if (Ty->isPointerType() || Ty->isReferenceType())
5443       Ty = Ty->getPointeeType();
5444     else if (Ty->isArrayType())
5445       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5446     else
5447       return Ty.withoutLocalFastQualifiers();
5448   } while (true);
5449 }
5450 
5451 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5452 /// and Definition have "nearly" matching parameters. This heuristic is
5453 /// used to improve diagnostics in the case where an out-of-line function
5454 /// definition doesn't match any declaration within the class or namespace.
5455 /// Also sets Params to the list of indices to the parameters that differ
5456 /// between the declaration and the definition. If hasSimilarParameters
5457 /// returns true and Params is empty, then all of the parameters match.
5458 static bool hasSimilarParameters(ASTContext &Context,
5459                                      FunctionDecl *Declaration,
5460                                      FunctionDecl *Definition,
5461                                      SmallVectorImpl<unsigned> &Params) {
5462   Params.clear();
5463   if (Declaration->param_size() != Definition->param_size())
5464     return false;
5465   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5466     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5467     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5468 
5469     // The parameter types are identical
5470     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5471       continue;
5472 
5473     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5474     QualType DefParamBaseTy = getCoreType(DefParamTy);
5475     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5476     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5477 
5478     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5479         (DeclTyName && DeclTyName == DefTyName))
5480       Params.push_back(Idx);
5481     else  // The two parameters aren't even close
5482       return false;
5483   }
5484 
5485   return true;
5486 }
5487 
5488 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5489 /// declarator needs to be rebuilt in the current instantiation.
5490 /// Any bits of declarator which appear before the name are valid for
5491 /// consideration here.  That's specifically the type in the decl spec
5492 /// and the base type in any member-pointer chunks.
5493 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5494                                                     DeclarationName Name) {
5495   // The types we specifically need to rebuild are:
5496   //   - typenames, typeofs, and decltypes
5497   //   - types which will become injected class names
5498   // Of course, we also need to rebuild any type referencing such a
5499   // type.  It's safest to just say "dependent", but we call out a
5500   // few cases here.
5501 
5502   DeclSpec &DS = D.getMutableDeclSpec();
5503   switch (DS.getTypeSpecType()) {
5504   case DeclSpec::TST_typename:
5505   case DeclSpec::TST_typeofType:
5506   case DeclSpec::TST_underlyingType:
5507   case DeclSpec::TST_atomic: {
5508     // Grab the type from the parser.
5509     TypeSourceInfo *TSI = nullptr;
5510     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5511     if (T.isNull() || !T->isInstantiationDependentType()) break;
5512 
5513     // Make sure there's a type source info.  This isn't really much
5514     // of a waste; most dependent types should have type source info
5515     // attached already.
5516     if (!TSI)
5517       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5518 
5519     // Rebuild the type in the current instantiation.
5520     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5521     if (!TSI) return true;
5522 
5523     // Store the new type back in the decl spec.
5524     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5525     DS.UpdateTypeRep(LocType);
5526     break;
5527   }
5528 
5529   case DeclSpec::TST_decltype:
5530   case DeclSpec::TST_typeofExpr: {
5531     Expr *E = DS.getRepAsExpr();
5532     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5533     if (Result.isInvalid()) return true;
5534     DS.UpdateExprRep(Result.get());
5535     break;
5536   }
5537 
5538   default:
5539     // Nothing to do for these decl specs.
5540     break;
5541   }
5542 
5543   // It doesn't matter what order we do this in.
5544   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5545     DeclaratorChunk &Chunk = D.getTypeObject(I);
5546 
5547     // The only type information in the declarator which can come
5548     // before the declaration name is the base type of a member
5549     // pointer.
5550     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5551       continue;
5552 
5553     // Rebuild the scope specifier in-place.
5554     CXXScopeSpec &SS = Chunk.Mem.Scope();
5555     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5556       return true;
5557   }
5558 
5559   return false;
5560 }
5561 
5562 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5563   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5564   // of system decl.
5565   if (D->getPreviousDecl() || D->isImplicit())
5566     return;
5567   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5568   if (Status != ReservedIdentifierStatus::NotReserved &&
5569       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5570     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5571         << D << static_cast<int>(Status);
5572 }
5573 
5574 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5575   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5576   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5577 
5578   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5579       Dcl && Dcl->getDeclContext()->isFileContext())
5580     Dcl->setTopLevelDeclInObjCContainer();
5581 
5582   if (getLangOpts().OpenCL)
5583     setCurrentOpenCLExtensionForDecl(Dcl);
5584 
5585   return Dcl;
5586 }
5587 
5588 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5589 ///   If T is the name of a class, then each of the following shall have a
5590 ///   name different from T:
5591 ///     - every static data member of class T;
5592 ///     - every member function of class T
5593 ///     - every member of class T that is itself a type;
5594 /// \returns true if the declaration name violates these rules.
5595 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5596                                    DeclarationNameInfo NameInfo) {
5597   DeclarationName Name = NameInfo.getName();
5598 
5599   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5600   while (Record && Record->isAnonymousStructOrUnion())
5601     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5602   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5603     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5604     return true;
5605   }
5606 
5607   return false;
5608 }
5609 
5610 /// Diagnose a declaration whose declarator-id has the given
5611 /// nested-name-specifier.
5612 ///
5613 /// \param SS The nested-name-specifier of the declarator-id.
5614 ///
5615 /// \param DC The declaration context to which the nested-name-specifier
5616 /// resolves.
5617 ///
5618 /// \param Name The name of the entity being declared.
5619 ///
5620 /// \param Loc The location of the name of the entity being declared.
5621 ///
5622 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5623 /// we're declaring an explicit / partial specialization / instantiation.
5624 ///
5625 /// \returns true if we cannot safely recover from this error, false otherwise.
5626 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5627                                         DeclarationName Name,
5628                                         SourceLocation Loc, bool IsTemplateId) {
5629   DeclContext *Cur = CurContext;
5630   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5631     Cur = Cur->getParent();
5632 
5633   // If the user provided a superfluous scope specifier that refers back to the
5634   // class in which the entity is already declared, diagnose and ignore it.
5635   //
5636   // class X {
5637   //   void X::f();
5638   // };
5639   //
5640   // Note, it was once ill-formed to give redundant qualification in all
5641   // contexts, but that rule was removed by DR482.
5642   if (Cur->Equals(DC)) {
5643     if (Cur->isRecord()) {
5644       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5645                                       : diag::err_member_extra_qualification)
5646         << Name << FixItHint::CreateRemoval(SS.getRange());
5647       SS.clear();
5648     } else {
5649       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5650     }
5651     return false;
5652   }
5653 
5654   // Check whether the qualifying scope encloses the scope of the original
5655   // declaration. For a template-id, we perform the checks in
5656   // CheckTemplateSpecializationScope.
5657   if (!Cur->Encloses(DC) && !IsTemplateId) {
5658     if (Cur->isRecord())
5659       Diag(Loc, diag::err_member_qualification)
5660         << Name << SS.getRange();
5661     else if (isa<TranslationUnitDecl>(DC))
5662       Diag(Loc, diag::err_invalid_declarator_global_scope)
5663         << Name << SS.getRange();
5664     else if (isa<FunctionDecl>(Cur))
5665       Diag(Loc, diag::err_invalid_declarator_in_function)
5666         << Name << SS.getRange();
5667     else if (isa<BlockDecl>(Cur))
5668       Diag(Loc, diag::err_invalid_declarator_in_block)
5669         << Name << SS.getRange();
5670     else
5671       Diag(Loc, diag::err_invalid_declarator_scope)
5672       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5673 
5674     return true;
5675   }
5676 
5677   if (Cur->isRecord()) {
5678     // Cannot qualify members within a class.
5679     Diag(Loc, diag::err_member_qualification)
5680       << Name << SS.getRange();
5681     SS.clear();
5682 
5683     // C++ constructors and destructors with incorrect scopes can break
5684     // our AST invariants by having the wrong underlying types. If
5685     // that's the case, then drop this declaration entirely.
5686     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5687          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5688         !Context.hasSameType(Name.getCXXNameType(),
5689                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5690       return true;
5691 
5692     return false;
5693   }
5694 
5695   // C++11 [dcl.meaning]p1:
5696   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5697   //   not begin with a decltype-specifer"
5698   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5699   while (SpecLoc.getPrefix())
5700     SpecLoc = SpecLoc.getPrefix();
5701   if (dyn_cast_or_null<DecltypeType>(
5702         SpecLoc.getNestedNameSpecifier()->getAsType()))
5703     Diag(Loc, diag::err_decltype_in_declarator)
5704       << SpecLoc.getTypeLoc().getSourceRange();
5705 
5706   return false;
5707 }
5708 
5709 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5710                                   MultiTemplateParamsArg TemplateParamLists) {
5711   // TODO: consider using NameInfo for diagnostic.
5712   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5713   DeclarationName Name = NameInfo.getName();
5714 
5715   // All of these full declarators require an identifier.  If it doesn't have
5716   // one, the ParsedFreeStandingDeclSpec action should be used.
5717   if (D.isDecompositionDeclarator()) {
5718     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5719   } else if (!Name) {
5720     if (!D.isInvalidType())  // Reject this if we think it is valid.
5721       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5722           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5723     return nullptr;
5724   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5725     return nullptr;
5726 
5727   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5728   // we find one that is.
5729   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5730          (S->getFlags() & Scope::TemplateParamScope) != 0)
5731     S = S->getParent();
5732 
5733   DeclContext *DC = CurContext;
5734   if (D.getCXXScopeSpec().isInvalid())
5735     D.setInvalidType();
5736   else if (D.getCXXScopeSpec().isSet()) {
5737     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5738                                         UPPC_DeclarationQualifier))
5739       return nullptr;
5740 
5741     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5742     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5743     if (!DC || isa<EnumDecl>(DC)) {
5744       // If we could not compute the declaration context, it's because the
5745       // declaration context is dependent but does not refer to a class,
5746       // class template, or class template partial specialization. Complain
5747       // and return early, to avoid the coming semantic disaster.
5748       Diag(D.getIdentifierLoc(),
5749            diag::err_template_qualified_declarator_no_match)
5750         << D.getCXXScopeSpec().getScopeRep()
5751         << D.getCXXScopeSpec().getRange();
5752       return nullptr;
5753     }
5754     bool IsDependentContext = DC->isDependentContext();
5755 
5756     if (!IsDependentContext &&
5757         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5758       return nullptr;
5759 
5760     // If a class is incomplete, do not parse entities inside it.
5761     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5762       Diag(D.getIdentifierLoc(),
5763            diag::err_member_def_undefined_record)
5764         << Name << DC << D.getCXXScopeSpec().getRange();
5765       return nullptr;
5766     }
5767     if (!D.getDeclSpec().isFriendSpecified()) {
5768       if (diagnoseQualifiedDeclaration(
5769               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5770               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5771         if (DC->isRecord())
5772           return nullptr;
5773 
5774         D.setInvalidType();
5775       }
5776     }
5777 
5778     // Check whether we need to rebuild the type of the given
5779     // declaration in the current instantiation.
5780     if (EnteringContext && IsDependentContext &&
5781         TemplateParamLists.size() != 0) {
5782       ContextRAII SavedContext(*this, DC);
5783       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5784         D.setInvalidType();
5785     }
5786   }
5787 
5788   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5789   QualType R = TInfo->getType();
5790 
5791   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5792                                       UPPC_DeclarationType))
5793     D.setInvalidType();
5794 
5795   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5796                         forRedeclarationInCurContext());
5797 
5798   // See if this is a redefinition of a variable in the same scope.
5799   if (!D.getCXXScopeSpec().isSet()) {
5800     bool IsLinkageLookup = false;
5801     bool CreateBuiltins = false;
5802 
5803     // If the declaration we're planning to build will be a function
5804     // or object with linkage, then look for another declaration with
5805     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5806     //
5807     // If the declaration we're planning to build will be declared with
5808     // external linkage in the translation unit, create any builtin with
5809     // the same name.
5810     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5811       /* Do nothing*/;
5812     else if (CurContext->isFunctionOrMethod() &&
5813              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5814               R->isFunctionType())) {
5815       IsLinkageLookup = true;
5816       CreateBuiltins =
5817           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5818     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5819                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5820       CreateBuiltins = true;
5821 
5822     if (IsLinkageLookup) {
5823       Previous.clear(LookupRedeclarationWithLinkage);
5824       Previous.setRedeclarationKind(ForExternalRedeclaration);
5825     }
5826 
5827     LookupName(Previous, S, CreateBuiltins);
5828   } else { // Something like "int foo::x;"
5829     LookupQualifiedName(Previous, DC);
5830 
5831     // C++ [dcl.meaning]p1:
5832     //   When the declarator-id is qualified, the declaration shall refer to a
5833     //  previously declared member of the class or namespace to which the
5834     //  qualifier refers (or, in the case of a namespace, of an element of the
5835     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5836     //  thereof; [...]
5837     //
5838     // Note that we already checked the context above, and that we do not have
5839     // enough information to make sure that Previous contains the declaration
5840     // we want to match. For example, given:
5841     //
5842     //   class X {
5843     //     void f();
5844     //     void f(float);
5845     //   };
5846     //
5847     //   void X::f(int) { } // ill-formed
5848     //
5849     // In this case, Previous will point to the overload set
5850     // containing the two f's declared in X, but neither of them
5851     // matches.
5852 
5853     // C++ [dcl.meaning]p1:
5854     //   [...] the member shall not merely have been introduced by a
5855     //   using-declaration in the scope of the class or namespace nominated by
5856     //   the nested-name-specifier of the declarator-id.
5857     RemoveUsingDecls(Previous);
5858   }
5859 
5860   if (Previous.isSingleResult() &&
5861       Previous.getFoundDecl()->isTemplateParameter()) {
5862     // Maybe we will complain about the shadowed template parameter.
5863     if (!D.isInvalidType())
5864       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5865                                       Previous.getFoundDecl());
5866 
5867     // Just pretend that we didn't see the previous declaration.
5868     Previous.clear();
5869   }
5870 
5871   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5872     // Forget that the previous declaration is the injected-class-name.
5873     Previous.clear();
5874 
5875   // In C++, the previous declaration we find might be a tag type
5876   // (class or enum). In this case, the new declaration will hide the
5877   // tag type. Note that this applies to functions, function templates, and
5878   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5879   if (Previous.isSingleTagDecl() &&
5880       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5881       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5882     Previous.clear();
5883 
5884   // Check that there are no default arguments other than in the parameters
5885   // of a function declaration (C++ only).
5886   if (getLangOpts().CPlusPlus)
5887     CheckExtraCXXDefaultArguments(D);
5888 
5889   NamedDecl *New;
5890 
5891   bool AddToScope = true;
5892   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5893     if (TemplateParamLists.size()) {
5894       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5895       return nullptr;
5896     }
5897 
5898     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5899   } else if (R->isFunctionType()) {
5900     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5901                                   TemplateParamLists,
5902                                   AddToScope);
5903   } else {
5904     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5905                                   AddToScope);
5906   }
5907 
5908   if (!New)
5909     return nullptr;
5910 
5911   // If this has an identifier and is not a function template specialization,
5912   // add it to the scope stack.
5913   if (New->getDeclName() && AddToScope)
5914     PushOnScopeChains(New, S);
5915 
5916   if (isInOpenMPDeclareTargetContext())
5917     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5918 
5919   return New;
5920 }
5921 
5922 /// Helper method to turn variable array types into constant array
5923 /// types in certain situations which would otherwise be errors (for
5924 /// GCC compatibility).
5925 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5926                                                     ASTContext &Context,
5927                                                     bool &SizeIsNegative,
5928                                                     llvm::APSInt &Oversized) {
5929   // This method tries to turn a variable array into a constant
5930   // array even when the size isn't an ICE.  This is necessary
5931   // for compatibility with code that depends on gcc's buggy
5932   // constant expression folding, like struct {char x[(int)(char*)2];}
5933   SizeIsNegative = false;
5934   Oversized = 0;
5935 
5936   if (T->isDependentType())
5937     return QualType();
5938 
5939   QualifierCollector Qs;
5940   const Type *Ty = Qs.strip(T);
5941 
5942   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5943     QualType Pointee = PTy->getPointeeType();
5944     QualType FixedType =
5945         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5946                                             Oversized);
5947     if (FixedType.isNull()) return FixedType;
5948     FixedType = Context.getPointerType(FixedType);
5949     return Qs.apply(Context, FixedType);
5950   }
5951   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5952     QualType Inner = PTy->getInnerType();
5953     QualType FixedType =
5954         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5955                                             Oversized);
5956     if (FixedType.isNull()) return FixedType;
5957     FixedType = Context.getParenType(FixedType);
5958     return Qs.apply(Context, FixedType);
5959   }
5960 
5961   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5962   if (!VLATy)
5963     return QualType();
5964 
5965   QualType ElemTy = VLATy->getElementType();
5966   if (ElemTy->isVariablyModifiedType()) {
5967     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5968                                                  SizeIsNegative, Oversized);
5969     if (ElemTy.isNull())
5970       return QualType();
5971   }
5972 
5973   Expr::EvalResult Result;
5974   if (!VLATy->getSizeExpr() ||
5975       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5976     return QualType();
5977 
5978   llvm::APSInt Res = Result.Val.getInt();
5979 
5980   // Check whether the array size is negative.
5981   if (Res.isSigned() && Res.isNegative()) {
5982     SizeIsNegative = true;
5983     return QualType();
5984   }
5985 
5986   // Check whether the array is too large to be addressed.
5987   unsigned ActiveSizeBits =
5988       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5989        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5990           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5991           : Res.getActiveBits();
5992   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5993     Oversized = Res;
5994     return QualType();
5995   }
5996 
5997   QualType FoldedArrayType = Context.getConstantArrayType(
5998       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5999   return Qs.apply(Context, FoldedArrayType);
6000 }
6001 
6002 static void
6003 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6004   SrcTL = SrcTL.getUnqualifiedLoc();
6005   DstTL = DstTL.getUnqualifiedLoc();
6006   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6007     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6008     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6009                                       DstPTL.getPointeeLoc());
6010     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6011     return;
6012   }
6013   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6014     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6015     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6016                                       DstPTL.getInnerLoc());
6017     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6018     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6019     return;
6020   }
6021   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6022   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6023   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6024   TypeLoc DstElemTL = DstATL.getElementLoc();
6025   if (VariableArrayTypeLoc SrcElemATL =
6026           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6027     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6028     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6029   } else {
6030     DstElemTL.initializeFullCopy(SrcElemTL);
6031   }
6032   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6033   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6034   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6035 }
6036 
6037 /// Helper method to turn variable array types into constant array
6038 /// types in certain situations which would otherwise be errors (for
6039 /// GCC compatibility).
6040 static TypeSourceInfo*
6041 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6042                                               ASTContext &Context,
6043                                               bool &SizeIsNegative,
6044                                               llvm::APSInt &Oversized) {
6045   QualType FixedTy
6046     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6047                                           SizeIsNegative, Oversized);
6048   if (FixedTy.isNull())
6049     return nullptr;
6050   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6051   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6052                                     FixedTInfo->getTypeLoc());
6053   return FixedTInfo;
6054 }
6055 
6056 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6057 /// true if we were successful.
6058 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6059                                            QualType &T, SourceLocation Loc,
6060                                            unsigned FailedFoldDiagID) {
6061   bool SizeIsNegative;
6062   llvm::APSInt Oversized;
6063   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6064       TInfo, Context, SizeIsNegative, Oversized);
6065   if (FixedTInfo) {
6066     Diag(Loc, diag::ext_vla_folded_to_constant);
6067     TInfo = FixedTInfo;
6068     T = FixedTInfo->getType();
6069     return true;
6070   }
6071 
6072   if (SizeIsNegative)
6073     Diag(Loc, diag::err_typecheck_negative_array_size);
6074   else if (Oversized.getBoolValue())
6075     Diag(Loc, diag::err_array_too_large) << Oversized.toString(10);
6076   else if (FailedFoldDiagID)
6077     Diag(Loc, FailedFoldDiagID);
6078   return false;
6079 }
6080 
6081 /// Register the given locally-scoped extern "C" declaration so
6082 /// that it can be found later for redeclarations. We include any extern "C"
6083 /// declaration that is not visible in the translation unit here, not just
6084 /// function-scope declarations.
6085 void
6086 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6087   if (!getLangOpts().CPlusPlus &&
6088       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6089     // Don't need to track declarations in the TU in C.
6090     return;
6091 
6092   // Note that we have a locally-scoped external with this name.
6093   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6094 }
6095 
6096 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6097   // FIXME: We can have multiple results via __attribute__((overloadable)).
6098   auto Result = Context.getExternCContextDecl()->lookup(Name);
6099   return Result.empty() ? nullptr : *Result.begin();
6100 }
6101 
6102 /// Diagnose function specifiers on a declaration of an identifier that
6103 /// does not identify a function.
6104 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6105   // FIXME: We should probably indicate the identifier in question to avoid
6106   // confusion for constructs like "virtual int a(), b;"
6107   if (DS.isVirtualSpecified())
6108     Diag(DS.getVirtualSpecLoc(),
6109          diag::err_virtual_non_function);
6110 
6111   if (DS.hasExplicitSpecifier())
6112     Diag(DS.getExplicitSpecLoc(),
6113          diag::err_explicit_non_function);
6114 
6115   if (DS.isNoreturnSpecified())
6116     Diag(DS.getNoreturnSpecLoc(),
6117          diag::err_noreturn_non_function);
6118 }
6119 
6120 NamedDecl*
6121 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6122                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6123   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6124   if (D.getCXXScopeSpec().isSet()) {
6125     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6126       << D.getCXXScopeSpec().getRange();
6127     D.setInvalidType();
6128     // Pretend we didn't see the scope specifier.
6129     DC = CurContext;
6130     Previous.clear();
6131   }
6132 
6133   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6134 
6135   if (D.getDeclSpec().isInlineSpecified())
6136     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6137         << getLangOpts().CPlusPlus17;
6138   if (D.getDeclSpec().hasConstexprSpecifier())
6139     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6140         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6141 
6142   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6143     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6144       Diag(D.getName().StartLocation,
6145            diag::err_deduction_guide_invalid_specifier)
6146           << "typedef";
6147     else
6148       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6149           << D.getName().getSourceRange();
6150     return nullptr;
6151   }
6152 
6153   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6154   if (!NewTD) return nullptr;
6155 
6156   // Handle attributes prior to checking for duplicates in MergeVarDecl
6157   ProcessDeclAttributes(S, NewTD, D);
6158 
6159   CheckTypedefForVariablyModifiedType(S, NewTD);
6160 
6161   bool Redeclaration = D.isRedeclaration();
6162   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6163   D.setRedeclaration(Redeclaration);
6164   return ND;
6165 }
6166 
6167 void
6168 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6169   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6170   // then it shall have block scope.
6171   // Note that variably modified types must be fixed before merging the decl so
6172   // that redeclarations will match.
6173   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6174   QualType T = TInfo->getType();
6175   if (T->isVariablyModifiedType()) {
6176     setFunctionHasBranchProtectedScope();
6177 
6178     if (S->getFnParent() == nullptr) {
6179       bool SizeIsNegative;
6180       llvm::APSInt Oversized;
6181       TypeSourceInfo *FixedTInfo =
6182         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6183                                                       SizeIsNegative,
6184                                                       Oversized);
6185       if (FixedTInfo) {
6186         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6187         NewTD->setTypeSourceInfo(FixedTInfo);
6188       } else {
6189         if (SizeIsNegative)
6190           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6191         else if (T->isVariableArrayType())
6192           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6193         else if (Oversized.getBoolValue())
6194           Diag(NewTD->getLocation(), diag::err_array_too_large)
6195             << Oversized.toString(10);
6196         else
6197           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6198         NewTD->setInvalidDecl();
6199       }
6200     }
6201   }
6202 }
6203 
6204 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6205 /// declares a typedef-name, either using the 'typedef' type specifier or via
6206 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6207 NamedDecl*
6208 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6209                            LookupResult &Previous, bool &Redeclaration) {
6210 
6211   // Find the shadowed declaration before filtering for scope.
6212   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6213 
6214   // Merge the decl with the existing one if appropriate. If the decl is
6215   // in an outer scope, it isn't the same thing.
6216   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6217                        /*AllowInlineNamespace*/false);
6218   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6219   if (!Previous.empty()) {
6220     Redeclaration = true;
6221     MergeTypedefNameDecl(S, NewTD, Previous);
6222   } else {
6223     inferGslPointerAttribute(NewTD);
6224   }
6225 
6226   if (ShadowedDecl && !Redeclaration)
6227     CheckShadow(NewTD, ShadowedDecl, Previous);
6228 
6229   // If this is the C FILE type, notify the AST context.
6230   if (IdentifierInfo *II = NewTD->getIdentifier())
6231     if (!NewTD->isInvalidDecl() &&
6232         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6233       if (II->isStr("FILE"))
6234         Context.setFILEDecl(NewTD);
6235       else if (II->isStr("jmp_buf"))
6236         Context.setjmp_bufDecl(NewTD);
6237       else if (II->isStr("sigjmp_buf"))
6238         Context.setsigjmp_bufDecl(NewTD);
6239       else if (II->isStr("ucontext_t"))
6240         Context.setucontext_tDecl(NewTD);
6241     }
6242 
6243   return NewTD;
6244 }
6245 
6246 /// Determines whether the given declaration is an out-of-scope
6247 /// previous declaration.
6248 ///
6249 /// This routine should be invoked when name lookup has found a
6250 /// previous declaration (PrevDecl) that is not in the scope where a
6251 /// new declaration by the same name is being introduced. If the new
6252 /// declaration occurs in a local scope, previous declarations with
6253 /// linkage may still be considered previous declarations (C99
6254 /// 6.2.2p4-5, C++ [basic.link]p6).
6255 ///
6256 /// \param PrevDecl the previous declaration found by name
6257 /// lookup
6258 ///
6259 /// \param DC the context in which the new declaration is being
6260 /// declared.
6261 ///
6262 /// \returns true if PrevDecl is an out-of-scope previous declaration
6263 /// for a new delcaration with the same name.
6264 static bool
6265 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6266                                 ASTContext &Context) {
6267   if (!PrevDecl)
6268     return false;
6269 
6270   if (!PrevDecl->hasLinkage())
6271     return false;
6272 
6273   if (Context.getLangOpts().CPlusPlus) {
6274     // C++ [basic.link]p6:
6275     //   If there is a visible declaration of an entity with linkage
6276     //   having the same name and type, ignoring entities declared
6277     //   outside the innermost enclosing namespace scope, the block
6278     //   scope declaration declares that same entity and receives the
6279     //   linkage of the previous declaration.
6280     DeclContext *OuterContext = DC->getRedeclContext();
6281     if (!OuterContext->isFunctionOrMethod())
6282       // This rule only applies to block-scope declarations.
6283       return false;
6284 
6285     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6286     if (PrevOuterContext->isRecord())
6287       // We found a member function: ignore it.
6288       return false;
6289 
6290     // Find the innermost enclosing namespace for the new and
6291     // previous declarations.
6292     OuterContext = OuterContext->getEnclosingNamespaceContext();
6293     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6294 
6295     // The previous declaration is in a different namespace, so it
6296     // isn't the same function.
6297     if (!OuterContext->Equals(PrevOuterContext))
6298       return false;
6299   }
6300 
6301   return true;
6302 }
6303 
6304 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6305   CXXScopeSpec &SS = D.getCXXScopeSpec();
6306   if (!SS.isSet()) return;
6307   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6308 }
6309 
6310 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6311   QualType type = decl->getType();
6312   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6313   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6314     // Various kinds of declaration aren't allowed to be __autoreleasing.
6315     unsigned kind = -1U;
6316     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6317       if (var->hasAttr<BlocksAttr>())
6318         kind = 0; // __block
6319       else if (!var->hasLocalStorage())
6320         kind = 1; // global
6321     } else if (isa<ObjCIvarDecl>(decl)) {
6322       kind = 3; // ivar
6323     } else if (isa<FieldDecl>(decl)) {
6324       kind = 2; // field
6325     }
6326 
6327     if (kind != -1U) {
6328       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6329         << kind;
6330     }
6331   } else if (lifetime == Qualifiers::OCL_None) {
6332     // Try to infer lifetime.
6333     if (!type->isObjCLifetimeType())
6334       return false;
6335 
6336     lifetime = type->getObjCARCImplicitLifetime();
6337     type = Context.getLifetimeQualifiedType(type, lifetime);
6338     decl->setType(type);
6339   }
6340 
6341   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6342     // Thread-local variables cannot have lifetime.
6343     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6344         var->getTLSKind()) {
6345       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6346         << var->getType();
6347       return true;
6348     }
6349   }
6350 
6351   return false;
6352 }
6353 
6354 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6355   if (Decl->getType().hasAddressSpace())
6356     return;
6357   if (Decl->getType()->isDependentType())
6358     return;
6359   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6360     QualType Type = Var->getType();
6361     if (Type->isSamplerT() || Type->isVoidType())
6362       return;
6363     LangAS ImplAS = LangAS::opencl_private;
6364     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6365         Var->hasGlobalStorage())
6366       ImplAS = LangAS::opencl_global;
6367     // If the original type from a decayed type is an array type and that array
6368     // type has no address space yet, deduce it now.
6369     if (auto DT = dyn_cast<DecayedType>(Type)) {
6370       auto OrigTy = DT->getOriginalType();
6371       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6372         // Add the address space to the original array type and then propagate
6373         // that to the element type through `getAsArrayType`.
6374         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6375         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6376         // Re-generate the decayed type.
6377         Type = Context.getDecayedType(OrigTy);
6378       }
6379     }
6380     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6381     // Apply any qualifiers (including address space) from the array type to
6382     // the element type. This implements C99 6.7.3p8: "If the specification of
6383     // an array type includes any type qualifiers, the element type is so
6384     // qualified, not the array type."
6385     if (Type->isArrayType())
6386       Type = QualType(Context.getAsArrayType(Type), 0);
6387     Decl->setType(Type);
6388   }
6389 }
6390 
6391 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6392   // Ensure that an auto decl is deduced otherwise the checks below might cache
6393   // the wrong linkage.
6394   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6395 
6396   // 'weak' only applies to declarations with external linkage.
6397   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6398     if (!ND.isExternallyVisible()) {
6399       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6400       ND.dropAttr<WeakAttr>();
6401     }
6402   }
6403   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6404     if (ND.isExternallyVisible()) {
6405       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6406       ND.dropAttr<WeakRefAttr>();
6407       ND.dropAttr<AliasAttr>();
6408     }
6409   }
6410 
6411   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6412     if (VD->hasInit()) {
6413       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6414         assert(VD->isThisDeclarationADefinition() &&
6415                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6416         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6417         VD->dropAttr<AliasAttr>();
6418       }
6419     }
6420   }
6421 
6422   // 'selectany' only applies to externally visible variable declarations.
6423   // It does not apply to functions.
6424   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6425     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6426       S.Diag(Attr->getLocation(),
6427              diag::err_attribute_selectany_non_extern_data);
6428       ND.dropAttr<SelectAnyAttr>();
6429     }
6430   }
6431 
6432   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6433     auto *VD = dyn_cast<VarDecl>(&ND);
6434     bool IsAnonymousNS = false;
6435     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6436     if (VD) {
6437       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6438       while (NS && !IsAnonymousNS) {
6439         IsAnonymousNS = NS->isAnonymousNamespace();
6440         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6441       }
6442     }
6443     // dll attributes require external linkage. Static locals may have external
6444     // linkage but still cannot be explicitly imported or exported.
6445     // In Microsoft mode, a variable defined in anonymous namespace must have
6446     // external linkage in order to be exported.
6447     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6448     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6449         (!AnonNSInMicrosoftMode &&
6450          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6451       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6452         << &ND << Attr;
6453       ND.setInvalidDecl();
6454     }
6455   }
6456 
6457   // Check the attributes on the function type, if any.
6458   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6459     // Don't declare this variable in the second operand of the for-statement;
6460     // GCC miscompiles that by ending its lifetime before evaluating the
6461     // third operand. See gcc.gnu.org/PR86769.
6462     AttributedTypeLoc ATL;
6463     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6464          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6465          TL = ATL.getModifiedLoc()) {
6466       // The [[lifetimebound]] attribute can be applied to the implicit object
6467       // parameter of a non-static member function (other than a ctor or dtor)
6468       // by applying it to the function type.
6469       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6470         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6471         if (!MD || MD->isStatic()) {
6472           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6473               << !MD << A->getRange();
6474         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6475           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6476               << isa<CXXDestructorDecl>(MD) << A->getRange();
6477         }
6478       }
6479     }
6480   }
6481 }
6482 
6483 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6484                                            NamedDecl *NewDecl,
6485                                            bool IsSpecialization,
6486                                            bool IsDefinition) {
6487   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6488     return;
6489 
6490   bool IsTemplate = false;
6491   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6492     OldDecl = OldTD->getTemplatedDecl();
6493     IsTemplate = true;
6494     if (!IsSpecialization)
6495       IsDefinition = false;
6496   }
6497   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6498     NewDecl = NewTD->getTemplatedDecl();
6499     IsTemplate = true;
6500   }
6501 
6502   if (!OldDecl || !NewDecl)
6503     return;
6504 
6505   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6506   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6507   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6508   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6509 
6510   // dllimport and dllexport are inheritable attributes so we have to exclude
6511   // inherited attribute instances.
6512   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6513                     (NewExportAttr && !NewExportAttr->isInherited());
6514 
6515   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6516   // the only exception being explicit specializations.
6517   // Implicitly generated declarations are also excluded for now because there
6518   // is no other way to switch these to use dllimport or dllexport.
6519   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6520 
6521   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6522     // Allow with a warning for free functions and global variables.
6523     bool JustWarn = false;
6524     if (!OldDecl->isCXXClassMember()) {
6525       auto *VD = dyn_cast<VarDecl>(OldDecl);
6526       if (VD && !VD->getDescribedVarTemplate())
6527         JustWarn = true;
6528       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6529       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6530         JustWarn = true;
6531     }
6532 
6533     // We cannot change a declaration that's been used because IR has already
6534     // been emitted. Dllimported functions will still work though (modulo
6535     // address equality) as they can use the thunk.
6536     if (OldDecl->isUsed())
6537       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6538         JustWarn = false;
6539 
6540     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6541                                : diag::err_attribute_dll_redeclaration;
6542     S.Diag(NewDecl->getLocation(), DiagID)
6543         << NewDecl
6544         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6545     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6546     if (!JustWarn) {
6547       NewDecl->setInvalidDecl();
6548       return;
6549     }
6550   }
6551 
6552   // A redeclaration is not allowed to drop a dllimport attribute, the only
6553   // exceptions being inline function definitions (except for function
6554   // templates), local extern declarations, qualified friend declarations or
6555   // special MSVC extension: in the last case, the declaration is treated as if
6556   // it were marked dllexport.
6557   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6558   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6559   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6560     // Ignore static data because out-of-line definitions are diagnosed
6561     // separately.
6562     IsStaticDataMember = VD->isStaticDataMember();
6563     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6564                    VarDecl::DeclarationOnly;
6565   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6566     IsInline = FD->isInlined();
6567     IsQualifiedFriend = FD->getQualifier() &&
6568                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6569   }
6570 
6571   if (OldImportAttr && !HasNewAttr &&
6572       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6573       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6574     if (IsMicrosoftABI && IsDefinition) {
6575       S.Diag(NewDecl->getLocation(),
6576              diag::warn_redeclaration_without_import_attribute)
6577           << NewDecl;
6578       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6579       NewDecl->dropAttr<DLLImportAttr>();
6580       NewDecl->addAttr(
6581           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6582     } else {
6583       S.Diag(NewDecl->getLocation(),
6584              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6585           << NewDecl << OldImportAttr;
6586       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6587       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6588       OldDecl->dropAttr<DLLImportAttr>();
6589       NewDecl->dropAttr<DLLImportAttr>();
6590     }
6591   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6592     // In MinGW, seeing a function declared inline drops the dllimport
6593     // attribute.
6594     OldDecl->dropAttr<DLLImportAttr>();
6595     NewDecl->dropAttr<DLLImportAttr>();
6596     S.Diag(NewDecl->getLocation(),
6597            diag::warn_dllimport_dropped_from_inline_function)
6598         << NewDecl << OldImportAttr;
6599   }
6600 
6601   // A specialization of a class template member function is processed here
6602   // since it's a redeclaration. If the parent class is dllexport, the
6603   // specialization inherits that attribute. This doesn't happen automatically
6604   // since the parent class isn't instantiated until later.
6605   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6606     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6607         !NewImportAttr && !NewExportAttr) {
6608       if (const DLLExportAttr *ParentExportAttr =
6609               MD->getParent()->getAttr<DLLExportAttr>()) {
6610         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6611         NewAttr->setInherited(true);
6612         NewDecl->addAttr(NewAttr);
6613       }
6614     }
6615   }
6616 }
6617 
6618 /// Given that we are within the definition of the given function,
6619 /// will that definition behave like C99's 'inline', where the
6620 /// definition is discarded except for optimization purposes?
6621 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6622   // Try to avoid calling GetGVALinkageForFunction.
6623 
6624   // All cases of this require the 'inline' keyword.
6625   if (!FD->isInlined()) return false;
6626 
6627   // This is only possible in C++ with the gnu_inline attribute.
6628   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6629     return false;
6630 
6631   // Okay, go ahead and call the relatively-more-expensive function.
6632   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6633 }
6634 
6635 /// Determine whether a variable is extern "C" prior to attaching
6636 /// an initializer. We can't just call isExternC() here, because that
6637 /// will also compute and cache whether the declaration is externally
6638 /// visible, which might change when we attach the initializer.
6639 ///
6640 /// This can only be used if the declaration is known to not be a
6641 /// redeclaration of an internal linkage declaration.
6642 ///
6643 /// For instance:
6644 ///
6645 ///   auto x = []{};
6646 ///
6647 /// Attaching the initializer here makes this declaration not externally
6648 /// visible, because its type has internal linkage.
6649 ///
6650 /// FIXME: This is a hack.
6651 template<typename T>
6652 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6653   if (S.getLangOpts().CPlusPlus) {
6654     // In C++, the overloadable attribute negates the effects of extern "C".
6655     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6656       return false;
6657 
6658     // So do CUDA's host/device attributes.
6659     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6660                                  D->template hasAttr<CUDAHostAttr>()))
6661       return false;
6662   }
6663   return D->isExternC();
6664 }
6665 
6666 static bool shouldConsiderLinkage(const VarDecl *VD) {
6667   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6668   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6669       isa<OMPDeclareMapperDecl>(DC))
6670     return VD->hasExternalStorage();
6671   if (DC->isFileContext())
6672     return true;
6673   if (DC->isRecord())
6674     return false;
6675   if (isa<RequiresExprBodyDecl>(DC))
6676     return false;
6677   llvm_unreachable("Unexpected context");
6678 }
6679 
6680 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6681   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6682   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6683       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6684     return true;
6685   if (DC->isRecord())
6686     return false;
6687   llvm_unreachable("Unexpected context");
6688 }
6689 
6690 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6691                           ParsedAttr::Kind Kind) {
6692   // Check decl attributes on the DeclSpec.
6693   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6694     return true;
6695 
6696   // Walk the declarator structure, checking decl attributes that were in a type
6697   // position to the decl itself.
6698   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6699     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6700       return true;
6701   }
6702 
6703   // Finally, check attributes on the decl itself.
6704   return PD.getAttributes().hasAttribute(Kind);
6705 }
6706 
6707 /// Adjust the \c DeclContext for a function or variable that might be a
6708 /// function-local external declaration.
6709 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6710   if (!DC->isFunctionOrMethod())
6711     return false;
6712 
6713   // If this is a local extern function or variable declared within a function
6714   // template, don't add it into the enclosing namespace scope until it is
6715   // instantiated; it might have a dependent type right now.
6716   if (DC->isDependentContext())
6717     return true;
6718 
6719   // C++11 [basic.link]p7:
6720   //   When a block scope declaration of an entity with linkage is not found to
6721   //   refer to some other declaration, then that entity is a member of the
6722   //   innermost enclosing namespace.
6723   //
6724   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6725   // semantically-enclosing namespace, not a lexically-enclosing one.
6726   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6727     DC = DC->getParent();
6728   return true;
6729 }
6730 
6731 /// Returns true if given declaration has external C language linkage.
6732 static bool isDeclExternC(const Decl *D) {
6733   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6734     return FD->isExternC();
6735   if (const auto *VD = dyn_cast<VarDecl>(D))
6736     return VD->isExternC();
6737 
6738   llvm_unreachable("Unknown type of decl!");
6739 }
6740 
6741 /// Returns true if there hasn't been any invalid type diagnosed.
6742 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6743   DeclContext *DC = NewVD->getDeclContext();
6744   QualType R = NewVD->getType();
6745 
6746   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6747   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6748   // argument.
6749   if (R->isImageType() || R->isPipeType()) {
6750     Se.Diag(NewVD->getLocation(),
6751             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6752         << R;
6753     NewVD->setInvalidDecl();
6754     return false;
6755   }
6756 
6757   // OpenCL v1.2 s6.9.r:
6758   // The event type cannot be used to declare a program scope variable.
6759   // OpenCL v2.0 s6.9.q:
6760   // The clk_event_t and reserve_id_t types cannot be declared in program
6761   // scope.
6762   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6763     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6764       Se.Diag(NewVD->getLocation(),
6765               diag::err_invalid_type_for_program_scope_var)
6766           << R;
6767       NewVD->setInvalidDecl();
6768       return false;
6769     }
6770   }
6771 
6772   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6773   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6774                                                Se.getLangOpts())) {
6775     QualType NR = R.getCanonicalType();
6776     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6777            NR->isReferenceType()) {
6778       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6779           NR->isFunctionReferenceType()) {
6780         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6781             << NR->isReferenceType();
6782         NewVD->setInvalidDecl();
6783         return false;
6784       }
6785       NR = NR->getPointeeType();
6786     }
6787   }
6788 
6789   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6790                                                Se.getLangOpts())) {
6791     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6792     // half array type (unless the cl_khr_fp16 extension is enabled).
6793     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6794       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6795       NewVD->setInvalidDecl();
6796       return false;
6797     }
6798   }
6799 
6800   // OpenCL v1.2 s6.9.r:
6801   // The event type cannot be used with the __local, __constant and __global
6802   // address space qualifiers.
6803   if (R->isEventT()) {
6804     if (R.getAddressSpace() != LangAS::opencl_private) {
6805       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6806       NewVD->setInvalidDecl();
6807       return false;
6808     }
6809   }
6810 
6811   if (R->isSamplerT()) {
6812     // OpenCL v1.2 s6.9.b p4:
6813     // The sampler type cannot be used with the __local and __global address
6814     // space qualifiers.
6815     if (R.getAddressSpace() == LangAS::opencl_local ||
6816         R.getAddressSpace() == LangAS::opencl_global) {
6817       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6818       NewVD->setInvalidDecl();
6819     }
6820 
6821     // OpenCL v1.2 s6.12.14.1:
6822     // A global sampler must be declared with either the constant address
6823     // space qualifier or with the const qualifier.
6824     if (DC->isTranslationUnit() &&
6825         !(R.getAddressSpace() == LangAS::opencl_constant ||
6826           R.isConstQualified())) {
6827       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6828       NewVD->setInvalidDecl();
6829     }
6830     if (NewVD->isInvalidDecl())
6831       return false;
6832   }
6833 
6834   return true;
6835 }
6836 
6837 template <typename AttrTy>
6838 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6839   const TypedefNameDecl *TND = TT->getDecl();
6840   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6841     AttrTy *Clone = Attribute->clone(S.Context);
6842     Clone->setInherited(true);
6843     D->addAttr(Clone);
6844   }
6845 }
6846 
6847 NamedDecl *Sema::ActOnVariableDeclarator(
6848     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6849     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6850     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6851   QualType R = TInfo->getType();
6852   DeclarationName Name = GetNameForDeclarator(D).getName();
6853 
6854   IdentifierInfo *II = Name.getAsIdentifierInfo();
6855 
6856   if (D.isDecompositionDeclarator()) {
6857     // Take the name of the first declarator as our name for diagnostic
6858     // purposes.
6859     auto &Decomp = D.getDecompositionDeclarator();
6860     if (!Decomp.bindings().empty()) {
6861       II = Decomp.bindings()[0].Name;
6862       Name = II;
6863     }
6864   } else if (!II) {
6865     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6866     return nullptr;
6867   }
6868 
6869 
6870   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6871   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6872 
6873   // dllimport globals without explicit storage class are treated as extern. We
6874   // have to change the storage class this early to get the right DeclContext.
6875   if (SC == SC_None && !DC->isRecord() &&
6876       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6877       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6878     SC = SC_Extern;
6879 
6880   DeclContext *OriginalDC = DC;
6881   bool IsLocalExternDecl = SC == SC_Extern &&
6882                            adjustContextForLocalExternDecl(DC);
6883 
6884   if (SCSpec == DeclSpec::SCS_mutable) {
6885     // mutable can only appear on non-static class members, so it's always
6886     // an error here
6887     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6888     D.setInvalidType();
6889     SC = SC_None;
6890   }
6891 
6892   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6893       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6894                               D.getDeclSpec().getStorageClassSpecLoc())) {
6895     // In C++11, the 'register' storage class specifier is deprecated.
6896     // Suppress the warning in system macros, it's used in macros in some
6897     // popular C system headers, such as in glibc's htonl() macro.
6898     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6899          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6900                                    : diag::warn_deprecated_register)
6901       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6902   }
6903 
6904   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6905 
6906   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6907     // C99 6.9p2: The storage-class specifiers auto and register shall not
6908     // appear in the declaration specifiers in an external declaration.
6909     // Global Register+Asm is a GNU extension we support.
6910     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6911       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6912       D.setInvalidType();
6913     }
6914   }
6915 
6916   // If this variable has a VLA type and an initializer, try to
6917   // fold to a constant-sized type. This is otherwise invalid.
6918   if (D.hasInitializer() && R->isVariableArrayType())
6919     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6920                                     /*DiagID=*/0);
6921 
6922   bool IsMemberSpecialization = false;
6923   bool IsVariableTemplateSpecialization = false;
6924   bool IsPartialSpecialization = false;
6925   bool IsVariableTemplate = false;
6926   VarDecl *NewVD = nullptr;
6927   VarTemplateDecl *NewTemplate = nullptr;
6928   TemplateParameterList *TemplateParams = nullptr;
6929   if (!getLangOpts().CPlusPlus) {
6930     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6931                             II, R, TInfo, SC);
6932 
6933     if (R->getContainedDeducedType())
6934       ParsingInitForAutoVars.insert(NewVD);
6935 
6936     if (D.isInvalidType())
6937       NewVD->setInvalidDecl();
6938 
6939     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6940         NewVD->hasLocalStorage())
6941       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6942                             NTCUC_AutoVar, NTCUK_Destruct);
6943   } else {
6944     bool Invalid = false;
6945 
6946     if (DC->isRecord() && !CurContext->isRecord()) {
6947       // This is an out-of-line definition of a static data member.
6948       switch (SC) {
6949       case SC_None:
6950         break;
6951       case SC_Static:
6952         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6953              diag::err_static_out_of_line)
6954           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6955         break;
6956       case SC_Auto:
6957       case SC_Register:
6958       case SC_Extern:
6959         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6960         // to names of variables declared in a block or to function parameters.
6961         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6962         // of class members
6963 
6964         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6965              diag::err_storage_class_for_static_member)
6966           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6967         break;
6968       case SC_PrivateExtern:
6969         llvm_unreachable("C storage class in c++!");
6970       }
6971     }
6972 
6973     if (SC == SC_Static && CurContext->isRecord()) {
6974       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6975         // Walk up the enclosing DeclContexts to check for any that are
6976         // incompatible with static data members.
6977         const DeclContext *FunctionOrMethod = nullptr;
6978         const CXXRecordDecl *AnonStruct = nullptr;
6979         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6980           if (Ctxt->isFunctionOrMethod()) {
6981             FunctionOrMethod = Ctxt;
6982             break;
6983           }
6984           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6985           if (ParentDecl && !ParentDecl->getDeclName()) {
6986             AnonStruct = ParentDecl;
6987             break;
6988           }
6989         }
6990         if (FunctionOrMethod) {
6991           // C++ [class.static.data]p5: A local class shall not have static data
6992           // members.
6993           Diag(D.getIdentifierLoc(),
6994                diag::err_static_data_member_not_allowed_in_local_class)
6995             << Name << RD->getDeclName() << RD->getTagKind();
6996         } else if (AnonStruct) {
6997           // C++ [class.static.data]p4: Unnamed classes and classes contained
6998           // directly or indirectly within unnamed classes shall not contain
6999           // static data members.
7000           Diag(D.getIdentifierLoc(),
7001                diag::err_static_data_member_not_allowed_in_anon_struct)
7002             << Name << AnonStruct->getTagKind();
7003           Invalid = true;
7004         } else if (RD->isUnion()) {
7005           // C++98 [class.union]p1: If a union contains a static data member,
7006           // the program is ill-formed. C++11 drops this restriction.
7007           Diag(D.getIdentifierLoc(),
7008                getLangOpts().CPlusPlus11
7009                  ? diag::warn_cxx98_compat_static_data_member_in_union
7010                  : diag::ext_static_data_member_in_union) << Name;
7011         }
7012       }
7013     }
7014 
7015     // Match up the template parameter lists with the scope specifier, then
7016     // determine whether we have a template or a template specialization.
7017     bool InvalidScope = false;
7018     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7019         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7020         D.getCXXScopeSpec(),
7021         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7022             ? D.getName().TemplateId
7023             : nullptr,
7024         TemplateParamLists,
7025         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7026     Invalid |= InvalidScope;
7027 
7028     if (TemplateParams) {
7029       if (!TemplateParams->size() &&
7030           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7031         // There is an extraneous 'template<>' for this variable. Complain
7032         // about it, but allow the declaration of the variable.
7033         Diag(TemplateParams->getTemplateLoc(),
7034              diag::err_template_variable_noparams)
7035           << II
7036           << SourceRange(TemplateParams->getTemplateLoc(),
7037                          TemplateParams->getRAngleLoc());
7038         TemplateParams = nullptr;
7039       } else {
7040         // Check that we can declare a template here.
7041         if (CheckTemplateDeclScope(S, TemplateParams))
7042           return nullptr;
7043 
7044         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7045           // This is an explicit specialization or a partial specialization.
7046           IsVariableTemplateSpecialization = true;
7047           IsPartialSpecialization = TemplateParams->size() > 0;
7048         } else { // if (TemplateParams->size() > 0)
7049           // This is a template declaration.
7050           IsVariableTemplate = true;
7051 
7052           // Only C++1y supports variable templates (N3651).
7053           Diag(D.getIdentifierLoc(),
7054                getLangOpts().CPlusPlus14
7055                    ? diag::warn_cxx11_compat_variable_template
7056                    : diag::ext_variable_template);
7057         }
7058       }
7059     } else {
7060       // Check that we can declare a member specialization here.
7061       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7062           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7063         return nullptr;
7064       assert((Invalid ||
7065               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7066              "should have a 'template<>' for this decl");
7067     }
7068 
7069     if (IsVariableTemplateSpecialization) {
7070       SourceLocation TemplateKWLoc =
7071           TemplateParamLists.size() > 0
7072               ? TemplateParamLists[0]->getTemplateLoc()
7073               : SourceLocation();
7074       DeclResult Res = ActOnVarTemplateSpecialization(
7075           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7076           IsPartialSpecialization);
7077       if (Res.isInvalid())
7078         return nullptr;
7079       NewVD = cast<VarDecl>(Res.get());
7080       AddToScope = false;
7081     } else if (D.isDecompositionDeclarator()) {
7082       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7083                                         D.getIdentifierLoc(), R, TInfo, SC,
7084                                         Bindings);
7085     } else
7086       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7087                               D.getIdentifierLoc(), II, R, TInfo, SC);
7088 
7089     // If this is supposed to be a variable template, create it as such.
7090     if (IsVariableTemplate) {
7091       NewTemplate =
7092           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7093                                   TemplateParams, NewVD);
7094       NewVD->setDescribedVarTemplate(NewTemplate);
7095     }
7096 
7097     // If this decl has an auto type in need of deduction, make a note of the
7098     // Decl so we can diagnose uses of it in its own initializer.
7099     if (R->getContainedDeducedType())
7100       ParsingInitForAutoVars.insert(NewVD);
7101 
7102     if (D.isInvalidType() || Invalid) {
7103       NewVD->setInvalidDecl();
7104       if (NewTemplate)
7105         NewTemplate->setInvalidDecl();
7106     }
7107 
7108     SetNestedNameSpecifier(*this, NewVD, D);
7109 
7110     // If we have any template parameter lists that don't directly belong to
7111     // the variable (matching the scope specifier), store them.
7112     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7113     if (TemplateParamLists.size() > VDTemplateParamLists)
7114       NewVD->setTemplateParameterListsInfo(
7115           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7116   }
7117 
7118   if (D.getDeclSpec().isInlineSpecified()) {
7119     if (!getLangOpts().CPlusPlus) {
7120       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7121           << 0;
7122     } else if (CurContext->isFunctionOrMethod()) {
7123       // 'inline' is not allowed on block scope variable declaration.
7124       Diag(D.getDeclSpec().getInlineSpecLoc(),
7125            diag::err_inline_declaration_block_scope) << Name
7126         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7127     } else {
7128       Diag(D.getDeclSpec().getInlineSpecLoc(),
7129            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7130                                      : diag::ext_inline_variable);
7131       NewVD->setInlineSpecified();
7132     }
7133   }
7134 
7135   // Set the lexical context. If the declarator has a C++ scope specifier, the
7136   // lexical context will be different from the semantic context.
7137   NewVD->setLexicalDeclContext(CurContext);
7138   if (NewTemplate)
7139     NewTemplate->setLexicalDeclContext(CurContext);
7140 
7141   if (IsLocalExternDecl) {
7142     if (D.isDecompositionDeclarator())
7143       for (auto *B : Bindings)
7144         B->setLocalExternDecl();
7145     else
7146       NewVD->setLocalExternDecl();
7147   }
7148 
7149   bool EmitTLSUnsupportedError = false;
7150   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7151     // C++11 [dcl.stc]p4:
7152     //   When thread_local is applied to a variable of block scope the
7153     //   storage-class-specifier static is implied if it does not appear
7154     //   explicitly.
7155     // Core issue: 'static' is not implied if the variable is declared
7156     //   'extern'.
7157     if (NewVD->hasLocalStorage() &&
7158         (SCSpec != DeclSpec::SCS_unspecified ||
7159          TSCS != DeclSpec::TSCS_thread_local ||
7160          !DC->isFunctionOrMethod()))
7161       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7162            diag::err_thread_non_global)
7163         << DeclSpec::getSpecifierName(TSCS);
7164     else if (!Context.getTargetInfo().isTLSSupported()) {
7165       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7166           getLangOpts().SYCLIsDevice) {
7167         // Postpone error emission until we've collected attributes required to
7168         // figure out whether it's a host or device variable and whether the
7169         // error should be ignored.
7170         EmitTLSUnsupportedError = true;
7171         // We still need to mark the variable as TLS so it shows up in AST with
7172         // proper storage class for other tools to use even if we're not going
7173         // to emit any code for it.
7174         NewVD->setTSCSpec(TSCS);
7175       } else
7176         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7177              diag::err_thread_unsupported);
7178     } else
7179       NewVD->setTSCSpec(TSCS);
7180   }
7181 
7182   switch (D.getDeclSpec().getConstexprSpecifier()) {
7183   case ConstexprSpecKind::Unspecified:
7184     break;
7185 
7186   case ConstexprSpecKind::Consteval:
7187     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7188          diag::err_constexpr_wrong_decl_kind)
7189         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7190     LLVM_FALLTHROUGH;
7191 
7192   case ConstexprSpecKind::Constexpr:
7193     NewVD->setConstexpr(true);
7194     MaybeAddCUDAConstantAttr(NewVD);
7195     // C++1z [dcl.spec.constexpr]p1:
7196     //   A static data member declared with the constexpr specifier is
7197     //   implicitly an inline variable.
7198     if (NewVD->isStaticDataMember() &&
7199         (getLangOpts().CPlusPlus17 ||
7200          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7201       NewVD->setImplicitlyInline();
7202     break;
7203 
7204   case ConstexprSpecKind::Constinit:
7205     if (!NewVD->hasGlobalStorage())
7206       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7207            diag::err_constinit_local_variable);
7208     else
7209       NewVD->addAttr(ConstInitAttr::Create(
7210           Context, D.getDeclSpec().getConstexprSpecLoc(),
7211           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7212     break;
7213   }
7214 
7215   // C99 6.7.4p3
7216   //   An inline definition of a function with external linkage shall
7217   //   not contain a definition of a modifiable object with static or
7218   //   thread storage duration...
7219   // We only apply this when the function is required to be defined
7220   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7221   // that a local variable with thread storage duration still has to
7222   // be marked 'static'.  Also note that it's possible to get these
7223   // semantics in C++ using __attribute__((gnu_inline)).
7224   if (SC == SC_Static && S->getFnParent() != nullptr &&
7225       !NewVD->getType().isConstQualified()) {
7226     FunctionDecl *CurFD = getCurFunctionDecl();
7227     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7228       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7229            diag::warn_static_local_in_extern_inline);
7230       MaybeSuggestAddingStaticToDecl(CurFD);
7231     }
7232   }
7233 
7234   if (D.getDeclSpec().isModulePrivateSpecified()) {
7235     if (IsVariableTemplateSpecialization)
7236       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7237           << (IsPartialSpecialization ? 1 : 0)
7238           << FixItHint::CreateRemoval(
7239                  D.getDeclSpec().getModulePrivateSpecLoc());
7240     else if (IsMemberSpecialization)
7241       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7242         << 2
7243         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7244     else if (NewVD->hasLocalStorage())
7245       Diag(NewVD->getLocation(), diag::err_module_private_local)
7246           << 0 << NewVD
7247           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7248           << FixItHint::CreateRemoval(
7249                  D.getDeclSpec().getModulePrivateSpecLoc());
7250     else {
7251       NewVD->setModulePrivate();
7252       if (NewTemplate)
7253         NewTemplate->setModulePrivate();
7254       for (auto *B : Bindings)
7255         B->setModulePrivate();
7256     }
7257   }
7258 
7259   if (getLangOpts().OpenCL) {
7260     deduceOpenCLAddressSpace(NewVD);
7261 
7262     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7263     if (TSC != TSCS_unspecified) {
7264       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7265       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7266            diag::err_opencl_unknown_type_specifier)
7267           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7268           << DeclSpec::getSpecifierName(TSC) << 1;
7269       NewVD->setInvalidDecl();
7270     }
7271   }
7272 
7273   // Handle attributes prior to checking for duplicates in MergeVarDecl
7274   ProcessDeclAttributes(S, NewVD, D);
7275 
7276   // FIXME: This is probably the wrong location to be doing this and we should
7277   // probably be doing this for more attributes (especially for function
7278   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7279   // the code to copy attributes would be generated by TableGen.
7280   if (R->isFunctionPointerType())
7281     if (const auto *TT = R->getAs<TypedefType>())
7282       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7283 
7284   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7285       getLangOpts().SYCLIsDevice) {
7286     if (EmitTLSUnsupportedError &&
7287         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7288          (getLangOpts().OpenMPIsDevice &&
7289           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7290       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7291            diag::err_thread_unsupported);
7292 
7293     if (EmitTLSUnsupportedError &&
7294         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7295       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7296     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7297     // storage [duration]."
7298     if (SC == SC_None && S->getFnParent() != nullptr &&
7299         (NewVD->hasAttr<CUDASharedAttr>() ||
7300          NewVD->hasAttr<CUDAConstantAttr>())) {
7301       NewVD->setStorageClass(SC_Static);
7302     }
7303   }
7304 
7305   // Ensure that dllimport globals without explicit storage class are treated as
7306   // extern. The storage class is set above using parsed attributes. Now we can
7307   // check the VarDecl itself.
7308   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7309          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7310          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7311 
7312   // In auto-retain/release, infer strong retension for variables of
7313   // retainable type.
7314   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7315     NewVD->setInvalidDecl();
7316 
7317   // Handle GNU asm-label extension (encoded as an attribute).
7318   if (Expr *E = (Expr*)D.getAsmLabel()) {
7319     // The parser guarantees this is a string.
7320     StringLiteral *SE = cast<StringLiteral>(E);
7321     StringRef Label = SE->getString();
7322     if (S->getFnParent() != nullptr) {
7323       switch (SC) {
7324       case SC_None:
7325       case SC_Auto:
7326         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7327         break;
7328       case SC_Register:
7329         // Local Named register
7330         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7331             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7332           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7333         break;
7334       case SC_Static:
7335       case SC_Extern:
7336       case SC_PrivateExtern:
7337         break;
7338       }
7339     } else if (SC == SC_Register) {
7340       // Global Named register
7341       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7342         const auto &TI = Context.getTargetInfo();
7343         bool HasSizeMismatch;
7344 
7345         if (!TI.isValidGCCRegisterName(Label))
7346           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7347         else if (!TI.validateGlobalRegisterVariable(Label,
7348                                                     Context.getTypeSize(R),
7349                                                     HasSizeMismatch))
7350           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7351         else if (HasSizeMismatch)
7352           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7353       }
7354 
7355       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7356         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7357         NewVD->setInvalidDecl(true);
7358       }
7359     }
7360 
7361     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7362                                         /*IsLiteralLabel=*/true,
7363                                         SE->getStrTokenLoc(0)));
7364   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7365     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7366       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7367     if (I != ExtnameUndeclaredIdentifiers.end()) {
7368       if (isDeclExternC(NewVD)) {
7369         NewVD->addAttr(I->second);
7370         ExtnameUndeclaredIdentifiers.erase(I);
7371       } else
7372         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7373             << /*Variable*/1 << NewVD;
7374     }
7375   }
7376 
7377   // Find the shadowed declaration before filtering for scope.
7378   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7379                                 ? getShadowedDeclaration(NewVD, Previous)
7380                                 : nullptr;
7381 
7382   // Don't consider existing declarations that are in a different
7383   // scope and are out-of-semantic-context declarations (if the new
7384   // declaration has linkage).
7385   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7386                        D.getCXXScopeSpec().isNotEmpty() ||
7387                        IsMemberSpecialization ||
7388                        IsVariableTemplateSpecialization);
7389 
7390   // Check whether the previous declaration is in the same block scope. This
7391   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7392   if (getLangOpts().CPlusPlus &&
7393       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7394     NewVD->setPreviousDeclInSameBlockScope(
7395         Previous.isSingleResult() && !Previous.isShadowed() &&
7396         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7397 
7398   if (!getLangOpts().CPlusPlus) {
7399     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7400   } else {
7401     // If this is an explicit specialization of a static data member, check it.
7402     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7403         CheckMemberSpecialization(NewVD, Previous))
7404       NewVD->setInvalidDecl();
7405 
7406     // Merge the decl with the existing one if appropriate.
7407     if (!Previous.empty()) {
7408       if (Previous.isSingleResult() &&
7409           isa<FieldDecl>(Previous.getFoundDecl()) &&
7410           D.getCXXScopeSpec().isSet()) {
7411         // The user tried to define a non-static data member
7412         // out-of-line (C++ [dcl.meaning]p1).
7413         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7414           << D.getCXXScopeSpec().getRange();
7415         Previous.clear();
7416         NewVD->setInvalidDecl();
7417       }
7418     } else if (D.getCXXScopeSpec().isSet()) {
7419       // No previous declaration in the qualifying scope.
7420       Diag(D.getIdentifierLoc(), diag::err_no_member)
7421         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7422         << D.getCXXScopeSpec().getRange();
7423       NewVD->setInvalidDecl();
7424     }
7425 
7426     if (!IsVariableTemplateSpecialization)
7427       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7428 
7429     if (NewTemplate) {
7430       VarTemplateDecl *PrevVarTemplate =
7431           NewVD->getPreviousDecl()
7432               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7433               : nullptr;
7434 
7435       // Check the template parameter list of this declaration, possibly
7436       // merging in the template parameter list from the previous variable
7437       // template declaration.
7438       if (CheckTemplateParameterList(
7439               TemplateParams,
7440               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7441                               : nullptr,
7442               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7443                DC->isDependentContext())
7444                   ? TPC_ClassTemplateMember
7445                   : TPC_VarTemplate))
7446         NewVD->setInvalidDecl();
7447 
7448       // If we are providing an explicit specialization of a static variable
7449       // template, make a note of that.
7450       if (PrevVarTemplate &&
7451           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7452         PrevVarTemplate->setMemberSpecialization();
7453     }
7454   }
7455 
7456   // Diagnose shadowed variables iff this isn't a redeclaration.
7457   if (ShadowedDecl && !D.isRedeclaration())
7458     CheckShadow(NewVD, ShadowedDecl, Previous);
7459 
7460   ProcessPragmaWeak(S, NewVD);
7461 
7462   // If this is the first declaration of an extern C variable, update
7463   // the map of such variables.
7464   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7465       isIncompleteDeclExternC(*this, NewVD))
7466     RegisterLocallyScopedExternCDecl(NewVD, S);
7467 
7468   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7469     MangleNumberingContext *MCtx;
7470     Decl *ManglingContextDecl;
7471     std::tie(MCtx, ManglingContextDecl) =
7472         getCurrentMangleNumberContext(NewVD->getDeclContext());
7473     if (MCtx) {
7474       Context.setManglingNumber(
7475           NewVD, MCtx->getManglingNumber(
7476                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7477       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7478     }
7479   }
7480 
7481   // Special handling of variable named 'main'.
7482   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7483       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7484       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7485 
7486     // C++ [basic.start.main]p3
7487     // A program that declares a variable main at global scope is ill-formed.
7488     if (getLangOpts().CPlusPlus)
7489       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7490 
7491     // In C, and external-linkage variable named main results in undefined
7492     // behavior.
7493     else if (NewVD->hasExternalFormalLinkage())
7494       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7495   }
7496 
7497   if (D.isRedeclaration() && !Previous.empty()) {
7498     NamedDecl *Prev = Previous.getRepresentativeDecl();
7499     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7500                                    D.isFunctionDefinition());
7501   }
7502 
7503   if (NewTemplate) {
7504     if (NewVD->isInvalidDecl())
7505       NewTemplate->setInvalidDecl();
7506     ActOnDocumentableDecl(NewTemplate);
7507     return NewTemplate;
7508   }
7509 
7510   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7511     CompleteMemberSpecialization(NewVD, Previous);
7512 
7513   return NewVD;
7514 }
7515 
7516 /// Enum describing the %select options in diag::warn_decl_shadow.
7517 enum ShadowedDeclKind {
7518   SDK_Local,
7519   SDK_Global,
7520   SDK_StaticMember,
7521   SDK_Field,
7522   SDK_Typedef,
7523   SDK_Using,
7524   SDK_StructuredBinding
7525 };
7526 
7527 /// Determine what kind of declaration we're shadowing.
7528 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7529                                                 const DeclContext *OldDC) {
7530   if (isa<TypeAliasDecl>(ShadowedDecl))
7531     return SDK_Using;
7532   else if (isa<TypedefDecl>(ShadowedDecl))
7533     return SDK_Typedef;
7534   else if (isa<BindingDecl>(ShadowedDecl))
7535     return SDK_StructuredBinding;
7536   else if (isa<RecordDecl>(OldDC))
7537     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7538 
7539   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7540 }
7541 
7542 /// Return the location of the capture if the given lambda captures the given
7543 /// variable \p VD, or an invalid source location otherwise.
7544 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7545                                          const VarDecl *VD) {
7546   for (const Capture &Capture : LSI->Captures) {
7547     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7548       return Capture.getLocation();
7549   }
7550   return SourceLocation();
7551 }
7552 
7553 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7554                                      const LookupResult &R) {
7555   // Only diagnose if we're shadowing an unambiguous field or variable.
7556   if (R.getResultKind() != LookupResult::Found)
7557     return false;
7558 
7559   // Return false if warning is ignored.
7560   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7561 }
7562 
7563 /// Return the declaration shadowed by the given variable \p D, or null
7564 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7565 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7566                                         const LookupResult &R) {
7567   if (!shouldWarnIfShadowedDecl(Diags, R))
7568     return nullptr;
7569 
7570   // Don't diagnose declarations at file scope.
7571   if (D->hasGlobalStorage())
7572     return nullptr;
7573 
7574   NamedDecl *ShadowedDecl = R.getFoundDecl();
7575   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7576                                                             : nullptr;
7577 }
7578 
7579 /// Return the declaration shadowed by the given typedef \p D, or null
7580 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7581 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7582                                         const LookupResult &R) {
7583   // Don't warn if typedef declaration is part of a class
7584   if (D->getDeclContext()->isRecord())
7585     return nullptr;
7586 
7587   if (!shouldWarnIfShadowedDecl(Diags, R))
7588     return nullptr;
7589 
7590   NamedDecl *ShadowedDecl = R.getFoundDecl();
7591   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7592 }
7593 
7594 /// Return the declaration shadowed by the given variable \p D, or null
7595 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7596 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7597                                         const LookupResult &R) {
7598   if (!shouldWarnIfShadowedDecl(Diags, R))
7599     return nullptr;
7600 
7601   NamedDecl *ShadowedDecl = R.getFoundDecl();
7602   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7603                                                             : nullptr;
7604 }
7605 
7606 /// Diagnose variable or built-in function shadowing.  Implements
7607 /// -Wshadow.
7608 ///
7609 /// This method is called whenever a VarDecl is added to a "useful"
7610 /// scope.
7611 ///
7612 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7613 /// \param R the lookup of the name
7614 ///
7615 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7616                        const LookupResult &R) {
7617   DeclContext *NewDC = D->getDeclContext();
7618 
7619   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7620     // Fields are not shadowed by variables in C++ static methods.
7621     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7622       if (MD->isStatic())
7623         return;
7624 
7625     // Fields shadowed by constructor parameters are a special case. Usually
7626     // the constructor initializes the field with the parameter.
7627     if (isa<CXXConstructorDecl>(NewDC))
7628       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7629         // Remember that this was shadowed so we can either warn about its
7630         // modification or its existence depending on warning settings.
7631         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7632         return;
7633       }
7634   }
7635 
7636   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7637     if (shadowedVar->isExternC()) {
7638       // For shadowing external vars, make sure that we point to the global
7639       // declaration, not a locally scoped extern declaration.
7640       for (auto I : shadowedVar->redecls())
7641         if (I->isFileVarDecl()) {
7642           ShadowedDecl = I;
7643           break;
7644         }
7645     }
7646 
7647   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7648 
7649   unsigned WarningDiag = diag::warn_decl_shadow;
7650   SourceLocation CaptureLoc;
7651   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7652       isa<CXXMethodDecl>(NewDC)) {
7653     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7654       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7655         if (RD->getLambdaCaptureDefault() == LCD_None) {
7656           // Try to avoid warnings for lambdas with an explicit capture list.
7657           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7658           // Warn only when the lambda captures the shadowed decl explicitly.
7659           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7660           if (CaptureLoc.isInvalid())
7661             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7662         } else {
7663           // Remember that this was shadowed so we can avoid the warning if the
7664           // shadowed decl isn't captured and the warning settings allow it.
7665           cast<LambdaScopeInfo>(getCurFunction())
7666               ->ShadowingDecls.push_back(
7667                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7668           return;
7669         }
7670       }
7671 
7672       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7673         // A variable can't shadow a local variable in an enclosing scope, if
7674         // they are separated by a non-capturing declaration context.
7675         for (DeclContext *ParentDC = NewDC;
7676              ParentDC && !ParentDC->Equals(OldDC);
7677              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7678           // Only block literals, captured statements, and lambda expressions
7679           // can capture; other scopes don't.
7680           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7681               !isLambdaCallOperator(ParentDC)) {
7682             return;
7683           }
7684         }
7685       }
7686     }
7687   }
7688 
7689   // Only warn about certain kinds of shadowing for class members.
7690   if (NewDC && NewDC->isRecord()) {
7691     // In particular, don't warn about shadowing non-class members.
7692     if (!OldDC->isRecord())
7693       return;
7694 
7695     // TODO: should we warn about static data members shadowing
7696     // static data members from base classes?
7697 
7698     // TODO: don't diagnose for inaccessible shadowed members.
7699     // This is hard to do perfectly because we might friend the
7700     // shadowing context, but that's just a false negative.
7701   }
7702 
7703 
7704   DeclarationName Name = R.getLookupName();
7705 
7706   // Emit warning and note.
7707   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7708     return;
7709   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7710   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7711   if (!CaptureLoc.isInvalid())
7712     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7713         << Name << /*explicitly*/ 1;
7714   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7715 }
7716 
7717 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7718 /// when these variables are captured by the lambda.
7719 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7720   for (const auto &Shadow : LSI->ShadowingDecls) {
7721     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7722     // Try to avoid the warning when the shadowed decl isn't captured.
7723     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7724     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7725     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7726                                        ? diag::warn_decl_shadow_uncaptured_local
7727                                        : diag::warn_decl_shadow)
7728         << Shadow.VD->getDeclName()
7729         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7730     if (!CaptureLoc.isInvalid())
7731       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7732           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7733     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7734   }
7735 }
7736 
7737 /// Check -Wshadow without the advantage of a previous lookup.
7738 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7739   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7740     return;
7741 
7742   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7743                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7744   LookupName(R, S);
7745   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7746     CheckShadow(D, ShadowedDecl, R);
7747 }
7748 
7749 /// Check if 'E', which is an expression that is about to be modified, refers
7750 /// to a constructor parameter that shadows a field.
7751 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7752   // Quickly ignore expressions that can't be shadowing ctor parameters.
7753   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7754     return;
7755   E = E->IgnoreParenImpCasts();
7756   auto *DRE = dyn_cast<DeclRefExpr>(E);
7757   if (!DRE)
7758     return;
7759   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7760   auto I = ShadowingDecls.find(D);
7761   if (I == ShadowingDecls.end())
7762     return;
7763   const NamedDecl *ShadowedDecl = I->second;
7764   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7765   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7766   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7767   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7768 
7769   // Avoid issuing multiple warnings about the same decl.
7770   ShadowingDecls.erase(I);
7771 }
7772 
7773 /// Check for conflict between this global or extern "C" declaration and
7774 /// previous global or extern "C" declarations. This is only used in C++.
7775 template<typename T>
7776 static bool checkGlobalOrExternCConflict(
7777     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7778   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7779   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7780 
7781   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7782     // The common case: this global doesn't conflict with any extern "C"
7783     // declaration.
7784     return false;
7785   }
7786 
7787   if (Prev) {
7788     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7789       // Both the old and new declarations have C language linkage. This is a
7790       // redeclaration.
7791       Previous.clear();
7792       Previous.addDecl(Prev);
7793       return true;
7794     }
7795 
7796     // This is a global, non-extern "C" declaration, and there is a previous
7797     // non-global extern "C" declaration. Diagnose if this is a variable
7798     // declaration.
7799     if (!isa<VarDecl>(ND))
7800       return false;
7801   } else {
7802     // The declaration is extern "C". Check for any declaration in the
7803     // translation unit which might conflict.
7804     if (IsGlobal) {
7805       // We have already performed the lookup into the translation unit.
7806       IsGlobal = false;
7807       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7808            I != E; ++I) {
7809         if (isa<VarDecl>(*I)) {
7810           Prev = *I;
7811           break;
7812         }
7813       }
7814     } else {
7815       DeclContext::lookup_result R =
7816           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7817       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7818            I != E; ++I) {
7819         if (isa<VarDecl>(*I)) {
7820           Prev = *I;
7821           break;
7822         }
7823         // FIXME: If we have any other entity with this name in global scope,
7824         // the declaration is ill-formed, but that is a defect: it breaks the
7825         // 'stat' hack, for instance. Only variables can have mangled name
7826         // clashes with extern "C" declarations, so only they deserve a
7827         // diagnostic.
7828       }
7829     }
7830 
7831     if (!Prev)
7832       return false;
7833   }
7834 
7835   // Use the first declaration's location to ensure we point at something which
7836   // is lexically inside an extern "C" linkage-spec.
7837   assert(Prev && "should have found a previous declaration to diagnose");
7838   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7839     Prev = FD->getFirstDecl();
7840   else
7841     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7842 
7843   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7844     << IsGlobal << ND;
7845   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7846     << IsGlobal;
7847   return false;
7848 }
7849 
7850 /// Apply special rules for handling extern "C" declarations. Returns \c true
7851 /// if we have found that this is a redeclaration of some prior entity.
7852 ///
7853 /// Per C++ [dcl.link]p6:
7854 ///   Two declarations [for a function or variable] with C language linkage
7855 ///   with the same name that appear in different scopes refer to the same
7856 ///   [entity]. An entity with C language linkage shall not be declared with
7857 ///   the same name as an entity in global scope.
7858 template<typename T>
7859 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7860                                                   LookupResult &Previous) {
7861   if (!S.getLangOpts().CPlusPlus) {
7862     // In C, when declaring a global variable, look for a corresponding 'extern'
7863     // variable declared in function scope. We don't need this in C++, because
7864     // we find local extern decls in the surrounding file-scope DeclContext.
7865     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7866       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7867         Previous.clear();
7868         Previous.addDecl(Prev);
7869         return true;
7870       }
7871     }
7872     return false;
7873   }
7874 
7875   // A declaration in the translation unit can conflict with an extern "C"
7876   // declaration.
7877   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7878     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7879 
7880   // An extern "C" declaration can conflict with a declaration in the
7881   // translation unit or can be a redeclaration of an extern "C" declaration
7882   // in another scope.
7883   if (isIncompleteDeclExternC(S,ND))
7884     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7885 
7886   // Neither global nor extern "C": nothing to do.
7887   return false;
7888 }
7889 
7890 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7891   // If the decl is already known invalid, don't check it.
7892   if (NewVD->isInvalidDecl())
7893     return;
7894 
7895   QualType T = NewVD->getType();
7896 
7897   // Defer checking an 'auto' type until its initializer is attached.
7898   if (T->isUndeducedType())
7899     return;
7900 
7901   if (NewVD->hasAttrs())
7902     CheckAlignasUnderalignment(NewVD);
7903 
7904   if (T->isObjCObjectType()) {
7905     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7906       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7907     T = Context.getObjCObjectPointerType(T);
7908     NewVD->setType(T);
7909   }
7910 
7911   // Emit an error if an address space was applied to decl with local storage.
7912   // This includes arrays of objects with address space qualifiers, but not
7913   // automatic variables that point to other address spaces.
7914   // ISO/IEC TR 18037 S5.1.2
7915   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7916       T.getAddressSpace() != LangAS::Default) {
7917     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7918     NewVD->setInvalidDecl();
7919     return;
7920   }
7921 
7922   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7923   // scope.
7924   if (getLangOpts().OpenCLVersion == 120 &&
7925       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7926                                             getLangOpts()) &&
7927       NewVD->isStaticLocal()) {
7928     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7929     NewVD->setInvalidDecl();
7930     return;
7931   }
7932 
7933   if (getLangOpts().OpenCL) {
7934     if (!diagnoseOpenCLTypes(*this, NewVD))
7935       return;
7936 
7937     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7938     if (NewVD->hasAttr<BlocksAttr>()) {
7939       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7940       return;
7941     }
7942 
7943     if (T->isBlockPointerType()) {
7944       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7945       // can't use 'extern' storage class.
7946       if (!T.isConstQualified()) {
7947         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7948             << 0 /*const*/;
7949         NewVD->setInvalidDecl();
7950         return;
7951       }
7952       if (NewVD->hasExternalStorage()) {
7953         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7954         NewVD->setInvalidDecl();
7955         return;
7956       }
7957     }
7958 
7959     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7960     // __constant address space.
7961     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7962     // variables inside a function can also be declared in the global
7963     // address space.
7964     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7965     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7966     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7967         NewVD->hasExternalStorage()) {
7968       if (!T->isSamplerT() &&
7969           !T->isDependentType() &&
7970           !(T.getAddressSpace() == LangAS::opencl_constant ||
7971             (T.getAddressSpace() == LangAS::opencl_global &&
7972              (getLangOpts().OpenCLVersion == 200 ||
7973               getLangOpts().OpenCLCPlusPlus)))) {
7974         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7975         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7976           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7977               << Scope << "global or constant";
7978         else
7979           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7980               << Scope << "constant";
7981         NewVD->setInvalidDecl();
7982         return;
7983       }
7984     } else {
7985       if (T.getAddressSpace() == LangAS::opencl_global) {
7986         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7987             << 1 /*is any function*/ << "global";
7988         NewVD->setInvalidDecl();
7989         return;
7990       }
7991       if (T.getAddressSpace() == LangAS::opencl_constant ||
7992           T.getAddressSpace() == LangAS::opencl_local) {
7993         FunctionDecl *FD = getCurFunctionDecl();
7994         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7995         // in functions.
7996         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7997           if (T.getAddressSpace() == LangAS::opencl_constant)
7998             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7999                 << 0 /*non-kernel only*/ << "constant";
8000           else
8001             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8002                 << 0 /*non-kernel only*/ << "local";
8003           NewVD->setInvalidDecl();
8004           return;
8005         }
8006         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8007         // in the outermost scope of a kernel function.
8008         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8009           if (!getCurScope()->isFunctionScope()) {
8010             if (T.getAddressSpace() == LangAS::opencl_constant)
8011               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8012                   << "constant";
8013             else
8014               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8015                   << "local";
8016             NewVD->setInvalidDecl();
8017             return;
8018           }
8019         }
8020       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8021                  // If we are parsing a template we didn't deduce an addr
8022                  // space yet.
8023                  T.getAddressSpace() != LangAS::Default) {
8024         // Do not allow other address spaces on automatic variable.
8025         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8026         NewVD->setInvalidDecl();
8027         return;
8028       }
8029     }
8030   }
8031 
8032   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8033       && !NewVD->hasAttr<BlocksAttr>()) {
8034     if (getLangOpts().getGC() != LangOptions::NonGC)
8035       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8036     else {
8037       assert(!getLangOpts().ObjCAutoRefCount);
8038       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8039     }
8040   }
8041 
8042   bool isVM = T->isVariablyModifiedType();
8043   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8044       NewVD->hasAttr<BlocksAttr>())
8045     setFunctionHasBranchProtectedScope();
8046 
8047   if ((isVM && NewVD->hasLinkage()) ||
8048       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8049     bool SizeIsNegative;
8050     llvm::APSInt Oversized;
8051     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8052         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8053     QualType FixedT;
8054     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8055       FixedT = FixedTInfo->getType();
8056     else if (FixedTInfo) {
8057       // Type and type-as-written are canonically different. We need to fix up
8058       // both types separately.
8059       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8060                                                    Oversized);
8061     }
8062     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8063       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8064       // FIXME: This won't give the correct result for
8065       // int a[10][n];
8066       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8067 
8068       if (NewVD->isFileVarDecl())
8069         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8070         << SizeRange;
8071       else if (NewVD->isStaticLocal())
8072         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8073         << SizeRange;
8074       else
8075         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8076         << SizeRange;
8077       NewVD->setInvalidDecl();
8078       return;
8079     }
8080 
8081     if (!FixedTInfo) {
8082       if (NewVD->isFileVarDecl())
8083         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8084       else
8085         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8086       NewVD->setInvalidDecl();
8087       return;
8088     }
8089 
8090     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8091     NewVD->setType(FixedT);
8092     NewVD->setTypeSourceInfo(FixedTInfo);
8093   }
8094 
8095   if (T->isVoidType()) {
8096     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8097     //                    of objects and functions.
8098     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8099       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8100         << T;
8101       NewVD->setInvalidDecl();
8102       return;
8103     }
8104   }
8105 
8106   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8107     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8108     NewVD->setInvalidDecl();
8109     return;
8110   }
8111 
8112   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8113     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8114     NewVD->setInvalidDecl();
8115     return;
8116   }
8117 
8118   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8119     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8120     NewVD->setInvalidDecl();
8121     return;
8122   }
8123 
8124   if (NewVD->isConstexpr() && !T->isDependentType() &&
8125       RequireLiteralType(NewVD->getLocation(), T,
8126                          diag::err_constexpr_var_non_literal)) {
8127     NewVD->setInvalidDecl();
8128     return;
8129   }
8130 
8131   // PPC MMA non-pointer types are not allowed as non-local variable types.
8132   if (Context.getTargetInfo().getTriple().isPPC64() &&
8133       !NewVD->isLocalVarDecl() &&
8134       CheckPPCMMAType(T, NewVD->getLocation())) {
8135     NewVD->setInvalidDecl();
8136     return;
8137   }
8138 }
8139 
8140 /// Perform semantic checking on a newly-created variable
8141 /// declaration.
8142 ///
8143 /// This routine performs all of the type-checking required for a
8144 /// variable declaration once it has been built. It is used both to
8145 /// check variables after they have been parsed and their declarators
8146 /// have been translated into a declaration, and to check variables
8147 /// that have been instantiated from a template.
8148 ///
8149 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8150 ///
8151 /// Returns true if the variable declaration is a redeclaration.
8152 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8153   CheckVariableDeclarationType(NewVD);
8154 
8155   // If the decl is already known invalid, don't check it.
8156   if (NewVD->isInvalidDecl())
8157     return false;
8158 
8159   // If we did not find anything by this name, look for a non-visible
8160   // extern "C" declaration with the same name.
8161   if (Previous.empty() &&
8162       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8163     Previous.setShadowed();
8164 
8165   if (!Previous.empty()) {
8166     MergeVarDecl(NewVD, Previous);
8167     return true;
8168   }
8169   return false;
8170 }
8171 
8172 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8173 /// and if so, check that it's a valid override and remember it.
8174 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8175   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8176 
8177   // Look for methods in base classes that this method might override.
8178   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8179                      /*DetectVirtual=*/false);
8180   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8181     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8182     DeclarationName Name = MD->getDeclName();
8183 
8184     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8185       // We really want to find the base class destructor here.
8186       QualType T = Context.getTypeDeclType(BaseRecord);
8187       CanQualType CT = Context.getCanonicalType(T);
8188       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8189     }
8190 
8191     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8192       CXXMethodDecl *BaseMD =
8193           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8194       if (!BaseMD || !BaseMD->isVirtual() ||
8195           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8196                      /*ConsiderCudaAttrs=*/true,
8197                      // C++2a [class.virtual]p2 does not consider requires
8198                      // clauses when overriding.
8199                      /*ConsiderRequiresClauses=*/false))
8200         continue;
8201 
8202       if (Overridden.insert(BaseMD).second) {
8203         MD->addOverriddenMethod(BaseMD);
8204         CheckOverridingFunctionReturnType(MD, BaseMD);
8205         CheckOverridingFunctionAttributes(MD, BaseMD);
8206         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8207         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8208       }
8209 
8210       // A method can only override one function from each base class. We
8211       // don't track indirectly overridden methods from bases of bases.
8212       return true;
8213     }
8214 
8215     return false;
8216   };
8217 
8218   DC->lookupInBases(VisitBase, Paths);
8219   return !Overridden.empty();
8220 }
8221 
8222 namespace {
8223   // Struct for holding all of the extra arguments needed by
8224   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8225   struct ActOnFDArgs {
8226     Scope *S;
8227     Declarator &D;
8228     MultiTemplateParamsArg TemplateParamLists;
8229     bool AddToScope;
8230   };
8231 } // end anonymous namespace
8232 
8233 namespace {
8234 
8235 // Callback to only accept typo corrections that have a non-zero edit distance.
8236 // Also only accept corrections that have the same parent decl.
8237 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8238  public:
8239   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8240                             CXXRecordDecl *Parent)
8241       : Context(Context), OriginalFD(TypoFD),
8242         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8243 
8244   bool ValidateCandidate(const TypoCorrection &candidate) override {
8245     if (candidate.getEditDistance() == 0)
8246       return false;
8247 
8248     SmallVector<unsigned, 1> MismatchedParams;
8249     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8250                                           CDeclEnd = candidate.end();
8251          CDecl != CDeclEnd; ++CDecl) {
8252       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8253 
8254       if (FD && !FD->hasBody() &&
8255           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8256         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8257           CXXRecordDecl *Parent = MD->getParent();
8258           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8259             return true;
8260         } else if (!ExpectedParent) {
8261           return true;
8262         }
8263       }
8264     }
8265 
8266     return false;
8267   }
8268 
8269   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8270     return std::make_unique<DifferentNameValidatorCCC>(*this);
8271   }
8272 
8273  private:
8274   ASTContext &Context;
8275   FunctionDecl *OriginalFD;
8276   CXXRecordDecl *ExpectedParent;
8277 };
8278 
8279 } // end anonymous namespace
8280 
8281 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8282   TypoCorrectedFunctionDefinitions.insert(F);
8283 }
8284 
8285 /// Generate diagnostics for an invalid function redeclaration.
8286 ///
8287 /// This routine handles generating the diagnostic messages for an invalid
8288 /// function redeclaration, including finding possible similar declarations
8289 /// or performing typo correction if there are no previous declarations with
8290 /// the same name.
8291 ///
8292 /// Returns a NamedDecl iff typo correction was performed and substituting in
8293 /// the new declaration name does not cause new errors.
8294 static NamedDecl *DiagnoseInvalidRedeclaration(
8295     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8296     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8297   DeclarationName Name = NewFD->getDeclName();
8298   DeclContext *NewDC = NewFD->getDeclContext();
8299   SmallVector<unsigned, 1> MismatchedParams;
8300   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8301   TypoCorrection Correction;
8302   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8303   unsigned DiagMsg =
8304     IsLocalFriend ? diag::err_no_matching_local_friend :
8305     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8306     diag::err_member_decl_does_not_match;
8307   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8308                     IsLocalFriend ? Sema::LookupLocalFriendName
8309                                   : Sema::LookupOrdinaryName,
8310                     Sema::ForVisibleRedeclaration);
8311 
8312   NewFD->setInvalidDecl();
8313   if (IsLocalFriend)
8314     SemaRef.LookupName(Prev, S);
8315   else
8316     SemaRef.LookupQualifiedName(Prev, NewDC);
8317   assert(!Prev.isAmbiguous() &&
8318          "Cannot have an ambiguity in previous-declaration lookup");
8319   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8320   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8321                                 MD ? MD->getParent() : nullptr);
8322   if (!Prev.empty()) {
8323     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8324          Func != FuncEnd; ++Func) {
8325       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8326       if (FD &&
8327           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8328         // Add 1 to the index so that 0 can mean the mismatch didn't
8329         // involve a parameter
8330         unsigned ParamNum =
8331             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8332         NearMatches.push_back(std::make_pair(FD, ParamNum));
8333       }
8334     }
8335   // If the qualified name lookup yielded nothing, try typo correction
8336   } else if ((Correction = SemaRef.CorrectTypo(
8337                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8338                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8339                   IsLocalFriend ? nullptr : NewDC))) {
8340     // Set up everything for the call to ActOnFunctionDeclarator
8341     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8342                               ExtraArgs.D.getIdentifierLoc());
8343     Previous.clear();
8344     Previous.setLookupName(Correction.getCorrection());
8345     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8346                                     CDeclEnd = Correction.end();
8347          CDecl != CDeclEnd; ++CDecl) {
8348       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8349       if (FD && !FD->hasBody() &&
8350           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8351         Previous.addDecl(FD);
8352       }
8353     }
8354     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8355 
8356     NamedDecl *Result;
8357     // Retry building the function declaration with the new previous
8358     // declarations, and with errors suppressed.
8359     {
8360       // Trap errors.
8361       Sema::SFINAETrap Trap(SemaRef);
8362 
8363       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8364       // pieces need to verify the typo-corrected C++ declaration and hopefully
8365       // eliminate the need for the parameter pack ExtraArgs.
8366       Result = SemaRef.ActOnFunctionDeclarator(
8367           ExtraArgs.S, ExtraArgs.D,
8368           Correction.getCorrectionDecl()->getDeclContext(),
8369           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8370           ExtraArgs.AddToScope);
8371 
8372       if (Trap.hasErrorOccurred())
8373         Result = nullptr;
8374     }
8375 
8376     if (Result) {
8377       // Determine which correction we picked.
8378       Decl *Canonical = Result->getCanonicalDecl();
8379       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8380            I != E; ++I)
8381         if ((*I)->getCanonicalDecl() == Canonical)
8382           Correction.setCorrectionDecl(*I);
8383 
8384       // Let Sema know about the correction.
8385       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8386       SemaRef.diagnoseTypo(
8387           Correction,
8388           SemaRef.PDiag(IsLocalFriend
8389                           ? diag::err_no_matching_local_friend_suggest
8390                           : diag::err_member_decl_does_not_match_suggest)
8391             << Name << NewDC << IsDefinition);
8392       return Result;
8393     }
8394 
8395     // Pretend the typo correction never occurred
8396     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8397                               ExtraArgs.D.getIdentifierLoc());
8398     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8399     Previous.clear();
8400     Previous.setLookupName(Name);
8401   }
8402 
8403   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8404       << Name << NewDC << IsDefinition << NewFD->getLocation();
8405 
8406   bool NewFDisConst = false;
8407   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8408     NewFDisConst = NewMD->isConst();
8409 
8410   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8411        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8412        NearMatch != NearMatchEnd; ++NearMatch) {
8413     FunctionDecl *FD = NearMatch->first;
8414     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8415     bool FDisConst = MD && MD->isConst();
8416     bool IsMember = MD || !IsLocalFriend;
8417 
8418     // FIXME: These notes are poorly worded for the local friend case.
8419     if (unsigned Idx = NearMatch->second) {
8420       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8421       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8422       if (Loc.isInvalid()) Loc = FD->getLocation();
8423       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8424                                  : diag::note_local_decl_close_param_match)
8425         << Idx << FDParam->getType()
8426         << NewFD->getParamDecl(Idx - 1)->getType();
8427     } else if (FDisConst != NewFDisConst) {
8428       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8429           << NewFDisConst << FD->getSourceRange().getEnd();
8430     } else
8431       SemaRef.Diag(FD->getLocation(),
8432                    IsMember ? diag::note_member_def_close_match
8433                             : diag::note_local_decl_close_match);
8434   }
8435   return nullptr;
8436 }
8437 
8438 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8439   switch (D.getDeclSpec().getStorageClassSpec()) {
8440   default: llvm_unreachable("Unknown storage class!");
8441   case DeclSpec::SCS_auto:
8442   case DeclSpec::SCS_register:
8443   case DeclSpec::SCS_mutable:
8444     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8445                  diag::err_typecheck_sclass_func);
8446     D.getMutableDeclSpec().ClearStorageClassSpecs();
8447     D.setInvalidType();
8448     break;
8449   case DeclSpec::SCS_unspecified: break;
8450   case DeclSpec::SCS_extern:
8451     if (D.getDeclSpec().isExternInLinkageSpec())
8452       return SC_None;
8453     return SC_Extern;
8454   case DeclSpec::SCS_static: {
8455     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8456       // C99 6.7.1p5:
8457       //   The declaration of an identifier for a function that has
8458       //   block scope shall have no explicit storage-class specifier
8459       //   other than extern
8460       // See also (C++ [dcl.stc]p4).
8461       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8462                    diag::err_static_block_func);
8463       break;
8464     } else
8465       return SC_Static;
8466   }
8467   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8468   }
8469 
8470   // No explicit storage class has already been returned
8471   return SC_None;
8472 }
8473 
8474 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8475                                            DeclContext *DC, QualType &R,
8476                                            TypeSourceInfo *TInfo,
8477                                            StorageClass SC,
8478                                            bool &IsVirtualOkay) {
8479   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8480   DeclarationName Name = NameInfo.getName();
8481 
8482   FunctionDecl *NewFD = nullptr;
8483   bool isInline = D.getDeclSpec().isInlineSpecified();
8484 
8485   if (!SemaRef.getLangOpts().CPlusPlus) {
8486     // Determine whether the function was written with a
8487     // prototype. This true when:
8488     //   - there is a prototype in the declarator, or
8489     //   - the type R of the function is some kind of typedef or other non-
8490     //     attributed reference to a type name (which eventually refers to a
8491     //     function type).
8492     bool HasPrototype =
8493       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8494       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8495 
8496     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8497                                  R, TInfo, SC, isInline, HasPrototype,
8498                                  ConstexprSpecKind::Unspecified,
8499                                  /*TrailingRequiresClause=*/nullptr);
8500     if (D.isInvalidType())
8501       NewFD->setInvalidDecl();
8502 
8503     return NewFD;
8504   }
8505 
8506   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8507 
8508   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8509   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8510     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8511                  diag::err_constexpr_wrong_decl_kind)
8512         << static_cast<int>(ConstexprKind);
8513     ConstexprKind = ConstexprSpecKind::Unspecified;
8514     D.getMutableDeclSpec().ClearConstexprSpec();
8515   }
8516   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8517 
8518   // Check that the return type is not an abstract class type.
8519   // For record types, this is done by the AbstractClassUsageDiagnoser once
8520   // the class has been completely parsed.
8521   if (!DC->isRecord() &&
8522       SemaRef.RequireNonAbstractType(
8523           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8524           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8525     D.setInvalidType();
8526 
8527   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8528     // This is a C++ constructor declaration.
8529     assert(DC->isRecord() &&
8530            "Constructors can only be declared in a member context");
8531 
8532     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8533     return CXXConstructorDecl::Create(
8534         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8535         TInfo, ExplicitSpecifier, isInline,
8536         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8537         TrailingRequiresClause);
8538 
8539   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8540     // This is a C++ destructor declaration.
8541     if (DC->isRecord()) {
8542       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8543       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8544       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8545           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8546           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8547           TrailingRequiresClause);
8548 
8549       // If the destructor needs an implicit exception specification, set it
8550       // now. FIXME: It'd be nice to be able to create the right type to start
8551       // with, but the type needs to reference the destructor declaration.
8552       if (SemaRef.getLangOpts().CPlusPlus11)
8553         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8554 
8555       IsVirtualOkay = true;
8556       return NewDD;
8557 
8558     } else {
8559       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8560       D.setInvalidType();
8561 
8562       // Create a FunctionDecl to satisfy the function definition parsing
8563       // code path.
8564       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8565                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8566                                   isInline,
8567                                   /*hasPrototype=*/true, ConstexprKind,
8568                                   TrailingRequiresClause);
8569     }
8570 
8571   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8572     if (!DC->isRecord()) {
8573       SemaRef.Diag(D.getIdentifierLoc(),
8574            diag::err_conv_function_not_member);
8575       return nullptr;
8576     }
8577 
8578     SemaRef.CheckConversionDeclarator(D, R, SC);
8579     if (D.isInvalidType())
8580       return nullptr;
8581 
8582     IsVirtualOkay = true;
8583     return CXXConversionDecl::Create(
8584         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8585         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8586         TrailingRequiresClause);
8587 
8588   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8589     if (TrailingRequiresClause)
8590       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8591                    diag::err_trailing_requires_clause_on_deduction_guide)
8592           << TrailingRequiresClause->getSourceRange();
8593     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8594 
8595     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8596                                          ExplicitSpecifier, NameInfo, R, TInfo,
8597                                          D.getEndLoc());
8598   } else if (DC->isRecord()) {
8599     // If the name of the function is the same as the name of the record,
8600     // then this must be an invalid constructor that has a return type.
8601     // (The parser checks for a return type and makes the declarator a
8602     // constructor if it has no return type).
8603     if (Name.getAsIdentifierInfo() &&
8604         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8605       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8606         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8607         << SourceRange(D.getIdentifierLoc());
8608       return nullptr;
8609     }
8610 
8611     // This is a C++ method declaration.
8612     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8613         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8614         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8615         TrailingRequiresClause);
8616     IsVirtualOkay = !Ret->isStatic();
8617     return Ret;
8618   } else {
8619     bool isFriend =
8620         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8621     if (!isFriend && SemaRef.CurContext->isRecord())
8622       return nullptr;
8623 
8624     // Determine whether the function was written with a
8625     // prototype. This true when:
8626     //   - we're in C++ (where every function has a prototype),
8627     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8628                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8629                                 ConstexprKind, TrailingRequiresClause);
8630   }
8631 }
8632 
8633 enum OpenCLParamType {
8634   ValidKernelParam,
8635   PtrPtrKernelParam,
8636   PtrKernelParam,
8637   InvalidAddrSpacePtrKernelParam,
8638   InvalidKernelParam,
8639   RecordKernelParam
8640 };
8641 
8642 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8643   // Size dependent types are just typedefs to normal integer types
8644   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8645   // integers other than by their names.
8646   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8647 
8648   // Remove typedefs one by one until we reach a typedef
8649   // for a size dependent type.
8650   QualType DesugaredTy = Ty;
8651   do {
8652     ArrayRef<StringRef> Names(SizeTypeNames);
8653     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8654     if (Names.end() != Match)
8655       return true;
8656 
8657     Ty = DesugaredTy;
8658     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8659   } while (DesugaredTy != Ty);
8660 
8661   return false;
8662 }
8663 
8664 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8665   if (PT->isPointerType() || PT->isReferenceType()) {
8666     QualType PointeeType = PT->getPointeeType();
8667     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8668         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8669         PointeeType.getAddressSpace() == LangAS::Default)
8670       return InvalidAddrSpacePtrKernelParam;
8671 
8672     if (PointeeType->isPointerType()) {
8673       // This is a pointer to pointer parameter.
8674       // Recursively check inner type.
8675       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8676       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8677           ParamKind == InvalidKernelParam)
8678         return ParamKind;
8679 
8680       return PtrPtrKernelParam;
8681     }
8682 
8683     // C++ for OpenCL v1.0 s2.4:
8684     // Moreover the types used in parameters of the kernel functions must be:
8685     // Standard layout types for pointer parameters. The same applies to
8686     // reference if an implementation supports them in kernel parameters.
8687     if (S.getLangOpts().OpenCLCPlusPlus && !PointeeType->isAtomicType() &&
8688         !PointeeType->isVoidType() && !PointeeType->isStandardLayoutType())
8689       return InvalidKernelParam;
8690 
8691     return PtrKernelParam;
8692   }
8693 
8694   // OpenCL v1.2 s6.9.k:
8695   // Arguments to kernel functions in a program cannot be declared with the
8696   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8697   // uintptr_t or a struct and/or union that contain fields declared to be one
8698   // of these built-in scalar types.
8699   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8700     return InvalidKernelParam;
8701 
8702   if (PT->isImageType())
8703     return PtrKernelParam;
8704 
8705   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8706     return InvalidKernelParam;
8707 
8708   // OpenCL extension spec v1.2 s9.5:
8709   // This extension adds support for half scalar and vector types as built-in
8710   // types that can be used for arithmetic operations, conversions etc.
8711   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8712       PT->isHalfType())
8713     return InvalidKernelParam;
8714 
8715   // Look into an array argument to check if it has a forbidden type.
8716   if (PT->isArrayType()) {
8717     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8718     // Call ourself to check an underlying type of an array. Since the
8719     // getPointeeOrArrayElementType returns an innermost type which is not an
8720     // array, this recursive call only happens once.
8721     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8722   }
8723 
8724   // C++ for OpenCL v1.0 s2.4:
8725   // Moreover the types used in parameters of the kernel functions must be:
8726   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8727   // types) for parameters passed by value;
8728   if (S.getLangOpts().OpenCLCPlusPlus && !PT->isOpenCLSpecificType() &&
8729       !PT.isPODType(S.Context))
8730     return InvalidKernelParam;
8731 
8732   if (PT->isRecordType())
8733     return RecordKernelParam;
8734 
8735   return ValidKernelParam;
8736 }
8737 
8738 static void checkIsValidOpenCLKernelParameter(
8739   Sema &S,
8740   Declarator &D,
8741   ParmVarDecl *Param,
8742   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8743   QualType PT = Param->getType();
8744 
8745   // Cache the valid types we encounter to avoid rechecking structs that are
8746   // used again
8747   if (ValidTypes.count(PT.getTypePtr()))
8748     return;
8749 
8750   switch (getOpenCLKernelParameterType(S, PT)) {
8751   case PtrPtrKernelParam:
8752     // OpenCL v3.0 s6.11.a:
8753     // A kernel function argument cannot be declared as a pointer to a pointer
8754     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8755     if (S.getLangOpts().OpenCLVersion < 120 &&
8756         !S.getLangOpts().OpenCLCPlusPlus) {
8757       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8758       D.setInvalidType();
8759       return;
8760     }
8761 
8762     ValidTypes.insert(PT.getTypePtr());
8763     return;
8764 
8765   case InvalidAddrSpacePtrKernelParam:
8766     // OpenCL v1.0 s6.5:
8767     // __kernel function arguments declared to be a pointer of a type can point
8768     // to one of the following address spaces only : __global, __local or
8769     // __constant.
8770     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8771     D.setInvalidType();
8772     return;
8773 
8774     // OpenCL v1.2 s6.9.k:
8775     // Arguments to kernel functions in a program cannot be declared with the
8776     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8777     // uintptr_t or a struct and/or union that contain fields declared to be
8778     // one of these built-in scalar types.
8779 
8780   case InvalidKernelParam:
8781     // OpenCL v1.2 s6.8 n:
8782     // A kernel function argument cannot be declared
8783     // of event_t type.
8784     // Do not diagnose half type since it is diagnosed as invalid argument
8785     // type for any function elsewhere.
8786     if (!PT->isHalfType()) {
8787       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8788 
8789       // Explain what typedefs are involved.
8790       const TypedefType *Typedef = nullptr;
8791       while ((Typedef = PT->getAs<TypedefType>())) {
8792         SourceLocation Loc = Typedef->getDecl()->getLocation();
8793         // SourceLocation may be invalid for a built-in type.
8794         if (Loc.isValid())
8795           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8796         PT = Typedef->desugar();
8797       }
8798     }
8799 
8800     D.setInvalidType();
8801     return;
8802 
8803   case PtrKernelParam:
8804   case ValidKernelParam:
8805     ValidTypes.insert(PT.getTypePtr());
8806     return;
8807 
8808   case RecordKernelParam:
8809     break;
8810   }
8811 
8812   // Track nested structs we will inspect
8813   SmallVector<const Decl *, 4> VisitStack;
8814 
8815   // Track where we are in the nested structs. Items will migrate from
8816   // VisitStack to HistoryStack as we do the DFS for bad field.
8817   SmallVector<const FieldDecl *, 4> HistoryStack;
8818   HistoryStack.push_back(nullptr);
8819 
8820   // At this point we already handled everything except of a RecordType or
8821   // an ArrayType of a RecordType.
8822   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8823   const RecordType *RecTy =
8824       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8825   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8826 
8827   VisitStack.push_back(RecTy->getDecl());
8828   assert(VisitStack.back() && "First decl null?");
8829 
8830   do {
8831     const Decl *Next = VisitStack.pop_back_val();
8832     if (!Next) {
8833       assert(!HistoryStack.empty());
8834       // Found a marker, we have gone up a level
8835       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8836         ValidTypes.insert(Hist->getType().getTypePtr());
8837 
8838       continue;
8839     }
8840 
8841     // Adds everything except the original parameter declaration (which is not a
8842     // field itself) to the history stack.
8843     const RecordDecl *RD;
8844     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8845       HistoryStack.push_back(Field);
8846 
8847       QualType FieldTy = Field->getType();
8848       // Other field types (known to be valid or invalid) are handled while we
8849       // walk around RecordDecl::fields().
8850       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8851              "Unexpected type.");
8852       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8853 
8854       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8855     } else {
8856       RD = cast<RecordDecl>(Next);
8857     }
8858 
8859     // Add a null marker so we know when we've gone back up a level
8860     VisitStack.push_back(nullptr);
8861 
8862     for (const auto *FD : RD->fields()) {
8863       QualType QT = FD->getType();
8864 
8865       if (ValidTypes.count(QT.getTypePtr()))
8866         continue;
8867 
8868       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8869       if (ParamType == ValidKernelParam)
8870         continue;
8871 
8872       if (ParamType == RecordKernelParam) {
8873         VisitStack.push_back(FD);
8874         continue;
8875       }
8876 
8877       // OpenCL v1.2 s6.9.p:
8878       // Arguments to kernel functions that are declared to be a struct or union
8879       // do not allow OpenCL objects to be passed as elements of the struct or
8880       // union.
8881       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8882           ParamType == InvalidAddrSpacePtrKernelParam) {
8883         S.Diag(Param->getLocation(),
8884                diag::err_record_with_pointers_kernel_param)
8885           << PT->isUnionType()
8886           << PT;
8887       } else {
8888         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8889       }
8890 
8891       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8892           << OrigRecDecl->getDeclName();
8893 
8894       // We have an error, now let's go back up through history and show where
8895       // the offending field came from
8896       for (ArrayRef<const FieldDecl *>::const_iterator
8897                I = HistoryStack.begin() + 1,
8898                E = HistoryStack.end();
8899            I != E; ++I) {
8900         const FieldDecl *OuterField = *I;
8901         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8902           << OuterField->getType();
8903       }
8904 
8905       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8906         << QT->isPointerType()
8907         << QT;
8908       D.setInvalidType();
8909       return;
8910     }
8911   } while (!VisitStack.empty());
8912 }
8913 
8914 /// Find the DeclContext in which a tag is implicitly declared if we see an
8915 /// elaborated type specifier in the specified context, and lookup finds
8916 /// nothing.
8917 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8918   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8919     DC = DC->getParent();
8920   return DC;
8921 }
8922 
8923 /// Find the Scope in which a tag is implicitly declared if we see an
8924 /// elaborated type specifier in the specified context, and lookup finds
8925 /// nothing.
8926 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8927   while (S->isClassScope() ||
8928          (LangOpts.CPlusPlus &&
8929           S->isFunctionPrototypeScope()) ||
8930          ((S->getFlags() & Scope::DeclScope) == 0) ||
8931          (S->getEntity() && S->getEntity()->isTransparentContext()))
8932     S = S->getParent();
8933   return S;
8934 }
8935 
8936 NamedDecl*
8937 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8938                               TypeSourceInfo *TInfo, LookupResult &Previous,
8939                               MultiTemplateParamsArg TemplateParamListsRef,
8940                               bool &AddToScope) {
8941   QualType R = TInfo->getType();
8942 
8943   assert(R->isFunctionType());
8944   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8945     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8946 
8947   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8948   for (TemplateParameterList *TPL : TemplateParamListsRef)
8949     TemplateParamLists.push_back(TPL);
8950   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8951     if (!TemplateParamLists.empty() &&
8952         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8953       TemplateParamLists.back() = Invented;
8954     else
8955       TemplateParamLists.push_back(Invented);
8956   }
8957 
8958   // TODO: consider using NameInfo for diagnostic.
8959   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8960   DeclarationName Name = NameInfo.getName();
8961   StorageClass SC = getFunctionStorageClass(*this, D);
8962 
8963   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8964     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8965          diag::err_invalid_thread)
8966       << DeclSpec::getSpecifierName(TSCS);
8967 
8968   if (D.isFirstDeclarationOfMember())
8969     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8970                            D.getIdentifierLoc());
8971 
8972   bool isFriend = false;
8973   FunctionTemplateDecl *FunctionTemplate = nullptr;
8974   bool isMemberSpecialization = false;
8975   bool isFunctionTemplateSpecialization = false;
8976 
8977   bool isDependentClassScopeExplicitSpecialization = false;
8978   bool HasExplicitTemplateArgs = false;
8979   TemplateArgumentListInfo TemplateArgs;
8980 
8981   bool isVirtualOkay = false;
8982 
8983   DeclContext *OriginalDC = DC;
8984   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8985 
8986   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8987                                               isVirtualOkay);
8988   if (!NewFD) return nullptr;
8989 
8990   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8991     NewFD->setTopLevelDeclInObjCContainer();
8992 
8993   // Set the lexical context. If this is a function-scope declaration, or has a
8994   // C++ scope specifier, or is the object of a friend declaration, the lexical
8995   // context will be different from the semantic context.
8996   NewFD->setLexicalDeclContext(CurContext);
8997 
8998   if (IsLocalExternDecl)
8999     NewFD->setLocalExternDecl();
9000 
9001   if (getLangOpts().CPlusPlus) {
9002     bool isInline = D.getDeclSpec().isInlineSpecified();
9003     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9004     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9005     isFriend = D.getDeclSpec().isFriendSpecified();
9006     if (isFriend && !isInline && D.isFunctionDefinition()) {
9007       // C++ [class.friend]p5
9008       //   A function can be defined in a friend declaration of a
9009       //   class . . . . Such a function is implicitly inline.
9010       NewFD->setImplicitlyInline();
9011     }
9012 
9013     // If this is a method defined in an __interface, and is not a constructor
9014     // or an overloaded operator, then set the pure flag (isVirtual will already
9015     // return true).
9016     if (const CXXRecordDecl *Parent =
9017           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9018       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9019         NewFD->setPure(true);
9020 
9021       // C++ [class.union]p2
9022       //   A union can have member functions, but not virtual functions.
9023       if (isVirtual && Parent->isUnion())
9024         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9025     }
9026 
9027     SetNestedNameSpecifier(*this, NewFD, D);
9028     isMemberSpecialization = false;
9029     isFunctionTemplateSpecialization = false;
9030     if (D.isInvalidType())
9031       NewFD->setInvalidDecl();
9032 
9033     // Match up the template parameter lists with the scope specifier, then
9034     // determine whether we have a template or a template specialization.
9035     bool Invalid = false;
9036     TemplateParameterList *TemplateParams =
9037         MatchTemplateParametersToScopeSpecifier(
9038             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9039             D.getCXXScopeSpec(),
9040             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9041                 ? D.getName().TemplateId
9042                 : nullptr,
9043             TemplateParamLists, isFriend, isMemberSpecialization,
9044             Invalid);
9045     if (TemplateParams) {
9046       // Check that we can declare a template here.
9047       if (CheckTemplateDeclScope(S, TemplateParams))
9048         NewFD->setInvalidDecl();
9049 
9050       if (TemplateParams->size() > 0) {
9051         // This is a function template
9052 
9053         // A destructor cannot be a template.
9054         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9055           Diag(NewFD->getLocation(), diag::err_destructor_template);
9056           NewFD->setInvalidDecl();
9057         }
9058 
9059         // If we're adding a template to a dependent context, we may need to
9060         // rebuilding some of the types used within the template parameter list,
9061         // now that we know what the current instantiation is.
9062         if (DC->isDependentContext()) {
9063           ContextRAII SavedContext(*this, DC);
9064           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9065             Invalid = true;
9066         }
9067 
9068         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9069                                                         NewFD->getLocation(),
9070                                                         Name, TemplateParams,
9071                                                         NewFD);
9072         FunctionTemplate->setLexicalDeclContext(CurContext);
9073         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9074 
9075         // For source fidelity, store the other template param lists.
9076         if (TemplateParamLists.size() > 1) {
9077           NewFD->setTemplateParameterListsInfo(Context,
9078               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9079                   .drop_back(1));
9080         }
9081       } else {
9082         // This is a function template specialization.
9083         isFunctionTemplateSpecialization = true;
9084         // For source fidelity, store all the template param lists.
9085         if (TemplateParamLists.size() > 0)
9086           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9087 
9088         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9089         if (isFriend) {
9090           // We want to remove the "template<>", found here.
9091           SourceRange RemoveRange = TemplateParams->getSourceRange();
9092 
9093           // If we remove the template<> and the name is not a
9094           // template-id, we're actually silently creating a problem:
9095           // the friend declaration will refer to an untemplated decl,
9096           // and clearly the user wants a template specialization.  So
9097           // we need to insert '<>' after the name.
9098           SourceLocation InsertLoc;
9099           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9100             InsertLoc = D.getName().getSourceRange().getEnd();
9101             InsertLoc = getLocForEndOfToken(InsertLoc);
9102           }
9103 
9104           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9105             << Name << RemoveRange
9106             << FixItHint::CreateRemoval(RemoveRange)
9107             << FixItHint::CreateInsertion(InsertLoc, "<>");
9108         }
9109       }
9110     } else {
9111       // Check that we can declare a template here.
9112       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9113           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9114         NewFD->setInvalidDecl();
9115 
9116       // All template param lists were matched against the scope specifier:
9117       // this is NOT (an explicit specialization of) a template.
9118       if (TemplateParamLists.size() > 0)
9119         // For source fidelity, store all the template param lists.
9120         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9121     }
9122 
9123     if (Invalid) {
9124       NewFD->setInvalidDecl();
9125       if (FunctionTemplate)
9126         FunctionTemplate->setInvalidDecl();
9127     }
9128 
9129     // C++ [dcl.fct.spec]p5:
9130     //   The virtual specifier shall only be used in declarations of
9131     //   nonstatic class member functions that appear within a
9132     //   member-specification of a class declaration; see 10.3.
9133     //
9134     if (isVirtual && !NewFD->isInvalidDecl()) {
9135       if (!isVirtualOkay) {
9136         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9137              diag::err_virtual_non_function);
9138       } else if (!CurContext->isRecord()) {
9139         // 'virtual' was specified outside of the class.
9140         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9141              diag::err_virtual_out_of_class)
9142           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9143       } else if (NewFD->getDescribedFunctionTemplate()) {
9144         // C++ [temp.mem]p3:
9145         //  A member function template shall not be virtual.
9146         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9147              diag::err_virtual_member_function_template)
9148           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9149       } else {
9150         // Okay: Add virtual to the method.
9151         NewFD->setVirtualAsWritten(true);
9152       }
9153 
9154       if (getLangOpts().CPlusPlus14 &&
9155           NewFD->getReturnType()->isUndeducedType())
9156         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9157     }
9158 
9159     if (getLangOpts().CPlusPlus14 &&
9160         (NewFD->isDependentContext() ||
9161          (isFriend && CurContext->isDependentContext())) &&
9162         NewFD->getReturnType()->isUndeducedType()) {
9163       // If the function template is referenced directly (for instance, as a
9164       // member of the current instantiation), pretend it has a dependent type.
9165       // This is not really justified by the standard, but is the only sane
9166       // thing to do.
9167       // FIXME: For a friend function, we have not marked the function as being
9168       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9169       const FunctionProtoType *FPT =
9170           NewFD->getType()->castAs<FunctionProtoType>();
9171       QualType Result =
9172           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9173       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9174                                              FPT->getExtProtoInfo()));
9175     }
9176 
9177     // C++ [dcl.fct.spec]p3:
9178     //  The inline specifier shall not appear on a block scope function
9179     //  declaration.
9180     if (isInline && !NewFD->isInvalidDecl()) {
9181       if (CurContext->isFunctionOrMethod()) {
9182         // 'inline' is not allowed on block scope function declaration.
9183         Diag(D.getDeclSpec().getInlineSpecLoc(),
9184              diag::err_inline_declaration_block_scope) << Name
9185           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9186       }
9187     }
9188 
9189     // C++ [dcl.fct.spec]p6:
9190     //  The explicit specifier shall be used only in the declaration of a
9191     //  constructor or conversion function within its class definition;
9192     //  see 12.3.1 and 12.3.2.
9193     if (hasExplicit && !NewFD->isInvalidDecl() &&
9194         !isa<CXXDeductionGuideDecl>(NewFD)) {
9195       if (!CurContext->isRecord()) {
9196         // 'explicit' was specified outside of the class.
9197         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9198              diag::err_explicit_out_of_class)
9199             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9200       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9201                  !isa<CXXConversionDecl>(NewFD)) {
9202         // 'explicit' was specified on a function that wasn't a constructor
9203         // or conversion function.
9204         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9205              diag::err_explicit_non_ctor_or_conv_function)
9206             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9207       }
9208     }
9209 
9210     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9211     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9212       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9213       // are implicitly inline.
9214       NewFD->setImplicitlyInline();
9215 
9216       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9217       // be either constructors or to return a literal type. Therefore,
9218       // destructors cannot be declared constexpr.
9219       if (isa<CXXDestructorDecl>(NewFD) &&
9220           (!getLangOpts().CPlusPlus20 ||
9221            ConstexprKind == ConstexprSpecKind::Consteval)) {
9222         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9223             << static_cast<int>(ConstexprKind);
9224         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9225                                     ? ConstexprSpecKind::Unspecified
9226                                     : ConstexprSpecKind::Constexpr);
9227       }
9228       // C++20 [dcl.constexpr]p2: An allocation function, or a
9229       // deallocation function shall not be declared with the consteval
9230       // specifier.
9231       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9232           (NewFD->getOverloadedOperator() == OO_New ||
9233            NewFD->getOverloadedOperator() == OO_Array_New ||
9234            NewFD->getOverloadedOperator() == OO_Delete ||
9235            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9236         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9237              diag::err_invalid_consteval_decl_kind)
9238             << NewFD;
9239         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9240       }
9241     }
9242 
9243     // If __module_private__ was specified, mark the function accordingly.
9244     if (D.getDeclSpec().isModulePrivateSpecified()) {
9245       if (isFunctionTemplateSpecialization) {
9246         SourceLocation ModulePrivateLoc
9247           = D.getDeclSpec().getModulePrivateSpecLoc();
9248         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9249           << 0
9250           << FixItHint::CreateRemoval(ModulePrivateLoc);
9251       } else {
9252         NewFD->setModulePrivate();
9253         if (FunctionTemplate)
9254           FunctionTemplate->setModulePrivate();
9255       }
9256     }
9257 
9258     if (isFriend) {
9259       if (FunctionTemplate) {
9260         FunctionTemplate->setObjectOfFriendDecl();
9261         FunctionTemplate->setAccess(AS_public);
9262       }
9263       NewFD->setObjectOfFriendDecl();
9264       NewFD->setAccess(AS_public);
9265     }
9266 
9267     // If a function is defined as defaulted or deleted, mark it as such now.
9268     // We'll do the relevant checks on defaulted / deleted functions later.
9269     switch (D.getFunctionDefinitionKind()) {
9270     case FunctionDefinitionKind::Declaration:
9271     case FunctionDefinitionKind::Definition:
9272       break;
9273 
9274     case FunctionDefinitionKind::Defaulted:
9275       NewFD->setDefaulted();
9276       break;
9277 
9278     case FunctionDefinitionKind::Deleted:
9279       NewFD->setDeletedAsWritten();
9280       break;
9281     }
9282 
9283     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9284         D.isFunctionDefinition()) {
9285       // C++ [class.mfct]p2:
9286       //   A member function may be defined (8.4) in its class definition, in
9287       //   which case it is an inline member function (7.1.2)
9288       NewFD->setImplicitlyInline();
9289     }
9290 
9291     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9292         !CurContext->isRecord()) {
9293       // C++ [class.static]p1:
9294       //   A data or function member of a class may be declared static
9295       //   in a class definition, in which case it is a static member of
9296       //   the class.
9297 
9298       // Complain about the 'static' specifier if it's on an out-of-line
9299       // member function definition.
9300 
9301       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9302       // member function template declaration and class member template
9303       // declaration (MSVC versions before 2015), warn about this.
9304       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9305            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9306              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9307            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9308            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9309         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9310     }
9311 
9312     // C++11 [except.spec]p15:
9313     //   A deallocation function with no exception-specification is treated
9314     //   as if it were specified with noexcept(true).
9315     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9316     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9317          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9318         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9319       NewFD->setType(Context.getFunctionType(
9320           FPT->getReturnType(), FPT->getParamTypes(),
9321           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9322   }
9323 
9324   // Filter out previous declarations that don't match the scope.
9325   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9326                        D.getCXXScopeSpec().isNotEmpty() ||
9327                        isMemberSpecialization ||
9328                        isFunctionTemplateSpecialization);
9329 
9330   // Handle GNU asm-label extension (encoded as an attribute).
9331   if (Expr *E = (Expr*) D.getAsmLabel()) {
9332     // The parser guarantees this is a string.
9333     StringLiteral *SE = cast<StringLiteral>(E);
9334     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9335                                         /*IsLiteralLabel=*/true,
9336                                         SE->getStrTokenLoc(0)));
9337   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9338     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9339       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9340     if (I != ExtnameUndeclaredIdentifiers.end()) {
9341       if (isDeclExternC(NewFD)) {
9342         NewFD->addAttr(I->second);
9343         ExtnameUndeclaredIdentifiers.erase(I);
9344       } else
9345         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9346             << /*Variable*/0 << NewFD;
9347     }
9348   }
9349 
9350   // Copy the parameter declarations from the declarator D to the function
9351   // declaration NewFD, if they are available.  First scavenge them into Params.
9352   SmallVector<ParmVarDecl*, 16> Params;
9353   unsigned FTIIdx;
9354   if (D.isFunctionDeclarator(FTIIdx)) {
9355     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9356 
9357     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9358     // function that takes no arguments, not a function that takes a
9359     // single void argument.
9360     // We let through "const void" here because Sema::GetTypeForDeclarator
9361     // already checks for that case.
9362     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9363       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9364         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9365         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9366         Param->setDeclContext(NewFD);
9367         Params.push_back(Param);
9368 
9369         if (Param->isInvalidDecl())
9370           NewFD->setInvalidDecl();
9371       }
9372     }
9373 
9374     if (!getLangOpts().CPlusPlus) {
9375       // In C, find all the tag declarations from the prototype and move them
9376       // into the function DeclContext. Remove them from the surrounding tag
9377       // injection context of the function, which is typically but not always
9378       // the TU.
9379       DeclContext *PrototypeTagContext =
9380           getTagInjectionContext(NewFD->getLexicalDeclContext());
9381       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9382         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9383 
9384         // We don't want to reparent enumerators. Look at their parent enum
9385         // instead.
9386         if (!TD) {
9387           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9388             TD = cast<EnumDecl>(ECD->getDeclContext());
9389         }
9390         if (!TD)
9391           continue;
9392         DeclContext *TagDC = TD->getLexicalDeclContext();
9393         if (!TagDC->containsDecl(TD))
9394           continue;
9395         TagDC->removeDecl(TD);
9396         TD->setDeclContext(NewFD);
9397         NewFD->addDecl(TD);
9398 
9399         // Preserve the lexical DeclContext if it is not the surrounding tag
9400         // injection context of the FD. In this example, the semantic context of
9401         // E will be f and the lexical context will be S, while both the
9402         // semantic and lexical contexts of S will be f:
9403         //   void f(struct S { enum E { a } f; } s);
9404         if (TagDC != PrototypeTagContext)
9405           TD->setLexicalDeclContext(TagDC);
9406       }
9407     }
9408   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9409     // When we're declaring a function with a typedef, typeof, etc as in the
9410     // following example, we'll need to synthesize (unnamed)
9411     // parameters for use in the declaration.
9412     //
9413     // @code
9414     // typedef void fn(int);
9415     // fn f;
9416     // @endcode
9417 
9418     // Synthesize a parameter for each argument type.
9419     for (const auto &AI : FT->param_types()) {
9420       ParmVarDecl *Param =
9421           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9422       Param->setScopeInfo(0, Params.size());
9423       Params.push_back(Param);
9424     }
9425   } else {
9426     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9427            "Should not need args for typedef of non-prototype fn");
9428   }
9429 
9430   // Finally, we know we have the right number of parameters, install them.
9431   NewFD->setParams(Params);
9432 
9433   if (D.getDeclSpec().isNoreturnSpecified())
9434     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9435                                            D.getDeclSpec().getNoreturnSpecLoc(),
9436                                            AttributeCommonInfo::AS_Keyword));
9437 
9438   // Functions returning a variably modified type violate C99 6.7.5.2p2
9439   // because all functions have linkage.
9440   if (!NewFD->isInvalidDecl() &&
9441       NewFD->getReturnType()->isVariablyModifiedType()) {
9442     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9443     NewFD->setInvalidDecl();
9444   }
9445 
9446   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9447   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9448       !NewFD->hasAttr<SectionAttr>())
9449     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9450         Context, PragmaClangTextSection.SectionName,
9451         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9452 
9453   // Apply an implicit SectionAttr if #pragma code_seg is active.
9454   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9455       !NewFD->hasAttr<SectionAttr>()) {
9456     NewFD->addAttr(SectionAttr::CreateImplicit(
9457         Context, CodeSegStack.CurrentValue->getString(),
9458         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9459         SectionAttr::Declspec_allocate));
9460     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9461                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9462                          ASTContext::PSF_Read,
9463                      NewFD))
9464       NewFD->dropAttr<SectionAttr>();
9465   }
9466 
9467   // Apply an implicit CodeSegAttr from class declspec or
9468   // apply an implicit SectionAttr from #pragma code_seg if active.
9469   if (!NewFD->hasAttr<CodeSegAttr>()) {
9470     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9471                                                                  D.isFunctionDefinition())) {
9472       NewFD->addAttr(SAttr);
9473     }
9474   }
9475 
9476   // Handle attributes.
9477   ProcessDeclAttributes(S, NewFD, D);
9478 
9479   if (getLangOpts().OpenCL) {
9480     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9481     // type declaration will generate a compilation error.
9482     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9483     if (AddressSpace != LangAS::Default) {
9484       Diag(NewFD->getLocation(),
9485            diag::err_opencl_return_value_with_address_space);
9486       NewFD->setInvalidDecl();
9487     }
9488   }
9489 
9490   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9491     checkDeviceDecl(NewFD, D.getBeginLoc());
9492 
9493   if (!getLangOpts().CPlusPlus) {
9494     // Perform semantic checking on the function declaration.
9495     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9496       CheckMain(NewFD, D.getDeclSpec());
9497 
9498     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9499       CheckMSVCRTEntryPoint(NewFD);
9500 
9501     if (!NewFD->isInvalidDecl())
9502       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9503                                                   isMemberSpecialization));
9504     else if (!Previous.empty())
9505       // Recover gracefully from an invalid redeclaration.
9506       D.setRedeclaration(true);
9507     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9508             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9509            "previous declaration set still overloaded");
9510 
9511     // Diagnose no-prototype function declarations with calling conventions that
9512     // don't support variadic calls. Only do this in C and do it after merging
9513     // possibly prototyped redeclarations.
9514     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9515     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9516       CallingConv CC = FT->getExtInfo().getCC();
9517       if (!supportsVariadicCall(CC)) {
9518         // Windows system headers sometimes accidentally use stdcall without
9519         // (void) parameters, so we relax this to a warning.
9520         int DiagID =
9521             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9522         Diag(NewFD->getLocation(), DiagID)
9523             << FunctionType::getNameForCallConv(CC);
9524       }
9525     }
9526 
9527    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9528        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9529      checkNonTrivialCUnion(NewFD->getReturnType(),
9530                            NewFD->getReturnTypeSourceRange().getBegin(),
9531                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9532   } else {
9533     // C++11 [replacement.functions]p3:
9534     //  The program's definitions shall not be specified as inline.
9535     //
9536     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9537     //
9538     // Suppress the diagnostic if the function is __attribute__((used)), since
9539     // that forces an external definition to be emitted.
9540     if (D.getDeclSpec().isInlineSpecified() &&
9541         NewFD->isReplaceableGlobalAllocationFunction() &&
9542         !NewFD->hasAttr<UsedAttr>())
9543       Diag(D.getDeclSpec().getInlineSpecLoc(),
9544            diag::ext_operator_new_delete_declared_inline)
9545         << NewFD->getDeclName();
9546 
9547     // If the declarator is a template-id, translate the parser's template
9548     // argument list into our AST format.
9549     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9550       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9551       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9552       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9553       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9554                                          TemplateId->NumArgs);
9555       translateTemplateArguments(TemplateArgsPtr,
9556                                  TemplateArgs);
9557 
9558       HasExplicitTemplateArgs = true;
9559 
9560       if (NewFD->isInvalidDecl()) {
9561         HasExplicitTemplateArgs = false;
9562       } else if (FunctionTemplate) {
9563         // Function template with explicit template arguments.
9564         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9565           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9566 
9567         HasExplicitTemplateArgs = false;
9568       } else {
9569         assert((isFunctionTemplateSpecialization ||
9570                 D.getDeclSpec().isFriendSpecified()) &&
9571                "should have a 'template<>' for this decl");
9572         // "friend void foo<>(int);" is an implicit specialization decl.
9573         isFunctionTemplateSpecialization = true;
9574       }
9575     } else if (isFriend && isFunctionTemplateSpecialization) {
9576       // This combination is only possible in a recovery case;  the user
9577       // wrote something like:
9578       //   template <> friend void foo(int);
9579       // which we're recovering from as if the user had written:
9580       //   friend void foo<>(int);
9581       // Go ahead and fake up a template id.
9582       HasExplicitTemplateArgs = true;
9583       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9584       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9585     }
9586 
9587     // We do not add HD attributes to specializations here because
9588     // they may have different constexpr-ness compared to their
9589     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9590     // may end up with different effective targets. Instead, a
9591     // specialization inherits its target attributes from its template
9592     // in the CheckFunctionTemplateSpecialization() call below.
9593     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9594       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9595 
9596     // If it's a friend (and only if it's a friend), it's possible
9597     // that either the specialized function type or the specialized
9598     // template is dependent, and therefore matching will fail.  In
9599     // this case, don't check the specialization yet.
9600     if (isFunctionTemplateSpecialization && isFriend &&
9601         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9602          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9603              TemplateArgs.arguments()))) {
9604       assert(HasExplicitTemplateArgs &&
9605              "friend function specialization without template args");
9606       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9607                                                        Previous))
9608         NewFD->setInvalidDecl();
9609     } else if (isFunctionTemplateSpecialization) {
9610       if (CurContext->isDependentContext() && CurContext->isRecord()
9611           && !isFriend) {
9612         isDependentClassScopeExplicitSpecialization = true;
9613       } else if (!NewFD->isInvalidDecl() &&
9614                  CheckFunctionTemplateSpecialization(
9615                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9616                      Previous))
9617         NewFD->setInvalidDecl();
9618 
9619       // C++ [dcl.stc]p1:
9620       //   A storage-class-specifier shall not be specified in an explicit
9621       //   specialization (14.7.3)
9622       FunctionTemplateSpecializationInfo *Info =
9623           NewFD->getTemplateSpecializationInfo();
9624       if (Info && SC != SC_None) {
9625         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9626           Diag(NewFD->getLocation(),
9627                diag::err_explicit_specialization_inconsistent_storage_class)
9628             << SC
9629             << FixItHint::CreateRemoval(
9630                                       D.getDeclSpec().getStorageClassSpecLoc());
9631 
9632         else
9633           Diag(NewFD->getLocation(),
9634                diag::ext_explicit_specialization_storage_class)
9635             << FixItHint::CreateRemoval(
9636                                       D.getDeclSpec().getStorageClassSpecLoc());
9637       }
9638     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9639       if (CheckMemberSpecialization(NewFD, Previous))
9640           NewFD->setInvalidDecl();
9641     }
9642 
9643     // Perform semantic checking on the function declaration.
9644     if (!isDependentClassScopeExplicitSpecialization) {
9645       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9646         CheckMain(NewFD, D.getDeclSpec());
9647 
9648       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9649         CheckMSVCRTEntryPoint(NewFD);
9650 
9651       if (!NewFD->isInvalidDecl())
9652         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9653                                                     isMemberSpecialization));
9654       else if (!Previous.empty())
9655         // Recover gracefully from an invalid redeclaration.
9656         D.setRedeclaration(true);
9657     }
9658 
9659     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9660             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9661            "previous declaration set still overloaded");
9662 
9663     NamedDecl *PrincipalDecl = (FunctionTemplate
9664                                 ? cast<NamedDecl>(FunctionTemplate)
9665                                 : NewFD);
9666 
9667     if (isFriend && NewFD->getPreviousDecl()) {
9668       AccessSpecifier Access = AS_public;
9669       if (!NewFD->isInvalidDecl())
9670         Access = NewFD->getPreviousDecl()->getAccess();
9671 
9672       NewFD->setAccess(Access);
9673       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9674     }
9675 
9676     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9677         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9678       PrincipalDecl->setNonMemberOperator();
9679 
9680     // If we have a function template, check the template parameter
9681     // list. This will check and merge default template arguments.
9682     if (FunctionTemplate) {
9683       FunctionTemplateDecl *PrevTemplate =
9684                                      FunctionTemplate->getPreviousDecl();
9685       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9686                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9687                                     : nullptr,
9688                             D.getDeclSpec().isFriendSpecified()
9689                               ? (D.isFunctionDefinition()
9690                                    ? TPC_FriendFunctionTemplateDefinition
9691                                    : TPC_FriendFunctionTemplate)
9692                               : (D.getCXXScopeSpec().isSet() &&
9693                                  DC && DC->isRecord() &&
9694                                  DC->isDependentContext())
9695                                   ? TPC_ClassTemplateMember
9696                                   : TPC_FunctionTemplate);
9697     }
9698 
9699     if (NewFD->isInvalidDecl()) {
9700       // Ignore all the rest of this.
9701     } else if (!D.isRedeclaration()) {
9702       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9703                                        AddToScope };
9704       // Fake up an access specifier if it's supposed to be a class member.
9705       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9706         NewFD->setAccess(AS_public);
9707 
9708       // Qualified decls generally require a previous declaration.
9709       if (D.getCXXScopeSpec().isSet()) {
9710         // ...with the major exception of templated-scope or
9711         // dependent-scope friend declarations.
9712 
9713         // TODO: we currently also suppress this check in dependent
9714         // contexts because (1) the parameter depth will be off when
9715         // matching friend templates and (2) we might actually be
9716         // selecting a friend based on a dependent factor.  But there
9717         // are situations where these conditions don't apply and we
9718         // can actually do this check immediately.
9719         //
9720         // Unless the scope is dependent, it's always an error if qualified
9721         // redeclaration lookup found nothing at all. Diagnose that now;
9722         // nothing will diagnose that error later.
9723         if (isFriend &&
9724             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9725              (!Previous.empty() && CurContext->isDependentContext()))) {
9726           // ignore these
9727         } else if (NewFD->isCPUDispatchMultiVersion() ||
9728                    NewFD->isCPUSpecificMultiVersion()) {
9729           // ignore this, we allow the redeclaration behavior here to create new
9730           // versions of the function.
9731         } else {
9732           // The user tried to provide an out-of-line definition for a
9733           // function that is a member of a class or namespace, but there
9734           // was no such member function declared (C++ [class.mfct]p2,
9735           // C++ [namespace.memdef]p2). For example:
9736           //
9737           // class X {
9738           //   void f() const;
9739           // };
9740           //
9741           // void X::f() { } // ill-formed
9742           //
9743           // Complain about this problem, and attempt to suggest close
9744           // matches (e.g., those that differ only in cv-qualifiers and
9745           // whether the parameter types are references).
9746 
9747           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9748                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9749             AddToScope = ExtraArgs.AddToScope;
9750             return Result;
9751           }
9752         }
9753 
9754         // Unqualified local friend declarations are required to resolve
9755         // to something.
9756       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9757         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9758                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9759           AddToScope = ExtraArgs.AddToScope;
9760           return Result;
9761         }
9762       }
9763     } else if (!D.isFunctionDefinition() &&
9764                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9765                !isFriend && !isFunctionTemplateSpecialization &&
9766                !isMemberSpecialization) {
9767       // An out-of-line member function declaration must also be a
9768       // definition (C++ [class.mfct]p2).
9769       // Note that this is not the case for explicit specializations of
9770       // function templates or member functions of class templates, per
9771       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9772       // extension for compatibility with old SWIG code which likes to
9773       // generate them.
9774       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9775         << D.getCXXScopeSpec().getRange();
9776     }
9777   }
9778 
9779   // If this is the first declaration of a library builtin function, add
9780   // attributes as appropriate.
9781   if (!D.isRedeclaration() &&
9782       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9783     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9784       if (unsigned BuiltinID = II->getBuiltinID()) {
9785         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9786           // Validate the type matches unless this builtin is specified as
9787           // matching regardless of its declared type.
9788           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9789             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9790           } else {
9791             ASTContext::GetBuiltinTypeError Error;
9792             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9793             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9794 
9795             if (!Error && !BuiltinType.isNull() &&
9796                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9797                     NewFD->getType(), BuiltinType))
9798               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9799           }
9800         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9801                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9802           // FIXME: We should consider this a builtin only in the std namespace.
9803           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9804         }
9805       }
9806     }
9807   }
9808 
9809   ProcessPragmaWeak(S, NewFD);
9810   checkAttributesAfterMerging(*this, *NewFD);
9811 
9812   AddKnownFunctionAttributes(NewFD);
9813 
9814   if (NewFD->hasAttr<OverloadableAttr>() &&
9815       !NewFD->getType()->getAs<FunctionProtoType>()) {
9816     Diag(NewFD->getLocation(),
9817          diag::err_attribute_overloadable_no_prototype)
9818       << NewFD;
9819 
9820     // Turn this into a variadic function with no parameters.
9821     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9822     FunctionProtoType::ExtProtoInfo EPI(
9823         Context.getDefaultCallingConvention(true, false));
9824     EPI.Variadic = true;
9825     EPI.ExtInfo = FT->getExtInfo();
9826 
9827     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9828     NewFD->setType(R);
9829   }
9830 
9831   // If there's a #pragma GCC visibility in scope, and this isn't a class
9832   // member, set the visibility of this function.
9833   if (!DC->isRecord() && NewFD->isExternallyVisible())
9834     AddPushedVisibilityAttribute(NewFD);
9835 
9836   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9837   // marking the function.
9838   AddCFAuditedAttribute(NewFD);
9839 
9840   // If this is a function definition, check if we have to apply optnone due to
9841   // a pragma.
9842   if(D.isFunctionDefinition())
9843     AddRangeBasedOptnone(NewFD);
9844 
9845   // If this is the first declaration of an extern C variable, update
9846   // the map of such variables.
9847   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9848       isIncompleteDeclExternC(*this, NewFD))
9849     RegisterLocallyScopedExternCDecl(NewFD, S);
9850 
9851   // Set this FunctionDecl's range up to the right paren.
9852   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9853 
9854   if (D.isRedeclaration() && !Previous.empty()) {
9855     NamedDecl *Prev = Previous.getRepresentativeDecl();
9856     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9857                                    isMemberSpecialization ||
9858                                        isFunctionTemplateSpecialization,
9859                                    D.isFunctionDefinition());
9860   }
9861 
9862   if (getLangOpts().CUDA) {
9863     IdentifierInfo *II = NewFD->getIdentifier();
9864     if (II && II->isStr(getCudaConfigureFuncName()) &&
9865         !NewFD->isInvalidDecl() &&
9866         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9867       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9868         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9869             << getCudaConfigureFuncName();
9870       Context.setcudaConfigureCallDecl(NewFD);
9871     }
9872 
9873     // Variadic functions, other than a *declaration* of printf, are not allowed
9874     // in device-side CUDA code, unless someone passed
9875     // -fcuda-allow-variadic-functions.
9876     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9877         (NewFD->hasAttr<CUDADeviceAttr>() ||
9878          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9879         !(II && II->isStr("printf") && NewFD->isExternC() &&
9880           !D.isFunctionDefinition())) {
9881       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9882     }
9883   }
9884 
9885   MarkUnusedFileScopedDecl(NewFD);
9886 
9887 
9888 
9889   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9890     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9891     if ((getLangOpts().OpenCLVersion >= 120)
9892         && (SC == SC_Static)) {
9893       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9894       D.setInvalidType();
9895     }
9896 
9897     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9898     if (!NewFD->getReturnType()->isVoidType()) {
9899       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9900       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9901           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9902                                 : FixItHint());
9903       D.setInvalidType();
9904     }
9905 
9906     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9907     for (auto Param : NewFD->parameters())
9908       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9909 
9910     if (getLangOpts().OpenCLCPlusPlus) {
9911       if (DC->isRecord()) {
9912         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9913         D.setInvalidType();
9914       }
9915       if (FunctionTemplate) {
9916         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9917         D.setInvalidType();
9918       }
9919     }
9920   }
9921 
9922   if (getLangOpts().CPlusPlus) {
9923     if (FunctionTemplate) {
9924       if (NewFD->isInvalidDecl())
9925         FunctionTemplate->setInvalidDecl();
9926       return FunctionTemplate;
9927     }
9928 
9929     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9930       CompleteMemberSpecialization(NewFD, Previous);
9931   }
9932 
9933   for (const ParmVarDecl *Param : NewFD->parameters()) {
9934     QualType PT = Param->getType();
9935 
9936     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9937     // types.
9938     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9939       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9940         QualType ElemTy = PipeTy->getElementType();
9941           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9942             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9943             D.setInvalidType();
9944           }
9945       }
9946     }
9947   }
9948 
9949   // Here we have an function template explicit specialization at class scope.
9950   // The actual specialization will be postponed to template instatiation
9951   // time via the ClassScopeFunctionSpecializationDecl node.
9952   if (isDependentClassScopeExplicitSpecialization) {
9953     ClassScopeFunctionSpecializationDecl *NewSpec =
9954                          ClassScopeFunctionSpecializationDecl::Create(
9955                                 Context, CurContext, NewFD->getLocation(),
9956                                 cast<CXXMethodDecl>(NewFD),
9957                                 HasExplicitTemplateArgs, TemplateArgs);
9958     CurContext->addDecl(NewSpec);
9959     AddToScope = false;
9960   }
9961 
9962   // Diagnose availability attributes. Availability cannot be used on functions
9963   // that are run during load/unload.
9964   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9965     if (NewFD->hasAttr<ConstructorAttr>()) {
9966       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9967           << 1;
9968       NewFD->dropAttr<AvailabilityAttr>();
9969     }
9970     if (NewFD->hasAttr<DestructorAttr>()) {
9971       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9972           << 2;
9973       NewFD->dropAttr<AvailabilityAttr>();
9974     }
9975   }
9976 
9977   // Diagnose no_builtin attribute on function declaration that are not a
9978   // definition.
9979   // FIXME: We should really be doing this in
9980   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9981   // the FunctionDecl and at this point of the code
9982   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9983   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9984   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9985     switch (D.getFunctionDefinitionKind()) {
9986     case FunctionDefinitionKind::Defaulted:
9987     case FunctionDefinitionKind::Deleted:
9988       Diag(NBA->getLocation(),
9989            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9990           << NBA->getSpelling();
9991       break;
9992     case FunctionDefinitionKind::Declaration:
9993       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9994           << NBA->getSpelling();
9995       break;
9996     case FunctionDefinitionKind::Definition:
9997       break;
9998     }
9999 
10000   return NewFD;
10001 }
10002 
10003 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10004 /// when __declspec(code_seg) "is applied to a class, all member functions of
10005 /// the class and nested classes -- this includes compiler-generated special
10006 /// member functions -- are put in the specified segment."
10007 /// The actual behavior is a little more complicated. The Microsoft compiler
10008 /// won't check outer classes if there is an active value from #pragma code_seg.
10009 /// The CodeSeg is always applied from the direct parent but only from outer
10010 /// classes when the #pragma code_seg stack is empty. See:
10011 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10012 /// available since MS has removed the page.
10013 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10014   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10015   if (!Method)
10016     return nullptr;
10017   const CXXRecordDecl *Parent = Method->getParent();
10018   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10019     Attr *NewAttr = SAttr->clone(S.getASTContext());
10020     NewAttr->setImplicit(true);
10021     return NewAttr;
10022   }
10023 
10024   // The Microsoft compiler won't check outer classes for the CodeSeg
10025   // when the #pragma code_seg stack is active.
10026   if (S.CodeSegStack.CurrentValue)
10027    return nullptr;
10028 
10029   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10030     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10031       Attr *NewAttr = SAttr->clone(S.getASTContext());
10032       NewAttr->setImplicit(true);
10033       return NewAttr;
10034     }
10035   }
10036   return nullptr;
10037 }
10038 
10039 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10040 /// containing class. Otherwise it will return implicit SectionAttr if the
10041 /// function is a definition and there is an active value on CodeSegStack
10042 /// (from the current #pragma code-seg value).
10043 ///
10044 /// \param FD Function being declared.
10045 /// \param IsDefinition Whether it is a definition or just a declarartion.
10046 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10047 ///          nullptr if no attribute should be added.
10048 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10049                                                        bool IsDefinition) {
10050   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10051     return A;
10052   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10053       CodeSegStack.CurrentValue)
10054     return SectionAttr::CreateImplicit(
10055         getASTContext(), CodeSegStack.CurrentValue->getString(),
10056         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10057         SectionAttr::Declspec_allocate);
10058   return nullptr;
10059 }
10060 
10061 /// Determines if we can perform a correct type check for \p D as a
10062 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10063 /// best-effort check.
10064 ///
10065 /// \param NewD The new declaration.
10066 /// \param OldD The old declaration.
10067 /// \param NewT The portion of the type of the new declaration to check.
10068 /// \param OldT The portion of the type of the old declaration to check.
10069 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10070                                           QualType NewT, QualType OldT) {
10071   if (!NewD->getLexicalDeclContext()->isDependentContext())
10072     return true;
10073 
10074   // For dependently-typed local extern declarations and friends, we can't
10075   // perform a correct type check in general until instantiation:
10076   //
10077   //   int f();
10078   //   template<typename T> void g() { T f(); }
10079   //
10080   // (valid if g() is only instantiated with T = int).
10081   if (NewT->isDependentType() &&
10082       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10083     return false;
10084 
10085   // Similarly, if the previous declaration was a dependent local extern
10086   // declaration, we don't really know its type yet.
10087   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10088     return false;
10089 
10090   return true;
10091 }
10092 
10093 /// Checks if the new declaration declared in dependent context must be
10094 /// put in the same redeclaration chain as the specified declaration.
10095 ///
10096 /// \param D Declaration that is checked.
10097 /// \param PrevDecl Previous declaration found with proper lookup method for the
10098 ///                 same declaration name.
10099 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10100 ///          belongs to.
10101 ///
10102 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10103   if (!D->getLexicalDeclContext()->isDependentContext())
10104     return true;
10105 
10106   // Don't chain dependent friend function definitions until instantiation, to
10107   // permit cases like
10108   //
10109   //   void func();
10110   //   template<typename T> class C1 { friend void func() {} };
10111   //   template<typename T> class C2 { friend void func() {} };
10112   //
10113   // ... which is valid if only one of C1 and C2 is ever instantiated.
10114   //
10115   // FIXME: This need only apply to function definitions. For now, we proxy
10116   // this by checking for a file-scope function. We do not want this to apply
10117   // to friend declarations nominating member functions, because that gets in
10118   // the way of access checks.
10119   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10120     return false;
10121 
10122   auto *VD = dyn_cast<ValueDecl>(D);
10123   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10124   return !VD || !PrevVD ||
10125          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10126                                         PrevVD->getType());
10127 }
10128 
10129 /// Check the target attribute of the function for MultiVersion
10130 /// validity.
10131 ///
10132 /// Returns true if there was an error, false otherwise.
10133 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10134   const auto *TA = FD->getAttr<TargetAttr>();
10135   assert(TA && "MultiVersion Candidate requires a target attribute");
10136   ParsedTargetAttr ParseInfo = TA->parse();
10137   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10138   enum ErrType { Feature = 0, Architecture = 1 };
10139 
10140   if (!ParseInfo.Architecture.empty() &&
10141       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10142     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10143         << Architecture << ParseInfo.Architecture;
10144     return true;
10145   }
10146 
10147   for (const auto &Feat : ParseInfo.Features) {
10148     auto BareFeat = StringRef{Feat}.substr(1);
10149     if (Feat[0] == '-') {
10150       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10151           << Feature << ("no-" + BareFeat).str();
10152       return true;
10153     }
10154 
10155     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10156         !TargetInfo.isValidFeatureName(BareFeat)) {
10157       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10158           << Feature << BareFeat;
10159       return true;
10160     }
10161   }
10162   return false;
10163 }
10164 
10165 // Provide a white-list of attributes that are allowed to be combined with
10166 // multiversion functions.
10167 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10168                                            MultiVersionKind MVType) {
10169   // Note: this list/diagnosis must match the list in
10170   // checkMultiversionAttributesAllSame.
10171   switch (Kind) {
10172   default:
10173     return false;
10174   case attr::Used:
10175     return MVType == MultiVersionKind::Target;
10176   case attr::NonNull:
10177   case attr::NoThrow:
10178     return true;
10179   }
10180 }
10181 
10182 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10183                                                  const FunctionDecl *FD,
10184                                                  const FunctionDecl *CausedFD,
10185                                                  MultiVersionKind MVType) {
10186   bool IsCPUSpecificCPUDispatchMVType =
10187       MVType == MultiVersionKind::CPUDispatch ||
10188       MVType == MultiVersionKind::CPUSpecific;
10189   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10190                             Sema &S, const Attr *A) {
10191     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10192         << IsCPUSpecificCPUDispatchMVType << A;
10193     if (CausedFD)
10194       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10195     return true;
10196   };
10197 
10198   for (const Attr *A : FD->attrs()) {
10199     switch (A->getKind()) {
10200     case attr::CPUDispatch:
10201     case attr::CPUSpecific:
10202       if (MVType != MultiVersionKind::CPUDispatch &&
10203           MVType != MultiVersionKind::CPUSpecific)
10204         return Diagnose(S, A);
10205       break;
10206     case attr::Target:
10207       if (MVType != MultiVersionKind::Target)
10208         return Diagnose(S, A);
10209       break;
10210     default:
10211       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10212         return Diagnose(S, A);
10213       break;
10214     }
10215   }
10216   return false;
10217 }
10218 
10219 bool Sema::areMultiversionVariantFunctionsCompatible(
10220     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10221     const PartialDiagnostic &NoProtoDiagID,
10222     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10223     const PartialDiagnosticAt &NoSupportDiagIDAt,
10224     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10225     bool ConstexprSupported, bool CLinkageMayDiffer) {
10226   enum DoesntSupport {
10227     FuncTemplates = 0,
10228     VirtFuncs = 1,
10229     DeducedReturn = 2,
10230     Constructors = 3,
10231     Destructors = 4,
10232     DeletedFuncs = 5,
10233     DefaultedFuncs = 6,
10234     ConstexprFuncs = 7,
10235     ConstevalFuncs = 8,
10236   };
10237   enum Different {
10238     CallingConv = 0,
10239     ReturnType = 1,
10240     ConstexprSpec = 2,
10241     InlineSpec = 3,
10242     StorageClass = 4,
10243     Linkage = 5,
10244   };
10245 
10246   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10247       !OldFD->getType()->getAs<FunctionProtoType>()) {
10248     Diag(OldFD->getLocation(), NoProtoDiagID);
10249     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10250     return true;
10251   }
10252 
10253   if (NoProtoDiagID.getDiagID() != 0 &&
10254       !NewFD->getType()->getAs<FunctionProtoType>())
10255     return Diag(NewFD->getLocation(), NoProtoDiagID);
10256 
10257   if (!TemplatesSupported &&
10258       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10259     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10260            << FuncTemplates;
10261 
10262   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10263     if (NewCXXFD->isVirtual())
10264       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10265              << VirtFuncs;
10266 
10267     if (isa<CXXConstructorDecl>(NewCXXFD))
10268       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10269              << Constructors;
10270 
10271     if (isa<CXXDestructorDecl>(NewCXXFD))
10272       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10273              << Destructors;
10274   }
10275 
10276   if (NewFD->isDeleted())
10277     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10278            << DeletedFuncs;
10279 
10280   if (NewFD->isDefaulted())
10281     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10282            << DefaultedFuncs;
10283 
10284   if (!ConstexprSupported && NewFD->isConstexpr())
10285     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10286            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10287 
10288   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10289   const auto *NewType = cast<FunctionType>(NewQType);
10290   QualType NewReturnType = NewType->getReturnType();
10291 
10292   if (NewReturnType->isUndeducedType())
10293     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10294            << DeducedReturn;
10295 
10296   // Ensure the return type is identical.
10297   if (OldFD) {
10298     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10299     const auto *OldType = cast<FunctionType>(OldQType);
10300     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10301     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10302 
10303     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10304       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10305 
10306     QualType OldReturnType = OldType->getReturnType();
10307 
10308     if (OldReturnType != NewReturnType)
10309       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10310 
10311     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10312       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10313 
10314     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10315       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10316 
10317     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10318       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10319 
10320     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10321       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10322 
10323     if (CheckEquivalentExceptionSpec(
10324             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10325             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10326       return true;
10327   }
10328   return false;
10329 }
10330 
10331 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10332                                              const FunctionDecl *NewFD,
10333                                              bool CausesMV,
10334                                              MultiVersionKind MVType) {
10335   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10336     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10337     if (OldFD)
10338       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10339     return true;
10340   }
10341 
10342   bool IsCPUSpecificCPUDispatchMVType =
10343       MVType == MultiVersionKind::CPUDispatch ||
10344       MVType == MultiVersionKind::CPUSpecific;
10345 
10346   if (CausesMV && OldFD &&
10347       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10348     return true;
10349 
10350   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10351     return true;
10352 
10353   // Only allow transition to MultiVersion if it hasn't been used.
10354   if (OldFD && CausesMV && OldFD->isUsed(false))
10355     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10356 
10357   return S.areMultiversionVariantFunctionsCompatible(
10358       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10359       PartialDiagnosticAt(NewFD->getLocation(),
10360                           S.PDiag(diag::note_multiversioning_caused_here)),
10361       PartialDiagnosticAt(NewFD->getLocation(),
10362                           S.PDiag(diag::err_multiversion_doesnt_support)
10363                               << IsCPUSpecificCPUDispatchMVType),
10364       PartialDiagnosticAt(NewFD->getLocation(),
10365                           S.PDiag(diag::err_multiversion_diff)),
10366       /*TemplatesSupported=*/false,
10367       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10368       /*CLinkageMayDiffer=*/false);
10369 }
10370 
10371 /// Check the validity of a multiversion function declaration that is the
10372 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10373 ///
10374 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10375 ///
10376 /// Returns true if there was an error, false otherwise.
10377 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10378                                            MultiVersionKind MVType,
10379                                            const TargetAttr *TA) {
10380   assert(MVType != MultiVersionKind::None &&
10381          "Function lacks multiversion attribute");
10382 
10383   // Target only causes MV if it is default, otherwise this is a normal
10384   // function.
10385   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10386     return false;
10387 
10388   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10389     FD->setInvalidDecl();
10390     return true;
10391   }
10392 
10393   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10394     FD->setInvalidDecl();
10395     return true;
10396   }
10397 
10398   FD->setIsMultiVersion();
10399   return false;
10400 }
10401 
10402 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10403   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10404     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10405       return true;
10406   }
10407 
10408   return false;
10409 }
10410 
10411 static bool CheckTargetCausesMultiVersioning(
10412     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10413     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10414     LookupResult &Previous) {
10415   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10416   ParsedTargetAttr NewParsed = NewTA->parse();
10417   // Sort order doesn't matter, it just needs to be consistent.
10418   llvm::sort(NewParsed.Features);
10419 
10420   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10421   // to change, this is a simple redeclaration.
10422   if (!NewTA->isDefaultVersion() &&
10423       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10424     return false;
10425 
10426   // Otherwise, this decl causes MultiVersioning.
10427   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10428     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10429     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10430     NewFD->setInvalidDecl();
10431     return true;
10432   }
10433 
10434   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10435                                        MultiVersionKind::Target)) {
10436     NewFD->setInvalidDecl();
10437     return true;
10438   }
10439 
10440   if (CheckMultiVersionValue(S, NewFD)) {
10441     NewFD->setInvalidDecl();
10442     return true;
10443   }
10444 
10445   // If this is 'default', permit the forward declaration.
10446   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10447     Redeclaration = true;
10448     OldDecl = OldFD;
10449     OldFD->setIsMultiVersion();
10450     NewFD->setIsMultiVersion();
10451     return false;
10452   }
10453 
10454   if (CheckMultiVersionValue(S, OldFD)) {
10455     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10456     NewFD->setInvalidDecl();
10457     return true;
10458   }
10459 
10460   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10461 
10462   if (OldParsed == NewParsed) {
10463     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10464     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10465     NewFD->setInvalidDecl();
10466     return true;
10467   }
10468 
10469   for (const auto *FD : OldFD->redecls()) {
10470     const auto *CurTA = FD->getAttr<TargetAttr>();
10471     // We allow forward declarations before ANY multiversioning attributes, but
10472     // nothing after the fact.
10473     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10474         (!CurTA || CurTA->isInherited())) {
10475       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10476           << 0;
10477       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10478       NewFD->setInvalidDecl();
10479       return true;
10480     }
10481   }
10482 
10483   OldFD->setIsMultiVersion();
10484   NewFD->setIsMultiVersion();
10485   Redeclaration = false;
10486   MergeTypeWithPrevious = false;
10487   OldDecl = nullptr;
10488   Previous.clear();
10489   return false;
10490 }
10491 
10492 /// Check the validity of a new function declaration being added to an existing
10493 /// multiversioned declaration collection.
10494 static bool CheckMultiVersionAdditionalDecl(
10495     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10496     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10497     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10498     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10499     LookupResult &Previous) {
10500 
10501   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10502   // Disallow mixing of multiversioning types.
10503   if ((OldMVType == MultiVersionKind::Target &&
10504        NewMVType != MultiVersionKind::Target) ||
10505       (NewMVType == MultiVersionKind::Target &&
10506        OldMVType != MultiVersionKind::Target)) {
10507     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10508     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10509     NewFD->setInvalidDecl();
10510     return true;
10511   }
10512 
10513   ParsedTargetAttr NewParsed;
10514   if (NewTA) {
10515     NewParsed = NewTA->parse();
10516     llvm::sort(NewParsed.Features);
10517   }
10518 
10519   bool UseMemberUsingDeclRules =
10520       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10521 
10522   // Next, check ALL non-overloads to see if this is a redeclaration of a
10523   // previous member of the MultiVersion set.
10524   for (NamedDecl *ND : Previous) {
10525     FunctionDecl *CurFD = ND->getAsFunction();
10526     if (!CurFD)
10527       continue;
10528     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10529       continue;
10530 
10531     if (NewMVType == MultiVersionKind::Target) {
10532       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10533       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10534         NewFD->setIsMultiVersion();
10535         Redeclaration = true;
10536         OldDecl = ND;
10537         return false;
10538       }
10539 
10540       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10541       if (CurParsed == NewParsed) {
10542         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10543         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10544         NewFD->setInvalidDecl();
10545         return true;
10546       }
10547     } else {
10548       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10549       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10550       // Handle CPUDispatch/CPUSpecific versions.
10551       // Only 1 CPUDispatch function is allowed, this will make it go through
10552       // the redeclaration errors.
10553       if (NewMVType == MultiVersionKind::CPUDispatch &&
10554           CurFD->hasAttr<CPUDispatchAttr>()) {
10555         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10556             std::equal(
10557                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10558                 NewCPUDisp->cpus_begin(),
10559                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10560                   return Cur->getName() == New->getName();
10561                 })) {
10562           NewFD->setIsMultiVersion();
10563           Redeclaration = true;
10564           OldDecl = ND;
10565           return false;
10566         }
10567 
10568         // If the declarations don't match, this is an error condition.
10569         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10570         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10571         NewFD->setInvalidDecl();
10572         return true;
10573       }
10574       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10575 
10576         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10577             std::equal(
10578                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10579                 NewCPUSpec->cpus_begin(),
10580                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10581                   return Cur->getName() == New->getName();
10582                 })) {
10583           NewFD->setIsMultiVersion();
10584           Redeclaration = true;
10585           OldDecl = ND;
10586           return false;
10587         }
10588 
10589         // Only 1 version of CPUSpecific is allowed for each CPU.
10590         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10591           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10592             if (CurII == NewII) {
10593               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10594                   << NewII;
10595               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10596               NewFD->setInvalidDecl();
10597               return true;
10598             }
10599           }
10600         }
10601       }
10602       // If the two decls aren't the same MVType, there is no possible error
10603       // condition.
10604     }
10605   }
10606 
10607   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10608   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10609   // handled in the attribute adding step.
10610   if (NewMVType == MultiVersionKind::Target &&
10611       CheckMultiVersionValue(S, NewFD)) {
10612     NewFD->setInvalidDecl();
10613     return true;
10614   }
10615 
10616   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10617                                        !OldFD->isMultiVersion(), NewMVType)) {
10618     NewFD->setInvalidDecl();
10619     return true;
10620   }
10621 
10622   // Permit forward declarations in the case where these two are compatible.
10623   if (!OldFD->isMultiVersion()) {
10624     OldFD->setIsMultiVersion();
10625     NewFD->setIsMultiVersion();
10626     Redeclaration = true;
10627     OldDecl = OldFD;
10628     return false;
10629   }
10630 
10631   NewFD->setIsMultiVersion();
10632   Redeclaration = false;
10633   MergeTypeWithPrevious = false;
10634   OldDecl = nullptr;
10635   Previous.clear();
10636   return false;
10637 }
10638 
10639 
10640 /// Check the validity of a mulitversion function declaration.
10641 /// Also sets the multiversion'ness' of the function itself.
10642 ///
10643 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10644 ///
10645 /// Returns true if there was an error, false otherwise.
10646 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10647                                       bool &Redeclaration, NamedDecl *&OldDecl,
10648                                       bool &MergeTypeWithPrevious,
10649                                       LookupResult &Previous) {
10650   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10651   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10652   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10653 
10654   // Mixing Multiversioning types is prohibited.
10655   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10656       (NewCPUDisp && NewCPUSpec)) {
10657     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10658     NewFD->setInvalidDecl();
10659     return true;
10660   }
10661 
10662   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10663 
10664   // Main isn't allowed to become a multiversion function, however it IS
10665   // permitted to have 'main' be marked with the 'target' optimization hint.
10666   if (NewFD->isMain()) {
10667     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10668         MVType == MultiVersionKind::CPUDispatch ||
10669         MVType == MultiVersionKind::CPUSpecific) {
10670       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10671       NewFD->setInvalidDecl();
10672       return true;
10673     }
10674     return false;
10675   }
10676 
10677   if (!OldDecl || !OldDecl->getAsFunction() ||
10678       OldDecl->getDeclContext()->getRedeclContext() !=
10679           NewFD->getDeclContext()->getRedeclContext()) {
10680     // If there's no previous declaration, AND this isn't attempting to cause
10681     // multiversioning, this isn't an error condition.
10682     if (MVType == MultiVersionKind::None)
10683       return false;
10684     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10685   }
10686 
10687   FunctionDecl *OldFD = OldDecl->getAsFunction();
10688 
10689   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10690     return false;
10691 
10692   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10693     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10694         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10695     NewFD->setInvalidDecl();
10696     return true;
10697   }
10698 
10699   // Handle the target potentially causes multiversioning case.
10700   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10701     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10702                                             Redeclaration, OldDecl,
10703                                             MergeTypeWithPrevious, Previous);
10704 
10705   // At this point, we have a multiversion function decl (in OldFD) AND an
10706   // appropriate attribute in the current function decl.  Resolve that these are
10707   // still compatible with previous declarations.
10708   return CheckMultiVersionAdditionalDecl(
10709       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10710       OldDecl, MergeTypeWithPrevious, Previous);
10711 }
10712 
10713 /// Perform semantic checking of a new function declaration.
10714 ///
10715 /// Performs semantic analysis of the new function declaration
10716 /// NewFD. This routine performs all semantic checking that does not
10717 /// require the actual declarator involved in the declaration, and is
10718 /// used both for the declaration of functions as they are parsed
10719 /// (called via ActOnDeclarator) and for the declaration of functions
10720 /// that have been instantiated via C++ template instantiation (called
10721 /// via InstantiateDecl).
10722 ///
10723 /// \param IsMemberSpecialization whether this new function declaration is
10724 /// a member specialization (that replaces any definition provided by the
10725 /// previous declaration).
10726 ///
10727 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10728 ///
10729 /// \returns true if the function declaration is a redeclaration.
10730 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10731                                     LookupResult &Previous,
10732                                     bool IsMemberSpecialization) {
10733   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10734          "Variably modified return types are not handled here");
10735 
10736   // Determine whether the type of this function should be merged with
10737   // a previous visible declaration. This never happens for functions in C++,
10738   // and always happens in C if the previous declaration was visible.
10739   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10740                                !Previous.isShadowed();
10741 
10742   bool Redeclaration = false;
10743   NamedDecl *OldDecl = nullptr;
10744   bool MayNeedOverloadableChecks = false;
10745 
10746   // Merge or overload the declaration with an existing declaration of
10747   // the same name, if appropriate.
10748   if (!Previous.empty()) {
10749     // Determine whether NewFD is an overload of PrevDecl or
10750     // a declaration that requires merging. If it's an overload,
10751     // there's no more work to do here; we'll just add the new
10752     // function to the scope.
10753     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10754       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10755       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10756         Redeclaration = true;
10757         OldDecl = Candidate;
10758       }
10759     } else {
10760       MayNeedOverloadableChecks = true;
10761       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10762                             /*NewIsUsingDecl*/ false)) {
10763       case Ovl_Match:
10764         Redeclaration = true;
10765         break;
10766 
10767       case Ovl_NonFunction:
10768         Redeclaration = true;
10769         break;
10770 
10771       case Ovl_Overload:
10772         Redeclaration = false;
10773         break;
10774       }
10775     }
10776   }
10777 
10778   // Check for a previous extern "C" declaration with this name.
10779   if (!Redeclaration &&
10780       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10781     if (!Previous.empty()) {
10782       // This is an extern "C" declaration with the same name as a previous
10783       // declaration, and thus redeclares that entity...
10784       Redeclaration = true;
10785       OldDecl = Previous.getFoundDecl();
10786       MergeTypeWithPrevious = false;
10787 
10788       // ... except in the presence of __attribute__((overloadable)).
10789       if (OldDecl->hasAttr<OverloadableAttr>() ||
10790           NewFD->hasAttr<OverloadableAttr>()) {
10791         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10792           MayNeedOverloadableChecks = true;
10793           Redeclaration = false;
10794           OldDecl = nullptr;
10795         }
10796       }
10797     }
10798   }
10799 
10800   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10801                                 MergeTypeWithPrevious, Previous))
10802     return Redeclaration;
10803 
10804   // PPC MMA non-pointer types are not allowed as function return types.
10805   if (Context.getTargetInfo().getTriple().isPPC64() &&
10806       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10807     NewFD->setInvalidDecl();
10808   }
10809 
10810   // C++11 [dcl.constexpr]p8:
10811   //   A constexpr specifier for a non-static member function that is not
10812   //   a constructor declares that member function to be const.
10813   //
10814   // This needs to be delayed until we know whether this is an out-of-line
10815   // definition of a static member function.
10816   //
10817   // This rule is not present in C++1y, so we produce a backwards
10818   // compatibility warning whenever it happens in C++11.
10819   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10820   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10821       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10822       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10823     CXXMethodDecl *OldMD = nullptr;
10824     if (OldDecl)
10825       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10826     if (!OldMD || !OldMD->isStatic()) {
10827       const FunctionProtoType *FPT =
10828         MD->getType()->castAs<FunctionProtoType>();
10829       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10830       EPI.TypeQuals.addConst();
10831       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10832                                           FPT->getParamTypes(), EPI));
10833 
10834       // Warn that we did this, if we're not performing template instantiation.
10835       // In that case, we'll have warned already when the template was defined.
10836       if (!inTemplateInstantiation()) {
10837         SourceLocation AddConstLoc;
10838         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10839                 .IgnoreParens().getAs<FunctionTypeLoc>())
10840           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10841 
10842         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10843           << FixItHint::CreateInsertion(AddConstLoc, " const");
10844       }
10845     }
10846   }
10847 
10848   if (Redeclaration) {
10849     // NewFD and OldDecl represent declarations that need to be
10850     // merged.
10851     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10852       NewFD->setInvalidDecl();
10853       return Redeclaration;
10854     }
10855 
10856     Previous.clear();
10857     Previous.addDecl(OldDecl);
10858 
10859     if (FunctionTemplateDecl *OldTemplateDecl =
10860             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10861       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10862       FunctionTemplateDecl *NewTemplateDecl
10863         = NewFD->getDescribedFunctionTemplate();
10864       assert(NewTemplateDecl && "Template/non-template mismatch");
10865 
10866       // The call to MergeFunctionDecl above may have created some state in
10867       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10868       // can add it as a redeclaration.
10869       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10870 
10871       NewFD->setPreviousDeclaration(OldFD);
10872       if (NewFD->isCXXClassMember()) {
10873         NewFD->setAccess(OldTemplateDecl->getAccess());
10874         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10875       }
10876 
10877       // If this is an explicit specialization of a member that is a function
10878       // template, mark it as a member specialization.
10879       if (IsMemberSpecialization &&
10880           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10881         NewTemplateDecl->setMemberSpecialization();
10882         assert(OldTemplateDecl->isMemberSpecialization());
10883         // Explicit specializations of a member template do not inherit deleted
10884         // status from the parent member template that they are specializing.
10885         if (OldFD->isDeleted()) {
10886           // FIXME: This assert will not hold in the presence of modules.
10887           assert(OldFD->getCanonicalDecl() == OldFD);
10888           // FIXME: We need an update record for this AST mutation.
10889           OldFD->setDeletedAsWritten(false);
10890         }
10891       }
10892 
10893     } else {
10894       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10895         auto *OldFD = cast<FunctionDecl>(OldDecl);
10896         // This needs to happen first so that 'inline' propagates.
10897         NewFD->setPreviousDeclaration(OldFD);
10898         if (NewFD->isCXXClassMember())
10899           NewFD->setAccess(OldFD->getAccess());
10900       }
10901     }
10902   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10903              !NewFD->getAttr<OverloadableAttr>()) {
10904     assert((Previous.empty() ||
10905             llvm::any_of(Previous,
10906                          [](const NamedDecl *ND) {
10907                            return ND->hasAttr<OverloadableAttr>();
10908                          })) &&
10909            "Non-redecls shouldn't happen without overloadable present");
10910 
10911     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10912       const auto *FD = dyn_cast<FunctionDecl>(ND);
10913       return FD && !FD->hasAttr<OverloadableAttr>();
10914     });
10915 
10916     if (OtherUnmarkedIter != Previous.end()) {
10917       Diag(NewFD->getLocation(),
10918            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10919       Diag((*OtherUnmarkedIter)->getLocation(),
10920            diag::note_attribute_overloadable_prev_overload)
10921           << false;
10922 
10923       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10924     }
10925   }
10926 
10927   if (LangOpts.OpenMP)
10928     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10929 
10930   // Semantic checking for this function declaration (in isolation).
10931 
10932   if (getLangOpts().CPlusPlus) {
10933     // C++-specific checks.
10934     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10935       CheckConstructor(Constructor);
10936     } else if (CXXDestructorDecl *Destructor =
10937                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10938       CXXRecordDecl *Record = Destructor->getParent();
10939       QualType ClassType = Context.getTypeDeclType(Record);
10940 
10941       // FIXME: Shouldn't we be able to perform this check even when the class
10942       // type is dependent? Both gcc and edg can handle that.
10943       if (!ClassType->isDependentType()) {
10944         DeclarationName Name
10945           = Context.DeclarationNames.getCXXDestructorName(
10946                                         Context.getCanonicalType(ClassType));
10947         if (NewFD->getDeclName() != Name) {
10948           Diag(NewFD->getLocation(), diag::err_destructor_name);
10949           NewFD->setInvalidDecl();
10950           return Redeclaration;
10951         }
10952       }
10953     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10954       if (auto *TD = Guide->getDescribedFunctionTemplate())
10955         CheckDeductionGuideTemplate(TD);
10956 
10957       // A deduction guide is not on the list of entities that can be
10958       // explicitly specialized.
10959       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10960         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10961             << /*explicit specialization*/ 1;
10962     }
10963 
10964     // Find any virtual functions that this function overrides.
10965     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10966       if (!Method->isFunctionTemplateSpecialization() &&
10967           !Method->getDescribedFunctionTemplate() &&
10968           Method->isCanonicalDecl()) {
10969         AddOverriddenMethods(Method->getParent(), Method);
10970       }
10971       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10972         // C++2a [class.virtual]p6
10973         // A virtual method shall not have a requires-clause.
10974         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10975              diag::err_constrained_virtual_method);
10976 
10977       if (Method->isStatic())
10978         checkThisInStaticMemberFunctionType(Method);
10979     }
10980 
10981     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10982       ActOnConversionDeclarator(Conversion);
10983 
10984     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10985     if (NewFD->isOverloadedOperator() &&
10986         CheckOverloadedOperatorDeclaration(NewFD)) {
10987       NewFD->setInvalidDecl();
10988       return Redeclaration;
10989     }
10990 
10991     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10992     if (NewFD->getLiteralIdentifier() &&
10993         CheckLiteralOperatorDeclaration(NewFD)) {
10994       NewFD->setInvalidDecl();
10995       return Redeclaration;
10996     }
10997 
10998     // In C++, check default arguments now that we have merged decls. Unless
10999     // the lexical context is the class, because in this case this is done
11000     // during delayed parsing anyway.
11001     if (!CurContext->isRecord())
11002       CheckCXXDefaultArguments(NewFD);
11003 
11004     // If this function is declared as being extern "C", then check to see if
11005     // the function returns a UDT (class, struct, or union type) that is not C
11006     // compatible, and if it does, warn the user.
11007     // But, issue any diagnostic on the first declaration only.
11008     if (Previous.empty() && NewFD->isExternC()) {
11009       QualType R = NewFD->getReturnType();
11010       if (R->isIncompleteType() && !R->isVoidType())
11011         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11012             << NewFD << R;
11013       else if (!R.isPODType(Context) && !R->isVoidType() &&
11014                !R->isObjCObjectPointerType())
11015         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11016     }
11017 
11018     // C++1z [dcl.fct]p6:
11019     //   [...] whether the function has a non-throwing exception-specification
11020     //   [is] part of the function type
11021     //
11022     // This results in an ABI break between C++14 and C++17 for functions whose
11023     // declared type includes an exception-specification in a parameter or
11024     // return type. (Exception specifications on the function itself are OK in
11025     // most cases, and exception specifications are not permitted in most other
11026     // contexts where they could make it into a mangling.)
11027     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11028       auto HasNoexcept = [&](QualType T) -> bool {
11029         // Strip off declarator chunks that could be between us and a function
11030         // type. We don't need to look far, exception specifications are very
11031         // restricted prior to C++17.
11032         if (auto *RT = T->getAs<ReferenceType>())
11033           T = RT->getPointeeType();
11034         else if (T->isAnyPointerType())
11035           T = T->getPointeeType();
11036         else if (auto *MPT = T->getAs<MemberPointerType>())
11037           T = MPT->getPointeeType();
11038         if (auto *FPT = T->getAs<FunctionProtoType>())
11039           if (FPT->isNothrow())
11040             return true;
11041         return false;
11042       };
11043 
11044       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11045       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11046       for (QualType T : FPT->param_types())
11047         AnyNoexcept |= HasNoexcept(T);
11048       if (AnyNoexcept)
11049         Diag(NewFD->getLocation(),
11050              diag::warn_cxx17_compat_exception_spec_in_signature)
11051             << NewFD;
11052     }
11053 
11054     if (!Redeclaration && LangOpts.CUDA)
11055       checkCUDATargetOverload(NewFD, Previous);
11056   }
11057   return Redeclaration;
11058 }
11059 
11060 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11061   // C++11 [basic.start.main]p3:
11062   //   A program that [...] declares main to be inline, static or
11063   //   constexpr is ill-formed.
11064   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11065   //   appear in a declaration of main.
11066   // static main is not an error under C99, but we should warn about it.
11067   // We accept _Noreturn main as an extension.
11068   if (FD->getStorageClass() == SC_Static)
11069     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11070          ? diag::err_static_main : diag::warn_static_main)
11071       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11072   if (FD->isInlineSpecified())
11073     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11074       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11075   if (DS.isNoreturnSpecified()) {
11076     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11077     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11078     Diag(NoreturnLoc, diag::ext_noreturn_main);
11079     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11080       << FixItHint::CreateRemoval(NoreturnRange);
11081   }
11082   if (FD->isConstexpr()) {
11083     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11084         << FD->isConsteval()
11085         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11086     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11087   }
11088 
11089   if (getLangOpts().OpenCL) {
11090     Diag(FD->getLocation(), diag::err_opencl_no_main)
11091         << FD->hasAttr<OpenCLKernelAttr>();
11092     FD->setInvalidDecl();
11093     return;
11094   }
11095 
11096   QualType T = FD->getType();
11097   assert(T->isFunctionType() && "function decl is not of function type");
11098   const FunctionType* FT = T->castAs<FunctionType>();
11099 
11100   // Set default calling convention for main()
11101   if (FT->getCallConv() != CC_C) {
11102     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11103     FD->setType(QualType(FT, 0));
11104     T = Context.getCanonicalType(FD->getType());
11105   }
11106 
11107   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11108     // In C with GNU extensions we allow main() to have non-integer return
11109     // type, but we should warn about the extension, and we disable the
11110     // implicit-return-zero rule.
11111 
11112     // GCC in C mode accepts qualified 'int'.
11113     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11114       FD->setHasImplicitReturnZero(true);
11115     else {
11116       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11117       SourceRange RTRange = FD->getReturnTypeSourceRange();
11118       if (RTRange.isValid())
11119         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11120             << FixItHint::CreateReplacement(RTRange, "int");
11121     }
11122   } else {
11123     // In C and C++, main magically returns 0 if you fall off the end;
11124     // set the flag which tells us that.
11125     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11126 
11127     // All the standards say that main() should return 'int'.
11128     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11129       FD->setHasImplicitReturnZero(true);
11130     else {
11131       // Otherwise, this is just a flat-out error.
11132       SourceRange RTRange = FD->getReturnTypeSourceRange();
11133       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11134           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11135                                 : FixItHint());
11136       FD->setInvalidDecl(true);
11137     }
11138   }
11139 
11140   // Treat protoless main() as nullary.
11141   if (isa<FunctionNoProtoType>(FT)) return;
11142 
11143   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11144   unsigned nparams = FTP->getNumParams();
11145   assert(FD->getNumParams() == nparams);
11146 
11147   bool HasExtraParameters = (nparams > 3);
11148 
11149   if (FTP->isVariadic()) {
11150     Diag(FD->getLocation(), diag::ext_variadic_main);
11151     // FIXME: if we had information about the location of the ellipsis, we
11152     // could add a FixIt hint to remove it as a parameter.
11153   }
11154 
11155   // Darwin passes an undocumented fourth argument of type char**.  If
11156   // other platforms start sprouting these, the logic below will start
11157   // getting shifty.
11158   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11159     HasExtraParameters = false;
11160 
11161   if (HasExtraParameters) {
11162     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11163     FD->setInvalidDecl(true);
11164     nparams = 3;
11165   }
11166 
11167   // FIXME: a lot of the following diagnostics would be improved
11168   // if we had some location information about types.
11169 
11170   QualType CharPP =
11171     Context.getPointerType(Context.getPointerType(Context.CharTy));
11172   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11173 
11174   for (unsigned i = 0; i < nparams; ++i) {
11175     QualType AT = FTP->getParamType(i);
11176 
11177     bool mismatch = true;
11178 
11179     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11180       mismatch = false;
11181     else if (Expected[i] == CharPP) {
11182       // As an extension, the following forms are okay:
11183       //   char const **
11184       //   char const * const *
11185       //   char * const *
11186 
11187       QualifierCollector qs;
11188       const PointerType* PT;
11189       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11190           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11191           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11192                               Context.CharTy)) {
11193         qs.removeConst();
11194         mismatch = !qs.empty();
11195       }
11196     }
11197 
11198     if (mismatch) {
11199       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11200       // TODO: suggest replacing given type with expected type
11201       FD->setInvalidDecl(true);
11202     }
11203   }
11204 
11205   if (nparams == 1 && !FD->isInvalidDecl()) {
11206     Diag(FD->getLocation(), diag::warn_main_one_arg);
11207   }
11208 
11209   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11210     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11211     FD->setInvalidDecl();
11212   }
11213 }
11214 
11215 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11216 
11217   // Default calling convention for main and wmain is __cdecl
11218   if (FD->getName() == "main" || FD->getName() == "wmain")
11219     return false;
11220 
11221   // Default calling convention for MinGW is __cdecl
11222   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11223   if (T.isWindowsGNUEnvironment())
11224     return false;
11225 
11226   // Default calling convention for WinMain, wWinMain and DllMain
11227   // is __stdcall on 32 bit Windows
11228   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11229     return true;
11230 
11231   return false;
11232 }
11233 
11234 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11235   QualType T = FD->getType();
11236   assert(T->isFunctionType() && "function decl is not of function type");
11237   const FunctionType *FT = T->castAs<FunctionType>();
11238 
11239   // Set an implicit return of 'zero' if the function can return some integral,
11240   // enumeration, pointer or nullptr type.
11241   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11242       FT->getReturnType()->isAnyPointerType() ||
11243       FT->getReturnType()->isNullPtrType())
11244     // DllMain is exempt because a return value of zero means it failed.
11245     if (FD->getName() != "DllMain")
11246       FD->setHasImplicitReturnZero(true);
11247 
11248   // Explicity specified calling conventions are applied to MSVC entry points
11249   if (!hasExplicitCallingConv(T)) {
11250     if (isDefaultStdCall(FD, *this)) {
11251       if (FT->getCallConv() != CC_X86StdCall) {
11252         FT = Context.adjustFunctionType(
11253             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11254         FD->setType(QualType(FT, 0));
11255       }
11256     } else if (FT->getCallConv() != CC_C) {
11257       FT = Context.adjustFunctionType(FT,
11258                                       FT->getExtInfo().withCallingConv(CC_C));
11259       FD->setType(QualType(FT, 0));
11260     }
11261   }
11262 
11263   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11264     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11265     FD->setInvalidDecl();
11266   }
11267 }
11268 
11269 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11270   // FIXME: Need strict checking.  In C89, we need to check for
11271   // any assignment, increment, decrement, function-calls, or
11272   // commas outside of a sizeof.  In C99, it's the same list,
11273   // except that the aforementioned are allowed in unevaluated
11274   // expressions.  Everything else falls under the
11275   // "may accept other forms of constant expressions" exception.
11276   //
11277   // Regular C++ code will not end up here (exceptions: language extensions,
11278   // OpenCL C++ etc), so the constant expression rules there don't matter.
11279   if (Init->isValueDependent()) {
11280     assert(Init->containsErrors() &&
11281            "Dependent code should only occur in error-recovery path.");
11282     return true;
11283   }
11284   const Expr *Culprit;
11285   if (Init->isConstantInitializer(Context, false, &Culprit))
11286     return false;
11287   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11288     << Culprit->getSourceRange();
11289   return true;
11290 }
11291 
11292 namespace {
11293   // Visits an initialization expression to see if OrigDecl is evaluated in
11294   // its own initialization and throws a warning if it does.
11295   class SelfReferenceChecker
11296       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11297     Sema &S;
11298     Decl *OrigDecl;
11299     bool isRecordType;
11300     bool isPODType;
11301     bool isReferenceType;
11302 
11303     bool isInitList;
11304     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11305 
11306   public:
11307     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11308 
11309     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11310                                                     S(S), OrigDecl(OrigDecl) {
11311       isPODType = false;
11312       isRecordType = false;
11313       isReferenceType = false;
11314       isInitList = false;
11315       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11316         isPODType = VD->getType().isPODType(S.Context);
11317         isRecordType = VD->getType()->isRecordType();
11318         isReferenceType = VD->getType()->isReferenceType();
11319       }
11320     }
11321 
11322     // For most expressions, just call the visitor.  For initializer lists,
11323     // track the index of the field being initialized since fields are
11324     // initialized in order allowing use of previously initialized fields.
11325     void CheckExpr(Expr *E) {
11326       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11327       if (!InitList) {
11328         Visit(E);
11329         return;
11330       }
11331 
11332       // Track and increment the index here.
11333       isInitList = true;
11334       InitFieldIndex.push_back(0);
11335       for (auto Child : InitList->children()) {
11336         CheckExpr(cast<Expr>(Child));
11337         ++InitFieldIndex.back();
11338       }
11339       InitFieldIndex.pop_back();
11340     }
11341 
11342     // Returns true if MemberExpr is checked and no further checking is needed.
11343     // Returns false if additional checking is required.
11344     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11345       llvm::SmallVector<FieldDecl*, 4> Fields;
11346       Expr *Base = E;
11347       bool ReferenceField = false;
11348 
11349       // Get the field members used.
11350       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11351         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11352         if (!FD)
11353           return false;
11354         Fields.push_back(FD);
11355         if (FD->getType()->isReferenceType())
11356           ReferenceField = true;
11357         Base = ME->getBase()->IgnoreParenImpCasts();
11358       }
11359 
11360       // Keep checking only if the base Decl is the same.
11361       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11362       if (!DRE || DRE->getDecl() != OrigDecl)
11363         return false;
11364 
11365       // A reference field can be bound to an unininitialized field.
11366       if (CheckReference && !ReferenceField)
11367         return true;
11368 
11369       // Convert FieldDecls to their index number.
11370       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11371       for (const FieldDecl *I : llvm::reverse(Fields))
11372         UsedFieldIndex.push_back(I->getFieldIndex());
11373 
11374       // See if a warning is needed by checking the first difference in index
11375       // numbers.  If field being used has index less than the field being
11376       // initialized, then the use is safe.
11377       for (auto UsedIter = UsedFieldIndex.begin(),
11378                 UsedEnd = UsedFieldIndex.end(),
11379                 OrigIter = InitFieldIndex.begin(),
11380                 OrigEnd = InitFieldIndex.end();
11381            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11382         if (*UsedIter < *OrigIter)
11383           return true;
11384         if (*UsedIter > *OrigIter)
11385           break;
11386       }
11387 
11388       // TODO: Add a different warning which will print the field names.
11389       HandleDeclRefExpr(DRE);
11390       return true;
11391     }
11392 
11393     // For most expressions, the cast is directly above the DeclRefExpr.
11394     // For conditional operators, the cast can be outside the conditional
11395     // operator if both expressions are DeclRefExpr's.
11396     void HandleValue(Expr *E) {
11397       E = E->IgnoreParens();
11398       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11399         HandleDeclRefExpr(DRE);
11400         return;
11401       }
11402 
11403       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11404         Visit(CO->getCond());
11405         HandleValue(CO->getTrueExpr());
11406         HandleValue(CO->getFalseExpr());
11407         return;
11408       }
11409 
11410       if (BinaryConditionalOperator *BCO =
11411               dyn_cast<BinaryConditionalOperator>(E)) {
11412         Visit(BCO->getCond());
11413         HandleValue(BCO->getFalseExpr());
11414         return;
11415       }
11416 
11417       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11418         HandleValue(OVE->getSourceExpr());
11419         return;
11420       }
11421 
11422       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11423         if (BO->getOpcode() == BO_Comma) {
11424           Visit(BO->getLHS());
11425           HandleValue(BO->getRHS());
11426           return;
11427         }
11428       }
11429 
11430       if (isa<MemberExpr>(E)) {
11431         if (isInitList) {
11432           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11433                                       false /*CheckReference*/))
11434             return;
11435         }
11436 
11437         Expr *Base = E->IgnoreParenImpCasts();
11438         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11439           // Check for static member variables and don't warn on them.
11440           if (!isa<FieldDecl>(ME->getMemberDecl()))
11441             return;
11442           Base = ME->getBase()->IgnoreParenImpCasts();
11443         }
11444         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11445           HandleDeclRefExpr(DRE);
11446         return;
11447       }
11448 
11449       Visit(E);
11450     }
11451 
11452     // Reference types not handled in HandleValue are handled here since all
11453     // uses of references are bad, not just r-value uses.
11454     void VisitDeclRefExpr(DeclRefExpr *E) {
11455       if (isReferenceType)
11456         HandleDeclRefExpr(E);
11457     }
11458 
11459     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11460       if (E->getCastKind() == CK_LValueToRValue) {
11461         HandleValue(E->getSubExpr());
11462         return;
11463       }
11464 
11465       Inherited::VisitImplicitCastExpr(E);
11466     }
11467 
11468     void VisitMemberExpr(MemberExpr *E) {
11469       if (isInitList) {
11470         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11471           return;
11472       }
11473 
11474       // Don't warn on arrays since they can be treated as pointers.
11475       if (E->getType()->canDecayToPointerType()) return;
11476 
11477       // Warn when a non-static method call is followed by non-static member
11478       // field accesses, which is followed by a DeclRefExpr.
11479       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11480       bool Warn = (MD && !MD->isStatic());
11481       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11482       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11483         if (!isa<FieldDecl>(ME->getMemberDecl()))
11484           Warn = false;
11485         Base = ME->getBase()->IgnoreParenImpCasts();
11486       }
11487 
11488       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11489         if (Warn)
11490           HandleDeclRefExpr(DRE);
11491         return;
11492       }
11493 
11494       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11495       // Visit that expression.
11496       Visit(Base);
11497     }
11498 
11499     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11500       Expr *Callee = E->getCallee();
11501 
11502       if (isa<UnresolvedLookupExpr>(Callee))
11503         return Inherited::VisitCXXOperatorCallExpr(E);
11504 
11505       Visit(Callee);
11506       for (auto Arg: E->arguments())
11507         HandleValue(Arg->IgnoreParenImpCasts());
11508     }
11509 
11510     void VisitUnaryOperator(UnaryOperator *E) {
11511       // For POD record types, addresses of its own members are well-defined.
11512       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11513           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11514         if (!isPODType)
11515           HandleValue(E->getSubExpr());
11516         return;
11517       }
11518 
11519       if (E->isIncrementDecrementOp()) {
11520         HandleValue(E->getSubExpr());
11521         return;
11522       }
11523 
11524       Inherited::VisitUnaryOperator(E);
11525     }
11526 
11527     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11528 
11529     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11530       if (E->getConstructor()->isCopyConstructor()) {
11531         Expr *ArgExpr = E->getArg(0);
11532         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11533           if (ILE->getNumInits() == 1)
11534             ArgExpr = ILE->getInit(0);
11535         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11536           if (ICE->getCastKind() == CK_NoOp)
11537             ArgExpr = ICE->getSubExpr();
11538         HandleValue(ArgExpr);
11539         return;
11540       }
11541       Inherited::VisitCXXConstructExpr(E);
11542     }
11543 
11544     void VisitCallExpr(CallExpr *E) {
11545       // Treat std::move as a use.
11546       if (E->isCallToStdMove()) {
11547         HandleValue(E->getArg(0));
11548         return;
11549       }
11550 
11551       Inherited::VisitCallExpr(E);
11552     }
11553 
11554     void VisitBinaryOperator(BinaryOperator *E) {
11555       if (E->isCompoundAssignmentOp()) {
11556         HandleValue(E->getLHS());
11557         Visit(E->getRHS());
11558         return;
11559       }
11560 
11561       Inherited::VisitBinaryOperator(E);
11562     }
11563 
11564     // A custom visitor for BinaryConditionalOperator is needed because the
11565     // regular visitor would check the condition and true expression separately
11566     // but both point to the same place giving duplicate diagnostics.
11567     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11568       Visit(E->getCond());
11569       Visit(E->getFalseExpr());
11570     }
11571 
11572     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11573       Decl* ReferenceDecl = DRE->getDecl();
11574       if (OrigDecl != ReferenceDecl) return;
11575       unsigned diag;
11576       if (isReferenceType) {
11577         diag = diag::warn_uninit_self_reference_in_reference_init;
11578       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11579         diag = diag::warn_static_self_reference_in_init;
11580       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11581                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11582                  DRE->getDecl()->getType()->isRecordType()) {
11583         diag = diag::warn_uninit_self_reference_in_init;
11584       } else {
11585         // Local variables will be handled by the CFG analysis.
11586         return;
11587       }
11588 
11589       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11590                             S.PDiag(diag)
11591                                 << DRE->getDecl() << OrigDecl->getLocation()
11592                                 << DRE->getSourceRange());
11593     }
11594   };
11595 
11596   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11597   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11598                                  bool DirectInit) {
11599     // Parameters arguments are occassionially constructed with itself,
11600     // for instance, in recursive functions.  Skip them.
11601     if (isa<ParmVarDecl>(OrigDecl))
11602       return;
11603 
11604     E = E->IgnoreParens();
11605 
11606     // Skip checking T a = a where T is not a record or reference type.
11607     // Doing so is a way to silence uninitialized warnings.
11608     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11609       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11610         if (ICE->getCastKind() == CK_LValueToRValue)
11611           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11612             if (DRE->getDecl() == OrigDecl)
11613               return;
11614 
11615     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11616   }
11617 } // end anonymous namespace
11618 
11619 namespace {
11620   // Simple wrapper to add the name of a variable or (if no variable is
11621   // available) a DeclarationName into a diagnostic.
11622   struct VarDeclOrName {
11623     VarDecl *VDecl;
11624     DeclarationName Name;
11625 
11626     friend const Sema::SemaDiagnosticBuilder &
11627     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11628       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11629     }
11630   };
11631 } // end anonymous namespace
11632 
11633 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11634                                             DeclarationName Name, QualType Type,
11635                                             TypeSourceInfo *TSI,
11636                                             SourceRange Range, bool DirectInit,
11637                                             Expr *Init) {
11638   bool IsInitCapture = !VDecl;
11639   assert((!VDecl || !VDecl->isInitCapture()) &&
11640          "init captures are expected to be deduced prior to initialization");
11641 
11642   VarDeclOrName VN{VDecl, Name};
11643 
11644   DeducedType *Deduced = Type->getContainedDeducedType();
11645   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11646 
11647   // C++11 [dcl.spec.auto]p3
11648   if (!Init) {
11649     assert(VDecl && "no init for init capture deduction?");
11650 
11651     // Except for class argument deduction, and then for an initializing
11652     // declaration only, i.e. no static at class scope or extern.
11653     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11654         VDecl->hasExternalStorage() ||
11655         VDecl->isStaticDataMember()) {
11656       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11657         << VDecl->getDeclName() << Type;
11658       return QualType();
11659     }
11660   }
11661 
11662   ArrayRef<Expr*> DeduceInits;
11663   if (Init)
11664     DeduceInits = Init;
11665 
11666   if (DirectInit) {
11667     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11668       DeduceInits = PL->exprs();
11669   }
11670 
11671   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11672     assert(VDecl && "non-auto type for init capture deduction?");
11673     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11674     InitializationKind Kind = InitializationKind::CreateForInit(
11675         VDecl->getLocation(), DirectInit, Init);
11676     // FIXME: Initialization should not be taking a mutable list of inits.
11677     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11678     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11679                                                        InitsCopy);
11680   }
11681 
11682   if (DirectInit) {
11683     if (auto *IL = dyn_cast<InitListExpr>(Init))
11684       DeduceInits = IL->inits();
11685   }
11686 
11687   // Deduction only works if we have exactly one source expression.
11688   if (DeduceInits.empty()) {
11689     // It isn't possible to write this directly, but it is possible to
11690     // end up in this situation with "auto x(some_pack...);"
11691     Diag(Init->getBeginLoc(), IsInitCapture
11692                                   ? diag::err_init_capture_no_expression
11693                                   : diag::err_auto_var_init_no_expression)
11694         << VN << Type << Range;
11695     return QualType();
11696   }
11697 
11698   if (DeduceInits.size() > 1) {
11699     Diag(DeduceInits[1]->getBeginLoc(),
11700          IsInitCapture ? diag::err_init_capture_multiple_expressions
11701                        : diag::err_auto_var_init_multiple_expressions)
11702         << VN << Type << Range;
11703     return QualType();
11704   }
11705 
11706   Expr *DeduceInit = DeduceInits[0];
11707   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11708     Diag(Init->getBeginLoc(), IsInitCapture
11709                                   ? diag::err_init_capture_paren_braces
11710                                   : diag::err_auto_var_init_paren_braces)
11711         << isa<InitListExpr>(Init) << VN << Type << Range;
11712     return QualType();
11713   }
11714 
11715   // Expressions default to 'id' when we're in a debugger.
11716   bool DefaultedAnyToId = false;
11717   if (getLangOpts().DebuggerCastResultToId &&
11718       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11719     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11720     if (Result.isInvalid()) {
11721       return QualType();
11722     }
11723     Init = Result.get();
11724     DefaultedAnyToId = true;
11725   }
11726 
11727   // C++ [dcl.decomp]p1:
11728   //   If the assignment-expression [...] has array type A and no ref-qualifier
11729   //   is present, e has type cv A
11730   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11731       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11732       DeduceInit->getType()->isConstantArrayType())
11733     return Context.getQualifiedType(DeduceInit->getType(),
11734                                     Type.getQualifiers());
11735 
11736   QualType DeducedType;
11737   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11738     if (!IsInitCapture)
11739       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11740     else if (isa<InitListExpr>(Init))
11741       Diag(Range.getBegin(),
11742            diag::err_init_capture_deduction_failure_from_init_list)
11743           << VN
11744           << (DeduceInit->getType().isNull() ? TSI->getType()
11745                                              : DeduceInit->getType())
11746           << DeduceInit->getSourceRange();
11747     else
11748       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11749           << VN << TSI->getType()
11750           << (DeduceInit->getType().isNull() ? TSI->getType()
11751                                              : DeduceInit->getType())
11752           << DeduceInit->getSourceRange();
11753   }
11754 
11755   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11756   // 'id' instead of a specific object type prevents most of our usual
11757   // checks.
11758   // We only want to warn outside of template instantiations, though:
11759   // inside a template, the 'id' could have come from a parameter.
11760   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11761       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11762     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11763     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11764   }
11765 
11766   return DeducedType;
11767 }
11768 
11769 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11770                                          Expr *Init) {
11771   assert(!Init || !Init->containsErrors());
11772   QualType DeducedType = deduceVarTypeFromInitializer(
11773       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11774       VDecl->getSourceRange(), DirectInit, Init);
11775   if (DeducedType.isNull()) {
11776     VDecl->setInvalidDecl();
11777     return true;
11778   }
11779 
11780   VDecl->setType(DeducedType);
11781   assert(VDecl->isLinkageValid());
11782 
11783   // In ARC, infer lifetime.
11784   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11785     VDecl->setInvalidDecl();
11786 
11787   if (getLangOpts().OpenCL)
11788     deduceOpenCLAddressSpace(VDecl);
11789 
11790   // If this is a redeclaration, check that the type we just deduced matches
11791   // the previously declared type.
11792   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11793     // We never need to merge the type, because we cannot form an incomplete
11794     // array of auto, nor deduce such a type.
11795     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11796   }
11797 
11798   // Check the deduced type is valid for a variable declaration.
11799   CheckVariableDeclarationType(VDecl);
11800   return VDecl->isInvalidDecl();
11801 }
11802 
11803 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11804                                               SourceLocation Loc) {
11805   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11806     Init = EWC->getSubExpr();
11807 
11808   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11809     Init = CE->getSubExpr();
11810 
11811   QualType InitType = Init->getType();
11812   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11813           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11814          "shouldn't be called if type doesn't have a non-trivial C struct");
11815   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11816     for (auto I : ILE->inits()) {
11817       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11818           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11819         continue;
11820       SourceLocation SL = I->getExprLoc();
11821       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11822     }
11823     return;
11824   }
11825 
11826   if (isa<ImplicitValueInitExpr>(Init)) {
11827     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11828       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11829                             NTCUK_Init);
11830   } else {
11831     // Assume all other explicit initializers involving copying some existing
11832     // object.
11833     // TODO: ignore any explicit initializers where we can guarantee
11834     // copy-elision.
11835     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11836       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11837   }
11838 }
11839 
11840 namespace {
11841 
11842 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11843   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11844   // in the source code or implicitly by the compiler if it is in a union
11845   // defined in a system header and has non-trivial ObjC ownership
11846   // qualifications. We don't want those fields to participate in determining
11847   // whether the containing union is non-trivial.
11848   return FD->hasAttr<UnavailableAttr>();
11849 }
11850 
11851 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11852     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11853                                     void> {
11854   using Super =
11855       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11856                                     void>;
11857 
11858   DiagNonTrivalCUnionDefaultInitializeVisitor(
11859       QualType OrigTy, SourceLocation OrigLoc,
11860       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11861       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11862 
11863   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11864                      const FieldDecl *FD, bool InNonTrivialUnion) {
11865     if (const auto *AT = S.Context.getAsArrayType(QT))
11866       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11867                                      InNonTrivialUnion);
11868     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11869   }
11870 
11871   void visitARCStrong(QualType QT, const FieldDecl *FD,
11872                       bool InNonTrivialUnion) {
11873     if (InNonTrivialUnion)
11874       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11875           << 1 << 0 << QT << FD->getName();
11876   }
11877 
11878   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11879     if (InNonTrivialUnion)
11880       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11881           << 1 << 0 << QT << FD->getName();
11882   }
11883 
11884   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11885     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11886     if (RD->isUnion()) {
11887       if (OrigLoc.isValid()) {
11888         bool IsUnion = false;
11889         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11890           IsUnion = OrigRD->isUnion();
11891         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11892             << 0 << OrigTy << IsUnion << UseContext;
11893         // Reset OrigLoc so that this diagnostic is emitted only once.
11894         OrigLoc = SourceLocation();
11895       }
11896       InNonTrivialUnion = true;
11897     }
11898 
11899     if (InNonTrivialUnion)
11900       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11901           << 0 << 0 << QT.getUnqualifiedType() << "";
11902 
11903     for (const FieldDecl *FD : RD->fields())
11904       if (!shouldIgnoreForRecordTriviality(FD))
11905         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11906   }
11907 
11908   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11909 
11910   // The non-trivial C union type or the struct/union type that contains a
11911   // non-trivial C union.
11912   QualType OrigTy;
11913   SourceLocation OrigLoc;
11914   Sema::NonTrivialCUnionContext UseContext;
11915   Sema &S;
11916 };
11917 
11918 struct DiagNonTrivalCUnionDestructedTypeVisitor
11919     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11920   using Super =
11921       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11922 
11923   DiagNonTrivalCUnionDestructedTypeVisitor(
11924       QualType OrigTy, SourceLocation OrigLoc,
11925       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11926       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11927 
11928   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11929                      const FieldDecl *FD, bool InNonTrivialUnion) {
11930     if (const auto *AT = S.Context.getAsArrayType(QT))
11931       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11932                                      InNonTrivialUnion);
11933     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11934   }
11935 
11936   void visitARCStrong(QualType QT, const FieldDecl *FD,
11937                       bool InNonTrivialUnion) {
11938     if (InNonTrivialUnion)
11939       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11940           << 1 << 1 << QT << FD->getName();
11941   }
11942 
11943   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11944     if (InNonTrivialUnion)
11945       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11946           << 1 << 1 << QT << FD->getName();
11947   }
11948 
11949   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11950     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11951     if (RD->isUnion()) {
11952       if (OrigLoc.isValid()) {
11953         bool IsUnion = false;
11954         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11955           IsUnion = OrigRD->isUnion();
11956         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11957             << 1 << OrigTy << IsUnion << UseContext;
11958         // Reset OrigLoc so that this diagnostic is emitted only once.
11959         OrigLoc = SourceLocation();
11960       }
11961       InNonTrivialUnion = true;
11962     }
11963 
11964     if (InNonTrivialUnion)
11965       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11966           << 0 << 1 << QT.getUnqualifiedType() << "";
11967 
11968     for (const FieldDecl *FD : RD->fields())
11969       if (!shouldIgnoreForRecordTriviality(FD))
11970         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11971   }
11972 
11973   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11974   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11975                           bool InNonTrivialUnion) {}
11976 
11977   // The non-trivial C union type or the struct/union type that contains a
11978   // non-trivial C union.
11979   QualType OrigTy;
11980   SourceLocation OrigLoc;
11981   Sema::NonTrivialCUnionContext UseContext;
11982   Sema &S;
11983 };
11984 
11985 struct DiagNonTrivalCUnionCopyVisitor
11986     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11987   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11988 
11989   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11990                                  Sema::NonTrivialCUnionContext UseContext,
11991                                  Sema &S)
11992       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11993 
11994   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11995                      const FieldDecl *FD, bool InNonTrivialUnion) {
11996     if (const auto *AT = S.Context.getAsArrayType(QT))
11997       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11998                                      InNonTrivialUnion);
11999     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12000   }
12001 
12002   void visitARCStrong(QualType QT, const FieldDecl *FD,
12003                       bool InNonTrivialUnion) {
12004     if (InNonTrivialUnion)
12005       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12006           << 1 << 2 << QT << FD->getName();
12007   }
12008 
12009   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12010     if (InNonTrivialUnion)
12011       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12012           << 1 << 2 << QT << FD->getName();
12013   }
12014 
12015   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12016     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12017     if (RD->isUnion()) {
12018       if (OrigLoc.isValid()) {
12019         bool IsUnion = false;
12020         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12021           IsUnion = OrigRD->isUnion();
12022         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12023             << 2 << OrigTy << IsUnion << UseContext;
12024         // Reset OrigLoc so that this diagnostic is emitted only once.
12025         OrigLoc = SourceLocation();
12026       }
12027       InNonTrivialUnion = true;
12028     }
12029 
12030     if (InNonTrivialUnion)
12031       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12032           << 0 << 2 << QT.getUnqualifiedType() << "";
12033 
12034     for (const FieldDecl *FD : RD->fields())
12035       if (!shouldIgnoreForRecordTriviality(FD))
12036         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12037   }
12038 
12039   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12040                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12041   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12042   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12043                             bool InNonTrivialUnion) {}
12044 
12045   // The non-trivial C union type or the struct/union type that contains a
12046   // non-trivial C union.
12047   QualType OrigTy;
12048   SourceLocation OrigLoc;
12049   Sema::NonTrivialCUnionContext UseContext;
12050   Sema &S;
12051 };
12052 
12053 } // namespace
12054 
12055 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12056                                  NonTrivialCUnionContext UseContext,
12057                                  unsigned NonTrivialKind) {
12058   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12059           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12060           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12061          "shouldn't be called if type doesn't have a non-trivial C union");
12062 
12063   if ((NonTrivialKind & NTCUK_Init) &&
12064       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12065     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12066         .visit(QT, nullptr, false);
12067   if ((NonTrivialKind & NTCUK_Destruct) &&
12068       QT.hasNonTrivialToPrimitiveDestructCUnion())
12069     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12070         .visit(QT, nullptr, false);
12071   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12072     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12073         .visit(QT, nullptr, false);
12074 }
12075 
12076 /// AddInitializerToDecl - Adds the initializer Init to the
12077 /// declaration dcl. If DirectInit is true, this is C++ direct
12078 /// initialization rather than copy initialization.
12079 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12080   // If there is no declaration, there was an error parsing it.  Just ignore
12081   // the initializer.
12082   if (!RealDecl || RealDecl->isInvalidDecl()) {
12083     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12084     return;
12085   }
12086 
12087   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12088     // Pure-specifiers are handled in ActOnPureSpecifier.
12089     Diag(Method->getLocation(), diag::err_member_function_initialization)
12090       << Method->getDeclName() << Init->getSourceRange();
12091     Method->setInvalidDecl();
12092     return;
12093   }
12094 
12095   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12096   if (!VDecl) {
12097     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12098     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12099     RealDecl->setInvalidDecl();
12100     return;
12101   }
12102 
12103   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12104   if (VDecl->getType()->isUndeducedType()) {
12105     // Attempt typo correction early so that the type of the init expression can
12106     // be deduced based on the chosen correction if the original init contains a
12107     // TypoExpr.
12108     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12109     if (!Res.isUsable()) {
12110       // There are unresolved typos in Init, just drop them.
12111       // FIXME: improve the recovery strategy to preserve the Init.
12112       RealDecl->setInvalidDecl();
12113       return;
12114     }
12115     if (Res.get()->containsErrors()) {
12116       // Invalidate the decl as we don't know the type for recovery-expr yet.
12117       RealDecl->setInvalidDecl();
12118       VDecl->setInit(Res.get());
12119       return;
12120     }
12121     Init = Res.get();
12122 
12123     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12124       return;
12125   }
12126 
12127   // dllimport cannot be used on variable definitions.
12128   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12129     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12130     VDecl->setInvalidDecl();
12131     return;
12132   }
12133 
12134   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12135     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12136     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12137     VDecl->setInvalidDecl();
12138     return;
12139   }
12140 
12141   if (!VDecl->getType()->isDependentType()) {
12142     // A definition must end up with a complete type, which means it must be
12143     // complete with the restriction that an array type might be completed by
12144     // the initializer; note that later code assumes this restriction.
12145     QualType BaseDeclType = VDecl->getType();
12146     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12147       BaseDeclType = Array->getElementType();
12148     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12149                             diag::err_typecheck_decl_incomplete_type)) {
12150       RealDecl->setInvalidDecl();
12151       return;
12152     }
12153 
12154     // The variable can not have an abstract class type.
12155     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12156                                diag::err_abstract_type_in_decl,
12157                                AbstractVariableType))
12158       VDecl->setInvalidDecl();
12159   }
12160 
12161   // If adding the initializer will turn this declaration into a definition,
12162   // and we already have a definition for this variable, diagnose or otherwise
12163   // handle the situation.
12164   VarDecl *Def;
12165   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12166       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12167       !VDecl->isThisDeclarationADemotedDefinition() &&
12168       checkVarDeclRedefinition(Def, VDecl))
12169     return;
12170 
12171   if (getLangOpts().CPlusPlus) {
12172     // C++ [class.static.data]p4
12173     //   If a static data member is of const integral or const
12174     //   enumeration type, its declaration in the class definition can
12175     //   specify a constant-initializer which shall be an integral
12176     //   constant expression (5.19). In that case, the member can appear
12177     //   in integral constant expressions. The member shall still be
12178     //   defined in a namespace scope if it is used in the program and the
12179     //   namespace scope definition shall not contain an initializer.
12180     //
12181     // We already performed a redefinition check above, but for static
12182     // data members we also need to check whether there was an in-class
12183     // declaration with an initializer.
12184     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12185       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12186           << VDecl->getDeclName();
12187       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12188            diag::note_previous_initializer)
12189           << 0;
12190       return;
12191     }
12192 
12193     if (VDecl->hasLocalStorage())
12194       setFunctionHasBranchProtectedScope();
12195 
12196     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12197       VDecl->setInvalidDecl();
12198       return;
12199     }
12200   }
12201 
12202   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12203   // a kernel function cannot be initialized."
12204   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12205     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12206     VDecl->setInvalidDecl();
12207     return;
12208   }
12209 
12210   // The LoaderUninitialized attribute acts as a definition (of undef).
12211   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12212     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12213     VDecl->setInvalidDecl();
12214     return;
12215   }
12216 
12217   // Get the decls type and save a reference for later, since
12218   // CheckInitializerTypes may change it.
12219   QualType DclT = VDecl->getType(), SavT = DclT;
12220 
12221   // Expressions default to 'id' when we're in a debugger
12222   // and we are assigning it to a variable of Objective-C pointer type.
12223   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12224       Init->getType() == Context.UnknownAnyTy) {
12225     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12226     if (Result.isInvalid()) {
12227       VDecl->setInvalidDecl();
12228       return;
12229     }
12230     Init = Result.get();
12231   }
12232 
12233   // Perform the initialization.
12234   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12235   if (!VDecl->isInvalidDecl()) {
12236     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12237     InitializationKind Kind = InitializationKind::CreateForInit(
12238         VDecl->getLocation(), DirectInit, Init);
12239 
12240     MultiExprArg Args = Init;
12241     if (CXXDirectInit)
12242       Args = MultiExprArg(CXXDirectInit->getExprs(),
12243                           CXXDirectInit->getNumExprs());
12244 
12245     // Try to correct any TypoExprs in the initialization arguments.
12246     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12247       ExprResult Res = CorrectDelayedTyposInExpr(
12248           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12249           [this, Entity, Kind](Expr *E) {
12250             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12251             return Init.Failed() ? ExprError() : E;
12252           });
12253       if (Res.isInvalid()) {
12254         VDecl->setInvalidDecl();
12255       } else if (Res.get() != Args[Idx]) {
12256         Args[Idx] = Res.get();
12257       }
12258     }
12259     if (VDecl->isInvalidDecl())
12260       return;
12261 
12262     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12263                                    /*TopLevelOfInitList=*/false,
12264                                    /*TreatUnavailableAsInvalid=*/false);
12265     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12266     if (Result.isInvalid()) {
12267       // If the provied initializer fails to initialize the var decl,
12268       // we attach a recovery expr for better recovery.
12269       auto RecoveryExpr =
12270           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12271       if (RecoveryExpr.get())
12272         VDecl->setInit(RecoveryExpr.get());
12273       return;
12274     }
12275 
12276     Init = Result.getAs<Expr>();
12277   }
12278 
12279   // Check for self-references within variable initializers.
12280   // Variables declared within a function/method body (except for references)
12281   // are handled by a dataflow analysis.
12282   // This is undefined behavior in C++, but valid in C.
12283   if (getLangOpts().CPlusPlus) {
12284     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12285         VDecl->getType()->isReferenceType()) {
12286       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12287     }
12288   }
12289 
12290   // If the type changed, it means we had an incomplete type that was
12291   // completed by the initializer. For example:
12292   //   int ary[] = { 1, 3, 5 };
12293   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12294   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12295     VDecl->setType(DclT);
12296 
12297   if (!VDecl->isInvalidDecl()) {
12298     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12299 
12300     if (VDecl->hasAttr<BlocksAttr>())
12301       checkRetainCycles(VDecl, Init);
12302 
12303     // It is safe to assign a weak reference into a strong variable.
12304     // Although this code can still have problems:
12305     //   id x = self.weakProp;
12306     //   id y = self.weakProp;
12307     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12308     // paths through the function. This should be revisited if
12309     // -Wrepeated-use-of-weak is made flow-sensitive.
12310     if (FunctionScopeInfo *FSI = getCurFunction())
12311       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12312            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12313           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12314                            Init->getBeginLoc()))
12315         FSI->markSafeWeakUse(Init);
12316   }
12317 
12318   // The initialization is usually a full-expression.
12319   //
12320   // FIXME: If this is a braced initialization of an aggregate, it is not
12321   // an expression, and each individual field initializer is a separate
12322   // full-expression. For instance, in:
12323   //
12324   //   struct Temp { ~Temp(); };
12325   //   struct S { S(Temp); };
12326   //   struct T { S a, b; } t = { Temp(), Temp() }
12327   //
12328   // we should destroy the first Temp before constructing the second.
12329   ExprResult Result =
12330       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12331                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12332   if (Result.isInvalid()) {
12333     VDecl->setInvalidDecl();
12334     return;
12335   }
12336   Init = Result.get();
12337 
12338   // Attach the initializer to the decl.
12339   VDecl->setInit(Init);
12340 
12341   if (VDecl->isLocalVarDecl()) {
12342     // Don't check the initializer if the declaration is malformed.
12343     if (VDecl->isInvalidDecl()) {
12344       // do nothing
12345 
12346     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12347     // This is true even in C++ for OpenCL.
12348     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12349       CheckForConstantInitializer(Init, DclT);
12350 
12351     // Otherwise, C++ does not restrict the initializer.
12352     } else if (getLangOpts().CPlusPlus) {
12353       // do nothing
12354 
12355     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12356     // static storage duration shall be constant expressions or string literals.
12357     } else if (VDecl->getStorageClass() == SC_Static) {
12358       CheckForConstantInitializer(Init, DclT);
12359 
12360     // C89 is stricter than C99 for aggregate initializers.
12361     // C89 6.5.7p3: All the expressions [...] in an initializer list
12362     // for an object that has aggregate or union type shall be
12363     // constant expressions.
12364     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12365                isa<InitListExpr>(Init)) {
12366       const Expr *Culprit;
12367       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12368         Diag(Culprit->getExprLoc(),
12369              diag::ext_aggregate_init_not_constant)
12370           << Culprit->getSourceRange();
12371       }
12372     }
12373 
12374     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12375       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12376         if (VDecl->hasLocalStorage())
12377           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12378   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12379              VDecl->getLexicalDeclContext()->isRecord()) {
12380     // This is an in-class initialization for a static data member, e.g.,
12381     //
12382     // struct S {
12383     //   static const int value = 17;
12384     // };
12385 
12386     // C++ [class.mem]p4:
12387     //   A member-declarator can contain a constant-initializer only
12388     //   if it declares a static member (9.4) of const integral or
12389     //   const enumeration type, see 9.4.2.
12390     //
12391     // C++11 [class.static.data]p3:
12392     //   If a non-volatile non-inline const static data member is of integral
12393     //   or enumeration type, its declaration in the class definition can
12394     //   specify a brace-or-equal-initializer in which every initializer-clause
12395     //   that is an assignment-expression is a constant expression. A static
12396     //   data member of literal type can be declared in the class definition
12397     //   with the constexpr specifier; if so, its declaration shall specify a
12398     //   brace-or-equal-initializer in which every initializer-clause that is
12399     //   an assignment-expression is a constant expression.
12400 
12401     // Do nothing on dependent types.
12402     if (DclT->isDependentType()) {
12403 
12404     // Allow any 'static constexpr' members, whether or not they are of literal
12405     // type. We separately check that every constexpr variable is of literal
12406     // type.
12407     } else if (VDecl->isConstexpr()) {
12408 
12409     // Require constness.
12410     } else if (!DclT.isConstQualified()) {
12411       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12412         << Init->getSourceRange();
12413       VDecl->setInvalidDecl();
12414 
12415     // We allow integer constant expressions in all cases.
12416     } else if (DclT->isIntegralOrEnumerationType()) {
12417       // Check whether the expression is a constant expression.
12418       SourceLocation Loc;
12419       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12420         // In C++11, a non-constexpr const static data member with an
12421         // in-class initializer cannot be volatile.
12422         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12423       else if (Init->isValueDependent())
12424         ; // Nothing to check.
12425       else if (Init->isIntegerConstantExpr(Context, &Loc))
12426         ; // Ok, it's an ICE!
12427       else if (Init->getType()->isScopedEnumeralType() &&
12428                Init->isCXX11ConstantExpr(Context))
12429         ; // Ok, it is a scoped-enum constant expression.
12430       else if (Init->isEvaluatable(Context)) {
12431         // If we can constant fold the initializer through heroics, accept it,
12432         // but report this as a use of an extension for -pedantic.
12433         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12434           << Init->getSourceRange();
12435       } else {
12436         // Otherwise, this is some crazy unknown case.  Report the issue at the
12437         // location provided by the isIntegerConstantExpr failed check.
12438         Diag(Loc, diag::err_in_class_initializer_non_constant)
12439           << Init->getSourceRange();
12440         VDecl->setInvalidDecl();
12441       }
12442 
12443     // We allow foldable floating-point constants as an extension.
12444     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12445       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12446       // it anyway and provide a fixit to add the 'constexpr'.
12447       if (getLangOpts().CPlusPlus11) {
12448         Diag(VDecl->getLocation(),
12449              diag::ext_in_class_initializer_float_type_cxx11)
12450             << DclT << Init->getSourceRange();
12451         Diag(VDecl->getBeginLoc(),
12452              diag::note_in_class_initializer_float_type_cxx11)
12453             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12454       } else {
12455         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12456           << DclT << Init->getSourceRange();
12457 
12458         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12459           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12460             << Init->getSourceRange();
12461           VDecl->setInvalidDecl();
12462         }
12463       }
12464 
12465     // Suggest adding 'constexpr' in C++11 for literal types.
12466     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12467       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12468           << DclT << Init->getSourceRange()
12469           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12470       VDecl->setConstexpr(true);
12471 
12472     } else {
12473       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12474         << DclT << Init->getSourceRange();
12475       VDecl->setInvalidDecl();
12476     }
12477   } else if (VDecl->isFileVarDecl()) {
12478     // In C, extern is typically used to avoid tentative definitions when
12479     // declaring variables in headers, but adding an intializer makes it a
12480     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12481     // In C++, extern is often used to give implictly static const variables
12482     // external linkage, so don't warn in that case. If selectany is present,
12483     // this might be header code intended for C and C++ inclusion, so apply the
12484     // C++ rules.
12485     if (VDecl->getStorageClass() == SC_Extern &&
12486         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12487          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12488         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12489         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12490       Diag(VDecl->getLocation(), diag::warn_extern_init);
12491 
12492     // In Microsoft C++ mode, a const variable defined in namespace scope has
12493     // external linkage by default if the variable is declared with
12494     // __declspec(dllexport).
12495     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12496         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12497         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12498       VDecl->setStorageClass(SC_Extern);
12499 
12500     // C99 6.7.8p4. All file scoped initializers need to be constant.
12501     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12502       CheckForConstantInitializer(Init, DclT);
12503   }
12504 
12505   QualType InitType = Init->getType();
12506   if (!InitType.isNull() &&
12507       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12508        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12509     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12510 
12511   // We will represent direct-initialization similarly to copy-initialization:
12512   //    int x(1);  -as-> int x = 1;
12513   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12514   //
12515   // Clients that want to distinguish between the two forms, can check for
12516   // direct initializer using VarDecl::getInitStyle().
12517   // A major benefit is that clients that don't particularly care about which
12518   // exactly form was it (like the CodeGen) can handle both cases without
12519   // special case code.
12520 
12521   // C++ 8.5p11:
12522   // The form of initialization (using parentheses or '=') is generally
12523   // insignificant, but does matter when the entity being initialized has a
12524   // class type.
12525   if (CXXDirectInit) {
12526     assert(DirectInit && "Call-style initializer must be direct init.");
12527     VDecl->setInitStyle(VarDecl::CallInit);
12528   } else if (DirectInit) {
12529     // This must be list-initialization. No other way is direct-initialization.
12530     VDecl->setInitStyle(VarDecl::ListInit);
12531   }
12532 
12533   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12534     DeclsToCheckForDeferredDiags.push_back(VDecl);
12535   CheckCompleteVariableDeclaration(VDecl);
12536 }
12537 
12538 /// ActOnInitializerError - Given that there was an error parsing an
12539 /// initializer for the given declaration, try to return to some form
12540 /// of sanity.
12541 void Sema::ActOnInitializerError(Decl *D) {
12542   // Our main concern here is re-establishing invariants like "a
12543   // variable's type is either dependent or complete".
12544   if (!D || D->isInvalidDecl()) return;
12545 
12546   VarDecl *VD = dyn_cast<VarDecl>(D);
12547   if (!VD) return;
12548 
12549   // Bindings are not usable if we can't make sense of the initializer.
12550   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12551     for (auto *BD : DD->bindings())
12552       BD->setInvalidDecl();
12553 
12554   // Auto types are meaningless if we can't make sense of the initializer.
12555   if (VD->getType()->isUndeducedType()) {
12556     D->setInvalidDecl();
12557     return;
12558   }
12559 
12560   QualType Ty = VD->getType();
12561   if (Ty->isDependentType()) return;
12562 
12563   // Require a complete type.
12564   if (RequireCompleteType(VD->getLocation(),
12565                           Context.getBaseElementType(Ty),
12566                           diag::err_typecheck_decl_incomplete_type)) {
12567     VD->setInvalidDecl();
12568     return;
12569   }
12570 
12571   // Require a non-abstract type.
12572   if (RequireNonAbstractType(VD->getLocation(), Ty,
12573                              diag::err_abstract_type_in_decl,
12574                              AbstractVariableType)) {
12575     VD->setInvalidDecl();
12576     return;
12577   }
12578 
12579   // Don't bother complaining about constructors or destructors,
12580   // though.
12581 }
12582 
12583 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12584   // If there is no declaration, there was an error parsing it. Just ignore it.
12585   if (!RealDecl)
12586     return;
12587 
12588   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12589     QualType Type = Var->getType();
12590 
12591     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12592     if (isa<DecompositionDecl>(RealDecl)) {
12593       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12594       Var->setInvalidDecl();
12595       return;
12596     }
12597 
12598     if (Type->isUndeducedType() &&
12599         DeduceVariableDeclarationType(Var, false, nullptr))
12600       return;
12601 
12602     // C++11 [class.static.data]p3: A static data member can be declared with
12603     // the constexpr specifier; if so, its declaration shall specify
12604     // a brace-or-equal-initializer.
12605     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12606     // the definition of a variable [...] or the declaration of a static data
12607     // member.
12608     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12609         !Var->isThisDeclarationADemotedDefinition()) {
12610       if (Var->isStaticDataMember()) {
12611         // C++1z removes the relevant rule; the in-class declaration is always
12612         // a definition there.
12613         if (!getLangOpts().CPlusPlus17 &&
12614             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12615           Diag(Var->getLocation(),
12616                diag::err_constexpr_static_mem_var_requires_init)
12617               << Var;
12618           Var->setInvalidDecl();
12619           return;
12620         }
12621       } else {
12622         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12623         Var->setInvalidDecl();
12624         return;
12625       }
12626     }
12627 
12628     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12629     // be initialized.
12630     if (!Var->isInvalidDecl() &&
12631         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12632         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12633       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12634       Var->setInvalidDecl();
12635       return;
12636     }
12637 
12638     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12639       if (Var->getStorageClass() == SC_Extern) {
12640         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12641             << Var;
12642         Var->setInvalidDecl();
12643         return;
12644       }
12645       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12646                               diag::err_typecheck_decl_incomplete_type)) {
12647         Var->setInvalidDecl();
12648         return;
12649       }
12650       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12651         if (!RD->hasTrivialDefaultConstructor()) {
12652           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12653           Var->setInvalidDecl();
12654           return;
12655         }
12656       }
12657       // The declaration is unitialized, no need for further checks.
12658       return;
12659     }
12660 
12661     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12662     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12663         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12664       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12665                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12666 
12667 
12668     switch (DefKind) {
12669     case VarDecl::Definition:
12670       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12671         break;
12672 
12673       // We have an out-of-line definition of a static data member
12674       // that has an in-class initializer, so we type-check this like
12675       // a declaration.
12676       //
12677       LLVM_FALLTHROUGH;
12678 
12679     case VarDecl::DeclarationOnly:
12680       // It's only a declaration.
12681 
12682       // Block scope. C99 6.7p7: If an identifier for an object is
12683       // declared with no linkage (C99 6.2.2p6), the type for the
12684       // object shall be complete.
12685       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12686           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12687           RequireCompleteType(Var->getLocation(), Type,
12688                               diag::err_typecheck_decl_incomplete_type))
12689         Var->setInvalidDecl();
12690 
12691       // Make sure that the type is not abstract.
12692       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12693           RequireNonAbstractType(Var->getLocation(), Type,
12694                                  diag::err_abstract_type_in_decl,
12695                                  AbstractVariableType))
12696         Var->setInvalidDecl();
12697       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12698           Var->getStorageClass() == SC_PrivateExtern) {
12699         Diag(Var->getLocation(), diag::warn_private_extern);
12700         Diag(Var->getLocation(), diag::note_private_extern);
12701       }
12702 
12703       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12704           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12705         ExternalDeclarations.push_back(Var);
12706 
12707       return;
12708 
12709     case VarDecl::TentativeDefinition:
12710       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12711       // object that has file scope without an initializer, and without a
12712       // storage-class specifier or with the storage-class specifier "static",
12713       // constitutes a tentative definition. Note: A tentative definition with
12714       // external linkage is valid (C99 6.2.2p5).
12715       if (!Var->isInvalidDecl()) {
12716         if (const IncompleteArrayType *ArrayT
12717                                     = Context.getAsIncompleteArrayType(Type)) {
12718           if (RequireCompleteSizedType(
12719                   Var->getLocation(), ArrayT->getElementType(),
12720                   diag::err_array_incomplete_or_sizeless_type))
12721             Var->setInvalidDecl();
12722         } else if (Var->getStorageClass() == SC_Static) {
12723           // C99 6.9.2p3: If the declaration of an identifier for an object is
12724           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12725           // declared type shall not be an incomplete type.
12726           // NOTE: code such as the following
12727           //     static struct s;
12728           //     struct s { int a; };
12729           // is accepted by gcc. Hence here we issue a warning instead of
12730           // an error and we do not invalidate the static declaration.
12731           // NOTE: to avoid multiple warnings, only check the first declaration.
12732           if (Var->isFirstDecl())
12733             RequireCompleteType(Var->getLocation(), Type,
12734                                 diag::ext_typecheck_decl_incomplete_type);
12735         }
12736       }
12737 
12738       // Record the tentative definition; we're done.
12739       if (!Var->isInvalidDecl())
12740         TentativeDefinitions.push_back(Var);
12741       return;
12742     }
12743 
12744     // Provide a specific diagnostic for uninitialized variable
12745     // definitions with incomplete array type.
12746     if (Type->isIncompleteArrayType()) {
12747       Diag(Var->getLocation(),
12748            diag::err_typecheck_incomplete_array_needs_initializer);
12749       Var->setInvalidDecl();
12750       return;
12751     }
12752 
12753     // Provide a specific diagnostic for uninitialized variable
12754     // definitions with reference type.
12755     if (Type->isReferenceType()) {
12756       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12757           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12758       Var->setInvalidDecl();
12759       return;
12760     }
12761 
12762     // Do not attempt to type-check the default initializer for a
12763     // variable with dependent type.
12764     if (Type->isDependentType())
12765       return;
12766 
12767     if (Var->isInvalidDecl())
12768       return;
12769 
12770     if (!Var->hasAttr<AliasAttr>()) {
12771       if (RequireCompleteType(Var->getLocation(),
12772                               Context.getBaseElementType(Type),
12773                               diag::err_typecheck_decl_incomplete_type)) {
12774         Var->setInvalidDecl();
12775         return;
12776       }
12777     } else {
12778       return;
12779     }
12780 
12781     // The variable can not have an abstract class type.
12782     if (RequireNonAbstractType(Var->getLocation(), Type,
12783                                diag::err_abstract_type_in_decl,
12784                                AbstractVariableType)) {
12785       Var->setInvalidDecl();
12786       return;
12787     }
12788 
12789     // Check for jumps past the implicit initializer.  C++0x
12790     // clarifies that this applies to a "variable with automatic
12791     // storage duration", not a "local variable".
12792     // C++11 [stmt.dcl]p3
12793     //   A program that jumps from a point where a variable with automatic
12794     //   storage duration is not in scope to a point where it is in scope is
12795     //   ill-formed unless the variable has scalar type, class type with a
12796     //   trivial default constructor and a trivial destructor, a cv-qualified
12797     //   version of one of these types, or an array of one of the preceding
12798     //   types and is declared without an initializer.
12799     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12800       if (const RecordType *Record
12801             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12802         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12803         // Mark the function (if we're in one) for further checking even if the
12804         // looser rules of C++11 do not require such checks, so that we can
12805         // diagnose incompatibilities with C++98.
12806         if (!CXXRecord->isPOD())
12807           setFunctionHasBranchProtectedScope();
12808       }
12809     }
12810     // In OpenCL, we can't initialize objects in the __local address space,
12811     // even implicitly, so don't synthesize an implicit initializer.
12812     if (getLangOpts().OpenCL &&
12813         Var->getType().getAddressSpace() == LangAS::opencl_local)
12814       return;
12815     // C++03 [dcl.init]p9:
12816     //   If no initializer is specified for an object, and the
12817     //   object is of (possibly cv-qualified) non-POD class type (or
12818     //   array thereof), the object shall be default-initialized; if
12819     //   the object is of const-qualified type, the underlying class
12820     //   type shall have a user-declared default
12821     //   constructor. Otherwise, if no initializer is specified for
12822     //   a non- static object, the object and its subobjects, if
12823     //   any, have an indeterminate initial value); if the object
12824     //   or any of its subobjects are of const-qualified type, the
12825     //   program is ill-formed.
12826     // C++0x [dcl.init]p11:
12827     //   If no initializer is specified for an object, the object is
12828     //   default-initialized; [...].
12829     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12830     InitializationKind Kind
12831       = InitializationKind::CreateDefault(Var->getLocation());
12832 
12833     InitializationSequence InitSeq(*this, Entity, Kind, None);
12834     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12835 
12836     if (Init.get()) {
12837       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12838       // This is important for template substitution.
12839       Var->setInitStyle(VarDecl::CallInit);
12840     } else if (Init.isInvalid()) {
12841       // If default-init fails, attach a recovery-expr initializer to track
12842       // that initialization was attempted and failed.
12843       auto RecoveryExpr =
12844           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12845       if (RecoveryExpr.get())
12846         Var->setInit(RecoveryExpr.get());
12847     }
12848 
12849     CheckCompleteVariableDeclaration(Var);
12850   }
12851 }
12852 
12853 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12854   // If there is no declaration, there was an error parsing it. Ignore it.
12855   if (!D)
12856     return;
12857 
12858   VarDecl *VD = dyn_cast<VarDecl>(D);
12859   if (!VD) {
12860     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12861     D->setInvalidDecl();
12862     return;
12863   }
12864 
12865   VD->setCXXForRangeDecl(true);
12866 
12867   // for-range-declaration cannot be given a storage class specifier.
12868   int Error = -1;
12869   switch (VD->getStorageClass()) {
12870   case SC_None:
12871     break;
12872   case SC_Extern:
12873     Error = 0;
12874     break;
12875   case SC_Static:
12876     Error = 1;
12877     break;
12878   case SC_PrivateExtern:
12879     Error = 2;
12880     break;
12881   case SC_Auto:
12882     Error = 3;
12883     break;
12884   case SC_Register:
12885     Error = 4;
12886     break;
12887   }
12888 
12889   // for-range-declaration cannot be given a storage class specifier con't.
12890   switch (VD->getTSCSpec()) {
12891   case TSCS_thread_local:
12892     Error = 6;
12893     break;
12894   case TSCS___thread:
12895   case TSCS__Thread_local:
12896   case TSCS_unspecified:
12897     break;
12898   }
12899 
12900   if (Error != -1) {
12901     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12902         << VD << Error;
12903     D->setInvalidDecl();
12904   }
12905 }
12906 
12907 StmtResult
12908 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12909                                  IdentifierInfo *Ident,
12910                                  ParsedAttributes &Attrs,
12911                                  SourceLocation AttrEnd) {
12912   // C++1y [stmt.iter]p1:
12913   //   A range-based for statement of the form
12914   //      for ( for-range-identifier : for-range-initializer ) statement
12915   //   is equivalent to
12916   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12917   DeclSpec DS(Attrs.getPool().getFactory());
12918 
12919   const char *PrevSpec;
12920   unsigned DiagID;
12921   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12922                      getPrintingPolicy());
12923 
12924   Declarator D(DS, DeclaratorContext::ForInit);
12925   D.SetIdentifier(Ident, IdentLoc);
12926   D.takeAttributes(Attrs, AttrEnd);
12927 
12928   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12929                 IdentLoc);
12930   Decl *Var = ActOnDeclarator(S, D);
12931   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12932   FinalizeDeclaration(Var);
12933   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12934                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12935 }
12936 
12937 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12938   if (var->isInvalidDecl()) return;
12939 
12940   if (getLangOpts().OpenCL) {
12941     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12942     // initialiser
12943     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12944         !var->hasInit()) {
12945       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12946           << 1 /*Init*/;
12947       var->setInvalidDecl();
12948       return;
12949     }
12950   }
12951 
12952   // In Objective-C, don't allow jumps past the implicit initialization of a
12953   // local retaining variable.
12954   if (getLangOpts().ObjC &&
12955       var->hasLocalStorage()) {
12956     switch (var->getType().getObjCLifetime()) {
12957     case Qualifiers::OCL_None:
12958     case Qualifiers::OCL_ExplicitNone:
12959     case Qualifiers::OCL_Autoreleasing:
12960       break;
12961 
12962     case Qualifiers::OCL_Weak:
12963     case Qualifiers::OCL_Strong:
12964       setFunctionHasBranchProtectedScope();
12965       break;
12966     }
12967   }
12968 
12969   if (var->hasLocalStorage() &&
12970       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12971     setFunctionHasBranchProtectedScope();
12972 
12973   // Warn about externally-visible variables being defined without a
12974   // prior declaration.  We only want to do this for global
12975   // declarations, but we also specifically need to avoid doing it for
12976   // class members because the linkage of an anonymous class can
12977   // change if it's later given a typedef name.
12978   if (var->isThisDeclarationADefinition() &&
12979       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12980       var->isExternallyVisible() && var->hasLinkage() &&
12981       !var->isInline() && !var->getDescribedVarTemplate() &&
12982       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12983       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12984       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12985                                   var->getLocation())) {
12986     // Find a previous declaration that's not a definition.
12987     VarDecl *prev = var->getPreviousDecl();
12988     while (prev && prev->isThisDeclarationADefinition())
12989       prev = prev->getPreviousDecl();
12990 
12991     if (!prev) {
12992       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12993       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12994           << /* variable */ 0;
12995     }
12996   }
12997 
12998   // Cache the result of checking for constant initialization.
12999   Optional<bool> CacheHasConstInit;
13000   const Expr *CacheCulprit = nullptr;
13001   auto checkConstInit = [&]() mutable {
13002     if (!CacheHasConstInit)
13003       CacheHasConstInit = var->getInit()->isConstantInitializer(
13004             Context, var->getType()->isReferenceType(), &CacheCulprit);
13005     return *CacheHasConstInit;
13006   };
13007 
13008   if (var->getTLSKind() == VarDecl::TLS_Static) {
13009     if (var->getType().isDestructedType()) {
13010       // GNU C++98 edits for __thread, [basic.start.term]p3:
13011       //   The type of an object with thread storage duration shall not
13012       //   have a non-trivial destructor.
13013       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13014       if (getLangOpts().CPlusPlus11)
13015         Diag(var->getLocation(), diag::note_use_thread_local);
13016     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13017       if (!checkConstInit()) {
13018         // GNU C++98 edits for __thread, [basic.start.init]p4:
13019         //   An object of thread storage duration shall not require dynamic
13020         //   initialization.
13021         // FIXME: Need strict checking here.
13022         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13023           << CacheCulprit->getSourceRange();
13024         if (getLangOpts().CPlusPlus11)
13025           Diag(var->getLocation(), diag::note_use_thread_local);
13026       }
13027     }
13028   }
13029 
13030   // Apply section attributes and pragmas to global variables.
13031   bool GlobalStorage = var->hasGlobalStorage();
13032   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13033       !inTemplateInstantiation()) {
13034     PragmaStack<StringLiteral *> *Stack = nullptr;
13035     int SectionFlags = ASTContext::PSF_Read;
13036     if (var->getType().isConstQualified())
13037       Stack = &ConstSegStack;
13038     else if (!var->getInit()) {
13039       Stack = &BSSSegStack;
13040       SectionFlags |= ASTContext::PSF_Write;
13041     } else {
13042       Stack = &DataSegStack;
13043       SectionFlags |= ASTContext::PSF_Write;
13044     }
13045     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13046       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13047         SectionFlags |= ASTContext::PSF_Implicit;
13048       UnifySection(SA->getName(), SectionFlags, var);
13049     } else if (Stack->CurrentValue) {
13050       SectionFlags |= ASTContext::PSF_Implicit;
13051       auto SectionName = Stack->CurrentValue->getString();
13052       var->addAttr(SectionAttr::CreateImplicit(
13053           Context, SectionName, Stack->CurrentPragmaLocation,
13054           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13055       if (UnifySection(SectionName, SectionFlags, var))
13056         var->dropAttr<SectionAttr>();
13057     }
13058 
13059     // Apply the init_seg attribute if this has an initializer.  If the
13060     // initializer turns out to not be dynamic, we'll end up ignoring this
13061     // attribute.
13062     if (CurInitSeg && var->getInit())
13063       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13064                                                CurInitSegLoc,
13065                                                AttributeCommonInfo::AS_Pragma));
13066   }
13067 
13068   if (!var->getType()->isStructureType() && var->hasInit() &&
13069       isa<InitListExpr>(var->getInit())) {
13070     const auto *ILE = cast<InitListExpr>(var->getInit());
13071     unsigned NumInits = ILE->getNumInits();
13072     if (NumInits > 2)
13073       for (unsigned I = 0; I < NumInits; ++I) {
13074         const auto *Init = ILE->getInit(I);
13075         if (!Init)
13076           break;
13077         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13078         if (!SL)
13079           break;
13080 
13081         unsigned NumConcat = SL->getNumConcatenated();
13082         // Diagnose missing comma in string array initialization.
13083         // Do not warn when all the elements in the initializer are concatenated
13084         // together. Do not warn for macros too.
13085         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13086           bool OnlyOneMissingComma = true;
13087           for (unsigned J = I + 1; J < NumInits; ++J) {
13088             const auto *Init = ILE->getInit(J);
13089             if (!Init)
13090               break;
13091             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13092             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13093               OnlyOneMissingComma = false;
13094               break;
13095             }
13096           }
13097 
13098           if (OnlyOneMissingComma) {
13099             SmallVector<FixItHint, 1> Hints;
13100             for (unsigned i = 0; i < NumConcat - 1; ++i)
13101               Hints.push_back(FixItHint::CreateInsertion(
13102                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13103 
13104             Diag(SL->getStrTokenLoc(1),
13105                  diag::warn_concatenated_literal_array_init)
13106                 << Hints;
13107             Diag(SL->getBeginLoc(),
13108                  diag::note_concatenated_string_literal_silence);
13109           }
13110           // In any case, stop now.
13111           break;
13112         }
13113       }
13114   }
13115 
13116   // All the following checks are C++ only.
13117   if (!getLangOpts().CPlusPlus) {
13118     // If this variable must be emitted, add it as an initializer for the
13119     // current module.
13120     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13121       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13122     return;
13123   }
13124 
13125   QualType type = var->getType();
13126 
13127   if (var->hasAttr<BlocksAttr>())
13128     getCurFunction()->addByrefBlockVar(var);
13129 
13130   Expr *Init = var->getInit();
13131   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13132   QualType baseType = Context.getBaseElementType(type);
13133 
13134   // Check whether the initializer is sufficiently constant.
13135   if (!type->isDependentType() && Init && !Init->isValueDependent() &&
13136       (GlobalStorage || var->isConstexpr() ||
13137        var->mightBeUsableInConstantExpressions(Context))) {
13138     // If this variable might have a constant initializer or might be usable in
13139     // constant expressions, check whether or not it actually is now.  We can't
13140     // do this lazily, because the result might depend on things that change
13141     // later, such as which constexpr functions happen to be defined.
13142     SmallVector<PartialDiagnosticAt, 8> Notes;
13143     bool HasConstInit;
13144     if (!getLangOpts().CPlusPlus11) {
13145       // Prior to C++11, in contexts where a constant initializer is required,
13146       // the set of valid constant initializers is described by syntactic rules
13147       // in [expr.const]p2-6.
13148       // FIXME: Stricter checking for these rules would be useful for constinit /
13149       // -Wglobal-constructors.
13150       HasConstInit = checkConstInit();
13151 
13152       // Compute and cache the constant value, and remember that we have a
13153       // constant initializer.
13154       if (HasConstInit) {
13155         (void)var->checkForConstantInitialization(Notes);
13156         Notes.clear();
13157       } else if (CacheCulprit) {
13158         Notes.emplace_back(CacheCulprit->getExprLoc(),
13159                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13160         Notes.back().second << CacheCulprit->getSourceRange();
13161       }
13162     } else {
13163       // Evaluate the initializer to see if it's a constant initializer.
13164       HasConstInit = var->checkForConstantInitialization(Notes);
13165     }
13166 
13167     if (HasConstInit) {
13168       // FIXME: Consider replacing the initializer with a ConstantExpr.
13169     } else if (var->isConstexpr()) {
13170       SourceLocation DiagLoc = var->getLocation();
13171       // If the note doesn't add any useful information other than a source
13172       // location, fold it into the primary diagnostic.
13173       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13174                                    diag::note_invalid_subexpr_in_const_expr) {
13175         DiagLoc = Notes[0].first;
13176         Notes.clear();
13177       }
13178       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13179           << var << Init->getSourceRange();
13180       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13181         Diag(Notes[I].first, Notes[I].second);
13182     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13183       auto *Attr = var->getAttr<ConstInitAttr>();
13184       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13185           << Init->getSourceRange();
13186       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13187           << Attr->getRange() << Attr->isConstinit();
13188       for (auto &it : Notes)
13189         Diag(it.first, it.second);
13190     } else if (IsGlobal &&
13191                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13192                                            var->getLocation())) {
13193       // Warn about globals which don't have a constant initializer.  Don't
13194       // warn about globals with a non-trivial destructor because we already
13195       // warned about them.
13196       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13197       if (!(RD && !RD->hasTrivialDestructor())) {
13198         // checkConstInit() here permits trivial default initialization even in
13199         // C++11 onwards, where such an initializer is not a constant initializer
13200         // but nonetheless doesn't require a global constructor.
13201         if (!checkConstInit())
13202           Diag(var->getLocation(), diag::warn_global_constructor)
13203               << Init->getSourceRange();
13204       }
13205     }
13206   }
13207 
13208   // Require the destructor.
13209   if (!type->isDependentType())
13210     if (const RecordType *recordType = baseType->getAs<RecordType>())
13211       FinalizeVarWithDestructor(var, recordType);
13212 
13213   // If this variable must be emitted, add it as an initializer for the current
13214   // module.
13215   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13216     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13217 
13218   // Build the bindings if this is a structured binding declaration.
13219   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13220     CheckCompleteDecompositionDeclaration(DD);
13221 }
13222 
13223 /// Determines if a variable's alignment is dependent.
13224 static bool hasDependentAlignment(VarDecl *VD) {
13225   if (VD->getType()->isDependentType())
13226     return true;
13227   for (auto *I : VD->specific_attrs<AlignedAttr>())
13228     if (I->isAlignmentDependent())
13229       return true;
13230   return false;
13231 }
13232 
13233 /// Check if VD needs to be dllexport/dllimport due to being in a
13234 /// dllexport/import function.
13235 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13236   assert(VD->isStaticLocal());
13237 
13238   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13239 
13240   // Find outermost function when VD is in lambda function.
13241   while (FD && !getDLLAttr(FD) &&
13242          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13243          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13244     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13245   }
13246 
13247   if (!FD)
13248     return;
13249 
13250   // Static locals inherit dll attributes from their function.
13251   if (Attr *A = getDLLAttr(FD)) {
13252     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13253     NewAttr->setInherited(true);
13254     VD->addAttr(NewAttr);
13255   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13256     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13257     NewAttr->setInherited(true);
13258     VD->addAttr(NewAttr);
13259 
13260     // Export this function to enforce exporting this static variable even
13261     // if it is not used in this compilation unit.
13262     if (!FD->hasAttr<DLLExportAttr>())
13263       FD->addAttr(NewAttr);
13264 
13265   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13266     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13267     NewAttr->setInherited(true);
13268     VD->addAttr(NewAttr);
13269   }
13270 }
13271 
13272 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13273 /// any semantic actions necessary after any initializer has been attached.
13274 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13275   // Note that we are no longer parsing the initializer for this declaration.
13276   ParsingInitForAutoVars.erase(ThisDecl);
13277 
13278   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13279   if (!VD)
13280     return;
13281 
13282   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13283   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13284       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13285     if (PragmaClangBSSSection.Valid)
13286       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13287           Context, PragmaClangBSSSection.SectionName,
13288           PragmaClangBSSSection.PragmaLocation,
13289           AttributeCommonInfo::AS_Pragma));
13290     if (PragmaClangDataSection.Valid)
13291       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13292           Context, PragmaClangDataSection.SectionName,
13293           PragmaClangDataSection.PragmaLocation,
13294           AttributeCommonInfo::AS_Pragma));
13295     if (PragmaClangRodataSection.Valid)
13296       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13297           Context, PragmaClangRodataSection.SectionName,
13298           PragmaClangRodataSection.PragmaLocation,
13299           AttributeCommonInfo::AS_Pragma));
13300     if (PragmaClangRelroSection.Valid)
13301       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13302           Context, PragmaClangRelroSection.SectionName,
13303           PragmaClangRelroSection.PragmaLocation,
13304           AttributeCommonInfo::AS_Pragma));
13305   }
13306 
13307   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13308     for (auto *BD : DD->bindings()) {
13309       FinalizeDeclaration(BD);
13310     }
13311   }
13312 
13313   checkAttributesAfterMerging(*this, *VD);
13314 
13315   // Perform TLS alignment check here after attributes attached to the variable
13316   // which may affect the alignment have been processed. Only perform the check
13317   // if the target has a maximum TLS alignment (zero means no constraints).
13318   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13319     // Protect the check so that it's not performed on dependent types and
13320     // dependent alignments (we can't determine the alignment in that case).
13321     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13322         !VD->isInvalidDecl()) {
13323       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13324       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13325         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13326           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13327           << (unsigned)MaxAlignChars.getQuantity();
13328       }
13329     }
13330   }
13331 
13332   if (VD->isStaticLocal())
13333     CheckStaticLocalForDllExport(VD);
13334 
13335   // Perform check for initializers of device-side global variables.
13336   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13337   // 7.5). We must also apply the same checks to all __shared__
13338   // variables whether they are local or not. CUDA also allows
13339   // constant initializers for __constant__ and __device__ variables.
13340   if (getLangOpts().CUDA)
13341     checkAllowedCUDAInitializer(VD);
13342 
13343   // Grab the dllimport or dllexport attribute off of the VarDecl.
13344   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13345 
13346   // Imported static data members cannot be defined out-of-line.
13347   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13348     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13349         VD->isThisDeclarationADefinition()) {
13350       // We allow definitions of dllimport class template static data members
13351       // with a warning.
13352       CXXRecordDecl *Context =
13353         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13354       bool IsClassTemplateMember =
13355           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13356           Context->getDescribedClassTemplate();
13357 
13358       Diag(VD->getLocation(),
13359            IsClassTemplateMember
13360                ? diag::warn_attribute_dllimport_static_field_definition
13361                : diag::err_attribute_dllimport_static_field_definition);
13362       Diag(IA->getLocation(), diag::note_attribute);
13363       if (!IsClassTemplateMember)
13364         VD->setInvalidDecl();
13365     }
13366   }
13367 
13368   // dllimport/dllexport variables cannot be thread local, their TLS index
13369   // isn't exported with the variable.
13370   if (DLLAttr && VD->getTLSKind()) {
13371     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13372     if (F && getDLLAttr(F)) {
13373       assert(VD->isStaticLocal());
13374       // But if this is a static local in a dlimport/dllexport function, the
13375       // function will never be inlined, which means the var would never be
13376       // imported, so having it marked import/export is safe.
13377     } else {
13378       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13379                                                                     << DLLAttr;
13380       VD->setInvalidDecl();
13381     }
13382   }
13383 
13384   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13385     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13386       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13387           << Attr;
13388       VD->dropAttr<UsedAttr>();
13389     }
13390   }
13391   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13392     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13393       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13394           << Attr;
13395       VD->dropAttr<RetainAttr>();
13396     }
13397   }
13398 
13399   const DeclContext *DC = VD->getDeclContext();
13400   // If there's a #pragma GCC visibility in scope, and this isn't a class
13401   // member, set the visibility of this variable.
13402   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13403     AddPushedVisibilityAttribute(VD);
13404 
13405   // FIXME: Warn on unused var template partial specializations.
13406   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13407     MarkUnusedFileScopedDecl(VD);
13408 
13409   // Now we have parsed the initializer and can update the table of magic
13410   // tag values.
13411   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13412       !VD->getType()->isIntegralOrEnumerationType())
13413     return;
13414 
13415   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13416     const Expr *MagicValueExpr = VD->getInit();
13417     if (!MagicValueExpr) {
13418       continue;
13419     }
13420     Optional<llvm::APSInt> MagicValueInt;
13421     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13422       Diag(I->getRange().getBegin(),
13423            diag::err_type_tag_for_datatype_not_ice)
13424         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13425       continue;
13426     }
13427     if (MagicValueInt->getActiveBits() > 64) {
13428       Diag(I->getRange().getBegin(),
13429            diag::err_type_tag_for_datatype_too_large)
13430         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13431       continue;
13432     }
13433     uint64_t MagicValue = MagicValueInt->getZExtValue();
13434     RegisterTypeTagForDatatype(I->getArgumentKind(),
13435                                MagicValue,
13436                                I->getMatchingCType(),
13437                                I->getLayoutCompatible(),
13438                                I->getMustBeNull());
13439   }
13440 }
13441 
13442 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13443   auto *VD = dyn_cast<VarDecl>(DD);
13444   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13445 }
13446 
13447 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13448                                                    ArrayRef<Decl *> Group) {
13449   SmallVector<Decl*, 8> Decls;
13450 
13451   if (DS.isTypeSpecOwned())
13452     Decls.push_back(DS.getRepAsDecl());
13453 
13454   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13455   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13456   bool DiagnosedMultipleDecomps = false;
13457   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13458   bool DiagnosedNonDeducedAuto = false;
13459 
13460   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13461     if (Decl *D = Group[i]) {
13462       // For declarators, there are some additional syntactic-ish checks we need
13463       // to perform.
13464       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13465         if (!FirstDeclaratorInGroup)
13466           FirstDeclaratorInGroup = DD;
13467         if (!FirstDecompDeclaratorInGroup)
13468           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13469         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13470             !hasDeducedAuto(DD))
13471           FirstNonDeducedAutoInGroup = DD;
13472 
13473         if (FirstDeclaratorInGroup != DD) {
13474           // A decomposition declaration cannot be combined with any other
13475           // declaration in the same group.
13476           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13477             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13478                  diag::err_decomp_decl_not_alone)
13479                 << FirstDeclaratorInGroup->getSourceRange()
13480                 << DD->getSourceRange();
13481             DiagnosedMultipleDecomps = true;
13482           }
13483 
13484           // A declarator that uses 'auto' in any way other than to declare a
13485           // variable with a deduced type cannot be combined with any other
13486           // declarator in the same group.
13487           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13488             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13489                  diag::err_auto_non_deduced_not_alone)
13490                 << FirstNonDeducedAutoInGroup->getType()
13491                        ->hasAutoForTrailingReturnType()
13492                 << FirstDeclaratorInGroup->getSourceRange()
13493                 << DD->getSourceRange();
13494             DiagnosedNonDeducedAuto = true;
13495           }
13496         }
13497       }
13498 
13499       Decls.push_back(D);
13500     }
13501   }
13502 
13503   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13504     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13505       handleTagNumbering(Tag, S);
13506       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13507           getLangOpts().CPlusPlus)
13508         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13509     }
13510   }
13511 
13512   return BuildDeclaratorGroup(Decls);
13513 }
13514 
13515 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13516 /// group, performing any necessary semantic checking.
13517 Sema::DeclGroupPtrTy
13518 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13519   // C++14 [dcl.spec.auto]p7: (DR1347)
13520   //   If the type that replaces the placeholder type is not the same in each
13521   //   deduction, the program is ill-formed.
13522   if (Group.size() > 1) {
13523     QualType Deduced;
13524     VarDecl *DeducedDecl = nullptr;
13525     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13526       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13527       if (!D || D->isInvalidDecl())
13528         break;
13529       DeducedType *DT = D->getType()->getContainedDeducedType();
13530       if (!DT || DT->getDeducedType().isNull())
13531         continue;
13532       if (Deduced.isNull()) {
13533         Deduced = DT->getDeducedType();
13534         DeducedDecl = D;
13535       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13536         auto *AT = dyn_cast<AutoType>(DT);
13537         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13538                         diag::err_auto_different_deductions)
13539                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13540                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13541                    << D->getDeclName();
13542         if (DeducedDecl->hasInit())
13543           Dia << DeducedDecl->getInit()->getSourceRange();
13544         if (D->getInit())
13545           Dia << D->getInit()->getSourceRange();
13546         D->setInvalidDecl();
13547         break;
13548       }
13549     }
13550   }
13551 
13552   ActOnDocumentableDecls(Group);
13553 
13554   return DeclGroupPtrTy::make(
13555       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13556 }
13557 
13558 void Sema::ActOnDocumentableDecl(Decl *D) {
13559   ActOnDocumentableDecls(D);
13560 }
13561 
13562 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13563   // Don't parse the comment if Doxygen diagnostics are ignored.
13564   if (Group.empty() || !Group[0])
13565     return;
13566 
13567   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13568                       Group[0]->getLocation()) &&
13569       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13570                       Group[0]->getLocation()))
13571     return;
13572 
13573   if (Group.size() >= 2) {
13574     // This is a decl group.  Normally it will contain only declarations
13575     // produced from declarator list.  But in case we have any definitions or
13576     // additional declaration references:
13577     //   'typedef struct S {} S;'
13578     //   'typedef struct S *S;'
13579     //   'struct S *pS;'
13580     // FinalizeDeclaratorGroup adds these as separate declarations.
13581     Decl *MaybeTagDecl = Group[0];
13582     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13583       Group = Group.slice(1);
13584     }
13585   }
13586 
13587   // FIMXE: We assume every Decl in the group is in the same file.
13588   // This is false when preprocessor constructs the group from decls in
13589   // different files (e. g. macros or #include).
13590   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13591 }
13592 
13593 /// Common checks for a parameter-declaration that should apply to both function
13594 /// parameters and non-type template parameters.
13595 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13596   // Check that there are no default arguments inside the type of this
13597   // parameter.
13598   if (getLangOpts().CPlusPlus)
13599     CheckExtraCXXDefaultArguments(D);
13600 
13601   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13602   if (D.getCXXScopeSpec().isSet()) {
13603     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13604       << D.getCXXScopeSpec().getRange();
13605   }
13606 
13607   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13608   // simple identifier except [...irrelevant cases...].
13609   switch (D.getName().getKind()) {
13610   case UnqualifiedIdKind::IK_Identifier:
13611     break;
13612 
13613   case UnqualifiedIdKind::IK_OperatorFunctionId:
13614   case UnqualifiedIdKind::IK_ConversionFunctionId:
13615   case UnqualifiedIdKind::IK_LiteralOperatorId:
13616   case UnqualifiedIdKind::IK_ConstructorName:
13617   case UnqualifiedIdKind::IK_DestructorName:
13618   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13619   case UnqualifiedIdKind::IK_DeductionGuideName:
13620     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13621       << GetNameForDeclarator(D).getName();
13622     break;
13623 
13624   case UnqualifiedIdKind::IK_TemplateId:
13625   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13626     // GetNameForDeclarator would not produce a useful name in this case.
13627     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13628     break;
13629   }
13630 }
13631 
13632 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13633 /// to introduce parameters into function prototype scope.
13634 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13635   const DeclSpec &DS = D.getDeclSpec();
13636 
13637   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13638 
13639   // C++03 [dcl.stc]p2 also permits 'auto'.
13640   StorageClass SC = SC_None;
13641   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13642     SC = SC_Register;
13643     // In C++11, the 'register' storage class specifier is deprecated.
13644     // In C++17, it is not allowed, but we tolerate it as an extension.
13645     if (getLangOpts().CPlusPlus11) {
13646       Diag(DS.getStorageClassSpecLoc(),
13647            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13648                                      : diag::warn_deprecated_register)
13649         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13650     }
13651   } else if (getLangOpts().CPlusPlus &&
13652              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13653     SC = SC_Auto;
13654   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13655     Diag(DS.getStorageClassSpecLoc(),
13656          diag::err_invalid_storage_class_in_func_decl);
13657     D.getMutableDeclSpec().ClearStorageClassSpecs();
13658   }
13659 
13660   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13661     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13662       << DeclSpec::getSpecifierName(TSCS);
13663   if (DS.isInlineSpecified())
13664     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13665         << getLangOpts().CPlusPlus17;
13666   if (DS.hasConstexprSpecifier())
13667     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13668         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13669 
13670   DiagnoseFunctionSpecifiers(DS);
13671 
13672   CheckFunctionOrTemplateParamDeclarator(S, D);
13673 
13674   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13675   QualType parmDeclType = TInfo->getType();
13676 
13677   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13678   IdentifierInfo *II = D.getIdentifier();
13679   if (II) {
13680     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13681                    ForVisibleRedeclaration);
13682     LookupName(R, S);
13683     if (R.isSingleResult()) {
13684       NamedDecl *PrevDecl = R.getFoundDecl();
13685       if (PrevDecl->isTemplateParameter()) {
13686         // Maybe we will complain about the shadowed template parameter.
13687         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13688         // Just pretend that we didn't see the previous declaration.
13689         PrevDecl = nullptr;
13690       } else if (S->isDeclScope(PrevDecl)) {
13691         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13692         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13693 
13694         // Recover by removing the name
13695         II = nullptr;
13696         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13697         D.setInvalidType(true);
13698       }
13699     }
13700   }
13701 
13702   // Temporarily put parameter variables in the translation unit, not
13703   // the enclosing context.  This prevents them from accidentally
13704   // looking like class members in C++.
13705   ParmVarDecl *New =
13706       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13707                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13708 
13709   if (D.isInvalidType())
13710     New->setInvalidDecl();
13711 
13712   assert(S->isFunctionPrototypeScope());
13713   assert(S->getFunctionPrototypeDepth() >= 1);
13714   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13715                     S->getNextFunctionPrototypeIndex());
13716 
13717   // Add the parameter declaration into this scope.
13718   S->AddDecl(New);
13719   if (II)
13720     IdResolver.AddDecl(New);
13721 
13722   ProcessDeclAttributes(S, New, D);
13723 
13724   if (D.getDeclSpec().isModulePrivateSpecified())
13725     Diag(New->getLocation(), diag::err_module_private_local)
13726         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13727         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13728 
13729   if (New->hasAttr<BlocksAttr>()) {
13730     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13731   }
13732 
13733   if (getLangOpts().OpenCL)
13734     deduceOpenCLAddressSpace(New);
13735 
13736   return New;
13737 }
13738 
13739 /// Synthesizes a variable for a parameter arising from a
13740 /// typedef.
13741 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13742                                               SourceLocation Loc,
13743                                               QualType T) {
13744   /* FIXME: setting StartLoc == Loc.
13745      Would it be worth to modify callers so as to provide proper source
13746      location for the unnamed parameters, embedding the parameter's type? */
13747   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13748                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13749                                            SC_None, nullptr);
13750   Param->setImplicit();
13751   return Param;
13752 }
13753 
13754 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13755   // Don't diagnose unused-parameter errors in template instantiations; we
13756   // will already have done so in the template itself.
13757   if (inTemplateInstantiation())
13758     return;
13759 
13760   for (const ParmVarDecl *Parameter : Parameters) {
13761     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13762         !Parameter->hasAttr<UnusedAttr>()) {
13763       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13764         << Parameter->getDeclName();
13765     }
13766   }
13767 }
13768 
13769 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13770     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13771   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13772     return;
13773 
13774   // Warn if the return value is pass-by-value and larger than the specified
13775   // threshold.
13776   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13777     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13778     if (Size > LangOpts.NumLargeByValueCopy)
13779       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13780   }
13781 
13782   // Warn if any parameter is pass-by-value and larger than the specified
13783   // threshold.
13784   for (const ParmVarDecl *Parameter : Parameters) {
13785     QualType T = Parameter->getType();
13786     if (T->isDependentType() || !T.isPODType(Context))
13787       continue;
13788     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13789     if (Size > LangOpts.NumLargeByValueCopy)
13790       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13791           << Parameter << Size;
13792   }
13793 }
13794 
13795 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13796                                   SourceLocation NameLoc, IdentifierInfo *Name,
13797                                   QualType T, TypeSourceInfo *TSInfo,
13798                                   StorageClass SC) {
13799   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13800   if (getLangOpts().ObjCAutoRefCount &&
13801       T.getObjCLifetime() == Qualifiers::OCL_None &&
13802       T->isObjCLifetimeType()) {
13803 
13804     Qualifiers::ObjCLifetime lifetime;
13805 
13806     // Special cases for arrays:
13807     //   - if it's const, use __unsafe_unretained
13808     //   - otherwise, it's an error
13809     if (T->isArrayType()) {
13810       if (!T.isConstQualified()) {
13811         if (DelayedDiagnostics.shouldDelayDiagnostics())
13812           DelayedDiagnostics.add(
13813               sema::DelayedDiagnostic::makeForbiddenType(
13814               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13815         else
13816           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13817               << TSInfo->getTypeLoc().getSourceRange();
13818       }
13819       lifetime = Qualifiers::OCL_ExplicitNone;
13820     } else {
13821       lifetime = T->getObjCARCImplicitLifetime();
13822     }
13823     T = Context.getLifetimeQualifiedType(T, lifetime);
13824   }
13825 
13826   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13827                                          Context.getAdjustedParameterType(T),
13828                                          TSInfo, SC, nullptr);
13829 
13830   // Make a note if we created a new pack in the scope of a lambda, so that
13831   // we know that references to that pack must also be expanded within the
13832   // lambda scope.
13833   if (New->isParameterPack())
13834     if (auto *LSI = getEnclosingLambda())
13835       LSI->LocalPacks.push_back(New);
13836 
13837   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13838       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13839     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13840                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13841 
13842   // Parameters can not be abstract class types.
13843   // For record types, this is done by the AbstractClassUsageDiagnoser once
13844   // the class has been completely parsed.
13845   if (!CurContext->isRecord() &&
13846       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13847                              AbstractParamType))
13848     New->setInvalidDecl();
13849 
13850   // Parameter declarators cannot be interface types. All ObjC objects are
13851   // passed by reference.
13852   if (T->isObjCObjectType()) {
13853     SourceLocation TypeEndLoc =
13854         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13855     Diag(NameLoc,
13856          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13857       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13858     T = Context.getObjCObjectPointerType(T);
13859     New->setType(T);
13860   }
13861 
13862   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13863   // duration shall not be qualified by an address-space qualifier."
13864   // Since all parameters have automatic store duration, they can not have
13865   // an address space.
13866   if (T.getAddressSpace() != LangAS::Default &&
13867       // OpenCL allows function arguments declared to be an array of a type
13868       // to be qualified with an address space.
13869       !(getLangOpts().OpenCL &&
13870         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13871     Diag(NameLoc, diag::err_arg_with_address_space);
13872     New->setInvalidDecl();
13873   }
13874 
13875   // PPC MMA non-pointer types are not allowed as function argument types.
13876   if (Context.getTargetInfo().getTriple().isPPC64() &&
13877       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13878     New->setInvalidDecl();
13879   }
13880 
13881   return New;
13882 }
13883 
13884 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13885                                            SourceLocation LocAfterDecls) {
13886   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13887 
13888   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13889   // for a K&R function.
13890   if (!FTI.hasPrototype) {
13891     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13892       --i;
13893       if (FTI.Params[i].Param == nullptr) {
13894         SmallString<256> Code;
13895         llvm::raw_svector_ostream(Code)
13896             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13897         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13898             << FTI.Params[i].Ident
13899             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13900 
13901         // Implicitly declare the argument as type 'int' for lack of a better
13902         // type.
13903         AttributeFactory attrs;
13904         DeclSpec DS(attrs);
13905         const char* PrevSpec; // unused
13906         unsigned DiagID; // unused
13907         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13908                            DiagID, Context.getPrintingPolicy());
13909         // Use the identifier location for the type source range.
13910         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13911         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13912         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13913         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13914         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13915       }
13916     }
13917   }
13918 }
13919 
13920 Decl *
13921 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13922                               MultiTemplateParamsArg TemplateParameterLists,
13923                               SkipBodyInfo *SkipBody) {
13924   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13925   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13926   Scope *ParentScope = FnBodyScope->getParent();
13927 
13928   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13929   // we define a non-templated function definition, we will create a declaration
13930   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13931   // The base function declaration will have the equivalent of an `omp declare
13932   // variant` annotation which specifies the mangled definition as a
13933   // specialization function under the OpenMP context defined as part of the
13934   // `omp begin declare variant`.
13935   SmallVector<FunctionDecl *, 4> Bases;
13936   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13937     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13938         ParentScope, D, TemplateParameterLists, Bases);
13939 
13940   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
13941   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13942   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13943 
13944   if (!Bases.empty())
13945     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13946 
13947   return Dcl;
13948 }
13949 
13950 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13951   Consumer.HandleInlineFunctionDefinition(D);
13952 }
13953 
13954 static bool
13955 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13956                                 const FunctionDecl *&PossiblePrototype) {
13957   // Don't warn about invalid declarations.
13958   if (FD->isInvalidDecl())
13959     return false;
13960 
13961   // Or declarations that aren't global.
13962   if (!FD->isGlobal())
13963     return false;
13964 
13965   // Don't warn about C++ member functions.
13966   if (isa<CXXMethodDecl>(FD))
13967     return false;
13968 
13969   // Don't warn about 'main'.
13970   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13971     if (IdentifierInfo *II = FD->getIdentifier())
13972       if (II->isStr("main") || II->isStr("efi_main"))
13973         return false;
13974 
13975   // Don't warn about inline functions.
13976   if (FD->isInlined())
13977     return false;
13978 
13979   // Don't warn about function templates.
13980   if (FD->getDescribedFunctionTemplate())
13981     return false;
13982 
13983   // Don't warn about function template specializations.
13984   if (FD->isFunctionTemplateSpecialization())
13985     return false;
13986 
13987   // Don't warn for OpenCL kernels.
13988   if (FD->hasAttr<OpenCLKernelAttr>())
13989     return false;
13990 
13991   // Don't warn on explicitly deleted functions.
13992   if (FD->isDeleted())
13993     return false;
13994 
13995   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13996        Prev; Prev = Prev->getPreviousDecl()) {
13997     // Ignore any declarations that occur in function or method
13998     // scope, because they aren't visible from the header.
13999     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14000       continue;
14001 
14002     PossiblePrototype = Prev;
14003     return Prev->getType()->isFunctionNoProtoType();
14004   }
14005 
14006   return true;
14007 }
14008 
14009 void
14010 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14011                                    const FunctionDecl *EffectiveDefinition,
14012                                    SkipBodyInfo *SkipBody) {
14013   const FunctionDecl *Definition = EffectiveDefinition;
14014   if (!Definition &&
14015       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14016     return;
14017 
14018   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14019     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14020       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14021         // A merged copy of the same function, instantiated as a member of
14022         // the same class, is OK.
14023         if (declaresSameEntity(OrigFD, OrigDef) &&
14024             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14025                                cast<Decl>(FD->getLexicalDeclContext())))
14026           return;
14027       }
14028     }
14029   }
14030 
14031   if (canRedefineFunction(Definition, getLangOpts()))
14032     return;
14033 
14034   // Don't emit an error when this is redefinition of a typo-corrected
14035   // definition.
14036   if (TypoCorrectedFunctionDefinitions.count(Definition))
14037     return;
14038 
14039   // If we don't have a visible definition of the function, and it's inline or
14040   // a template, skip the new definition.
14041   if (SkipBody && !hasVisibleDefinition(Definition) &&
14042       (Definition->getFormalLinkage() == InternalLinkage ||
14043        Definition->isInlined() ||
14044        Definition->getDescribedFunctionTemplate() ||
14045        Definition->getNumTemplateParameterLists())) {
14046     SkipBody->ShouldSkip = true;
14047     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14048     if (auto *TD = Definition->getDescribedFunctionTemplate())
14049       makeMergedDefinitionVisible(TD);
14050     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14051     return;
14052   }
14053 
14054   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14055       Definition->getStorageClass() == SC_Extern)
14056     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14057         << FD << getLangOpts().CPlusPlus;
14058   else
14059     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14060 
14061   Diag(Definition->getLocation(), diag::note_previous_definition);
14062   FD->setInvalidDecl();
14063 }
14064 
14065 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14066                                    Sema &S) {
14067   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14068 
14069   LambdaScopeInfo *LSI = S.PushLambdaScope();
14070   LSI->CallOperator = CallOperator;
14071   LSI->Lambda = LambdaClass;
14072   LSI->ReturnType = CallOperator->getReturnType();
14073   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14074 
14075   if (LCD == LCD_None)
14076     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14077   else if (LCD == LCD_ByCopy)
14078     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14079   else if (LCD == LCD_ByRef)
14080     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14081   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14082 
14083   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14084   LSI->Mutable = !CallOperator->isConst();
14085 
14086   // Add the captures to the LSI so they can be noted as already
14087   // captured within tryCaptureVar.
14088   auto I = LambdaClass->field_begin();
14089   for (const auto &C : LambdaClass->captures()) {
14090     if (C.capturesVariable()) {
14091       VarDecl *VD = C.getCapturedVar();
14092       if (VD->isInitCapture())
14093         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14094       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14095       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14096           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14097           /*EllipsisLoc*/C.isPackExpansion()
14098                          ? C.getEllipsisLoc() : SourceLocation(),
14099           I->getType(), /*Invalid*/false);
14100 
14101     } else if (C.capturesThis()) {
14102       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14103                           C.getCaptureKind() == LCK_StarThis);
14104     } else {
14105       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14106                              I->getType());
14107     }
14108     ++I;
14109   }
14110 }
14111 
14112 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14113                                     SkipBodyInfo *SkipBody) {
14114   if (!D) {
14115     // Parsing the function declaration failed in some way. Push on a fake scope
14116     // anyway so we can try to parse the function body.
14117     PushFunctionScope();
14118     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14119     return D;
14120   }
14121 
14122   FunctionDecl *FD = nullptr;
14123 
14124   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14125     FD = FunTmpl->getTemplatedDecl();
14126   else
14127     FD = cast<FunctionDecl>(D);
14128 
14129   // Do not push if it is a lambda because one is already pushed when building
14130   // the lambda in ActOnStartOfLambdaDefinition().
14131   if (!isLambdaCallOperator(FD))
14132     PushExpressionEvaluationContext(
14133         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14134                           : ExprEvalContexts.back().Context);
14135 
14136   // Check for defining attributes before the check for redefinition.
14137   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14138     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14139     FD->dropAttr<AliasAttr>();
14140     FD->setInvalidDecl();
14141   }
14142   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14143     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14144     FD->dropAttr<IFuncAttr>();
14145     FD->setInvalidDecl();
14146   }
14147 
14148   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14149     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14150         Ctor->isDefaultConstructor() &&
14151         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14152       // If this is an MS ABI dllexport default constructor, instantiate any
14153       // default arguments.
14154       InstantiateDefaultCtorDefaultArgs(Ctor);
14155     }
14156   }
14157 
14158   // See if this is a redefinition. If 'will have body' (or similar) is already
14159   // set, then these checks were already performed when it was set.
14160   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14161       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14162     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14163 
14164     // If we're skipping the body, we're done. Don't enter the scope.
14165     if (SkipBody && SkipBody->ShouldSkip)
14166       return D;
14167   }
14168 
14169   // Mark this function as "will have a body eventually".  This lets users to
14170   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14171   // this function.
14172   FD->setWillHaveBody();
14173 
14174   // If we are instantiating a generic lambda call operator, push
14175   // a LambdaScopeInfo onto the function stack.  But use the information
14176   // that's already been calculated (ActOnLambdaExpr) to prime the current
14177   // LambdaScopeInfo.
14178   // When the template operator is being specialized, the LambdaScopeInfo,
14179   // has to be properly restored so that tryCaptureVariable doesn't try
14180   // and capture any new variables. In addition when calculating potential
14181   // captures during transformation of nested lambdas, it is necessary to
14182   // have the LSI properly restored.
14183   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14184     assert(inTemplateInstantiation() &&
14185            "There should be an active template instantiation on the stack "
14186            "when instantiating a generic lambda!");
14187     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14188   } else {
14189     // Enter a new function scope
14190     PushFunctionScope();
14191   }
14192 
14193   // Builtin functions cannot be defined.
14194   if (unsigned BuiltinID = FD->getBuiltinID()) {
14195     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14196         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14197       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14198       FD->setInvalidDecl();
14199     }
14200   }
14201 
14202   // The return type of a function definition must be complete
14203   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14204   QualType ResultType = FD->getReturnType();
14205   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14206       !FD->isInvalidDecl() &&
14207       RequireCompleteType(FD->getLocation(), ResultType,
14208                           diag::err_func_def_incomplete_result))
14209     FD->setInvalidDecl();
14210 
14211   if (FnBodyScope)
14212     PushDeclContext(FnBodyScope, FD);
14213 
14214   // Check the validity of our function parameters
14215   CheckParmsForFunctionDef(FD->parameters(),
14216                            /*CheckParameterNames=*/true);
14217 
14218   // Add non-parameter declarations already in the function to the current
14219   // scope.
14220   if (FnBodyScope) {
14221     for (Decl *NPD : FD->decls()) {
14222       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14223       if (!NonParmDecl)
14224         continue;
14225       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14226              "parameters should not be in newly created FD yet");
14227 
14228       // If the decl has a name, make it accessible in the current scope.
14229       if (NonParmDecl->getDeclName())
14230         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14231 
14232       // Similarly, dive into enums and fish their constants out, making them
14233       // accessible in this scope.
14234       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14235         for (auto *EI : ED->enumerators())
14236           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14237       }
14238     }
14239   }
14240 
14241   // Introduce our parameters into the function scope
14242   for (auto Param : FD->parameters()) {
14243     Param->setOwningFunction(FD);
14244 
14245     // If this has an identifier, add it to the scope stack.
14246     if (Param->getIdentifier() && FnBodyScope) {
14247       CheckShadow(FnBodyScope, Param);
14248 
14249       PushOnScopeChains(Param, FnBodyScope);
14250     }
14251   }
14252 
14253   // Ensure that the function's exception specification is instantiated.
14254   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14255     ResolveExceptionSpec(D->getLocation(), FPT);
14256 
14257   // dllimport cannot be applied to non-inline function definitions.
14258   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14259       !FD->isTemplateInstantiation()) {
14260     assert(!FD->hasAttr<DLLExportAttr>());
14261     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14262     FD->setInvalidDecl();
14263     return D;
14264   }
14265   // We want to attach documentation to original Decl (which might be
14266   // a function template).
14267   ActOnDocumentableDecl(D);
14268   if (getCurLexicalContext()->isObjCContainer() &&
14269       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14270       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14271     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14272 
14273   return D;
14274 }
14275 
14276 /// Given the set of return statements within a function body,
14277 /// compute the variables that are subject to the named return value
14278 /// optimization.
14279 ///
14280 /// Each of the variables that is subject to the named return value
14281 /// optimization will be marked as NRVO variables in the AST, and any
14282 /// return statement that has a marked NRVO variable as its NRVO candidate can
14283 /// use the named return value optimization.
14284 ///
14285 /// This function applies a very simplistic algorithm for NRVO: if every return
14286 /// statement in the scope of a variable has the same NRVO candidate, that
14287 /// candidate is an NRVO variable.
14288 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14289   ReturnStmt **Returns = Scope->Returns.data();
14290 
14291   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14292     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14293       if (!NRVOCandidate->isNRVOVariable())
14294         Returns[I]->setNRVOCandidate(nullptr);
14295     }
14296   }
14297 }
14298 
14299 bool Sema::canDelayFunctionBody(const Declarator &D) {
14300   // We can't delay parsing the body of a constexpr function template (yet).
14301   if (D.getDeclSpec().hasConstexprSpecifier())
14302     return false;
14303 
14304   // We can't delay parsing the body of a function template with a deduced
14305   // return type (yet).
14306   if (D.getDeclSpec().hasAutoTypeSpec()) {
14307     // If the placeholder introduces a non-deduced trailing return type,
14308     // we can still delay parsing it.
14309     if (D.getNumTypeObjects()) {
14310       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14311       if (Outer.Kind == DeclaratorChunk::Function &&
14312           Outer.Fun.hasTrailingReturnType()) {
14313         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14314         return Ty.isNull() || !Ty->isUndeducedType();
14315       }
14316     }
14317     return false;
14318   }
14319 
14320   return true;
14321 }
14322 
14323 bool Sema::canSkipFunctionBody(Decl *D) {
14324   // We cannot skip the body of a function (or function template) which is
14325   // constexpr, since we may need to evaluate its body in order to parse the
14326   // rest of the file.
14327   // We cannot skip the body of a function with an undeduced return type,
14328   // because any callers of that function need to know the type.
14329   if (const FunctionDecl *FD = D->getAsFunction()) {
14330     if (FD->isConstexpr())
14331       return false;
14332     // We can't simply call Type::isUndeducedType here, because inside template
14333     // auto can be deduced to a dependent type, which is not considered
14334     // "undeduced".
14335     if (FD->getReturnType()->getContainedDeducedType())
14336       return false;
14337   }
14338   return Consumer.shouldSkipFunctionBody(D);
14339 }
14340 
14341 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14342   if (!Decl)
14343     return nullptr;
14344   if (FunctionDecl *FD = Decl->getAsFunction())
14345     FD->setHasSkippedBody();
14346   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14347     MD->setHasSkippedBody();
14348   return Decl;
14349 }
14350 
14351 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14352   return ActOnFinishFunctionBody(D, BodyArg, false);
14353 }
14354 
14355 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14356 /// body.
14357 class ExitFunctionBodyRAII {
14358 public:
14359   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14360   ~ExitFunctionBodyRAII() {
14361     if (!IsLambda)
14362       S.PopExpressionEvaluationContext();
14363   }
14364 
14365 private:
14366   Sema &S;
14367   bool IsLambda = false;
14368 };
14369 
14370 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14371   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14372 
14373   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14374     if (EscapeInfo.count(BD))
14375       return EscapeInfo[BD];
14376 
14377     bool R = false;
14378     const BlockDecl *CurBD = BD;
14379 
14380     do {
14381       R = !CurBD->doesNotEscape();
14382       if (R)
14383         break;
14384       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14385     } while (CurBD);
14386 
14387     return EscapeInfo[BD] = R;
14388   };
14389 
14390   // If the location where 'self' is implicitly retained is inside a escaping
14391   // block, emit a diagnostic.
14392   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14393        S.ImplicitlyRetainedSelfLocs)
14394     if (IsOrNestedInEscapingBlock(P.second))
14395       S.Diag(P.first, diag::warn_implicitly_retains_self)
14396           << FixItHint::CreateInsertion(P.first, "self->");
14397 }
14398 
14399 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14400                                     bool IsInstantiation) {
14401   FunctionScopeInfo *FSI = getCurFunction();
14402   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14403 
14404   if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14405     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14406 
14407   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14408   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14409 
14410   if (getLangOpts().Coroutines && FSI->isCoroutine())
14411     CheckCompletedCoroutineBody(FD, Body);
14412 
14413   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14414   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14415   // meant to pop the context added in ActOnStartOfFunctionDef().
14416   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14417 
14418   if (FD) {
14419     FD->setBody(Body);
14420     FD->setWillHaveBody(false);
14421 
14422     if (getLangOpts().CPlusPlus14) {
14423       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14424           FD->getReturnType()->isUndeducedType()) {
14425         // If the function has a deduced result type but contains no 'return'
14426         // statements, the result type as written must be exactly 'auto', and
14427         // the deduced result type is 'void'.
14428         if (!FD->getReturnType()->getAs<AutoType>()) {
14429           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14430               << FD->getReturnType();
14431           FD->setInvalidDecl();
14432         } else {
14433           // Substitute 'void' for the 'auto' in the type.
14434           TypeLoc ResultType = getReturnTypeLoc(FD);
14435           Context.adjustDeducedFunctionResultType(
14436               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14437         }
14438       }
14439     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14440       // In C++11, we don't use 'auto' deduction rules for lambda call
14441       // operators because we don't support return type deduction.
14442       auto *LSI = getCurLambda();
14443       if (LSI->HasImplicitReturnType) {
14444         deduceClosureReturnType(*LSI);
14445 
14446         // C++11 [expr.prim.lambda]p4:
14447         //   [...] if there are no return statements in the compound-statement
14448         //   [the deduced type is] the type void
14449         QualType RetType =
14450             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14451 
14452         // Update the return type to the deduced type.
14453         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14454         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14455                                             Proto->getExtProtoInfo()));
14456       }
14457     }
14458 
14459     // If the function implicitly returns zero (like 'main') or is naked,
14460     // don't complain about missing return statements.
14461     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14462       WP.disableCheckFallThrough();
14463 
14464     // MSVC permits the use of pure specifier (=0) on function definition,
14465     // defined at class scope, warn about this non-standard construct.
14466     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14467       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14468 
14469     if (!FD->isInvalidDecl()) {
14470       // Don't diagnose unused parameters of defaulted or deleted functions.
14471       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14472         DiagnoseUnusedParameters(FD->parameters());
14473       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14474                                              FD->getReturnType(), FD);
14475 
14476       // If this is a structor, we need a vtable.
14477       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14478         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14479       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14480         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14481 
14482       // Try to apply the named return value optimization. We have to check
14483       // if we can do this here because lambdas keep return statements around
14484       // to deduce an implicit return type.
14485       if (FD->getReturnType()->isRecordType() &&
14486           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14487         computeNRVO(Body, FSI);
14488     }
14489 
14490     // GNU warning -Wmissing-prototypes:
14491     //   Warn if a global function is defined without a previous
14492     //   prototype declaration. This warning is issued even if the
14493     //   definition itself provides a prototype. The aim is to detect
14494     //   global functions that fail to be declared in header files.
14495     const FunctionDecl *PossiblePrototype = nullptr;
14496     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14497       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14498 
14499       if (PossiblePrototype) {
14500         // We found a declaration that is not a prototype,
14501         // but that could be a zero-parameter prototype
14502         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14503           TypeLoc TL = TI->getTypeLoc();
14504           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14505             Diag(PossiblePrototype->getLocation(),
14506                  diag::note_declaration_not_a_prototype)
14507                 << (FD->getNumParams() != 0)
14508                 << (FD->getNumParams() == 0
14509                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14510                         : FixItHint{});
14511         }
14512       } else {
14513         // Returns true if the token beginning at this Loc is `const`.
14514         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14515                                 const LangOptions &LangOpts) {
14516           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14517           if (LocInfo.first.isInvalid())
14518             return false;
14519 
14520           bool Invalid = false;
14521           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14522           if (Invalid)
14523             return false;
14524 
14525           if (LocInfo.second > Buffer.size())
14526             return false;
14527 
14528           const char *LexStart = Buffer.data() + LocInfo.second;
14529           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14530 
14531           return StartTok.consume_front("const") &&
14532                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14533                   StartTok.startswith("/*") || StartTok.startswith("//"));
14534         };
14535 
14536         auto findBeginLoc = [&]() {
14537           // If the return type has `const` qualifier, we want to insert
14538           // `static` before `const` (and not before the typename).
14539           if ((FD->getReturnType()->isAnyPointerType() &&
14540                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14541               FD->getReturnType().isConstQualified()) {
14542             // But only do this if we can determine where the `const` is.
14543 
14544             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14545                              getLangOpts()))
14546 
14547               return FD->getBeginLoc();
14548           }
14549           return FD->getTypeSpecStartLoc();
14550         };
14551         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14552             << /* function */ 1
14553             << (FD->getStorageClass() == SC_None
14554                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14555                     : FixItHint{});
14556       }
14557 
14558       // GNU warning -Wstrict-prototypes
14559       //   Warn if K&R function is defined without a previous declaration.
14560       //   This warning is issued only if the definition itself does not provide
14561       //   a prototype. Only K&R definitions do not provide a prototype.
14562       if (!FD->hasWrittenPrototype()) {
14563         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14564         TypeLoc TL = TI->getTypeLoc();
14565         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14566         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14567       }
14568     }
14569 
14570     // Warn on CPUDispatch with an actual body.
14571     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14572       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14573         if (!CmpndBody->body_empty())
14574           Diag(CmpndBody->body_front()->getBeginLoc(),
14575                diag::warn_dispatch_body_ignored);
14576 
14577     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14578       const CXXMethodDecl *KeyFunction;
14579       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14580           MD->isVirtual() &&
14581           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14582           MD == KeyFunction->getCanonicalDecl()) {
14583         // Update the key-function state if necessary for this ABI.
14584         if (FD->isInlined() &&
14585             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14586           Context.setNonKeyFunction(MD);
14587 
14588           // If the newly-chosen key function is already defined, then we
14589           // need to mark the vtable as used retroactively.
14590           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14591           const FunctionDecl *Definition;
14592           if (KeyFunction && KeyFunction->isDefined(Definition))
14593             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14594         } else {
14595           // We just defined they key function; mark the vtable as used.
14596           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14597         }
14598       }
14599     }
14600 
14601     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14602            "Function parsing confused");
14603   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14604     assert(MD == getCurMethodDecl() && "Method parsing confused");
14605     MD->setBody(Body);
14606     if (!MD->isInvalidDecl()) {
14607       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14608                                              MD->getReturnType(), MD);
14609 
14610       if (Body)
14611         computeNRVO(Body, FSI);
14612     }
14613     if (FSI->ObjCShouldCallSuper) {
14614       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14615           << MD->getSelector().getAsString();
14616       FSI->ObjCShouldCallSuper = false;
14617     }
14618     if (FSI->ObjCWarnForNoDesignatedInitChain) {
14619       const ObjCMethodDecl *InitMethod = nullptr;
14620       bool isDesignated =
14621           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14622       assert(isDesignated && InitMethod);
14623       (void)isDesignated;
14624 
14625       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14626         auto IFace = MD->getClassInterface();
14627         if (!IFace)
14628           return false;
14629         auto SuperD = IFace->getSuperClass();
14630         if (!SuperD)
14631           return false;
14632         return SuperD->getIdentifier() ==
14633             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14634       };
14635       // Don't issue this warning for unavailable inits or direct subclasses
14636       // of NSObject.
14637       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14638         Diag(MD->getLocation(),
14639              diag::warn_objc_designated_init_missing_super_call);
14640         Diag(InitMethod->getLocation(),
14641              diag::note_objc_designated_init_marked_here);
14642       }
14643       FSI->ObjCWarnForNoDesignatedInitChain = false;
14644     }
14645     if (FSI->ObjCWarnForNoInitDelegation) {
14646       // Don't issue this warning for unavaialable inits.
14647       if (!MD->isUnavailable())
14648         Diag(MD->getLocation(),
14649              diag::warn_objc_secondary_init_missing_init_call);
14650       FSI->ObjCWarnForNoInitDelegation = false;
14651     }
14652 
14653     diagnoseImplicitlyRetainedSelf(*this);
14654   } else {
14655     // Parsing the function declaration failed in some way. Pop the fake scope
14656     // we pushed on.
14657     PopFunctionScopeInfo(ActivePolicy, dcl);
14658     return nullptr;
14659   }
14660 
14661   if (Body && FSI->HasPotentialAvailabilityViolations)
14662     DiagnoseUnguardedAvailabilityViolations(dcl);
14663 
14664   assert(!FSI->ObjCShouldCallSuper &&
14665          "This should only be set for ObjC methods, which should have been "
14666          "handled in the block above.");
14667 
14668   // Verify and clean out per-function state.
14669   if (Body && (!FD || !FD->isDefaulted())) {
14670     // C++ constructors that have function-try-blocks can't have return
14671     // statements in the handlers of that block. (C++ [except.handle]p14)
14672     // Verify this.
14673     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14674       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14675 
14676     // Verify that gotos and switch cases don't jump into scopes illegally.
14677     if (FSI->NeedsScopeChecking() &&
14678         !PP.isCodeCompletionEnabled())
14679       DiagnoseInvalidJumps(Body);
14680 
14681     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14682       if (!Destructor->getParent()->isDependentType())
14683         CheckDestructor(Destructor);
14684 
14685       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14686                                              Destructor->getParent());
14687     }
14688 
14689     // If any errors have occurred, clear out any temporaries that may have
14690     // been leftover. This ensures that these temporaries won't be picked up for
14691     // deletion in some later function.
14692     if (hasUncompilableErrorOccurred() ||
14693         getDiagnostics().getSuppressAllDiagnostics()) {
14694       DiscardCleanupsInEvaluationContext();
14695     }
14696     if (!hasUncompilableErrorOccurred() &&
14697         !isa<FunctionTemplateDecl>(dcl)) {
14698       // Since the body is valid, issue any analysis-based warnings that are
14699       // enabled.
14700       ActivePolicy = &WP;
14701     }
14702 
14703     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14704         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14705       FD->setInvalidDecl();
14706 
14707     if (FD && FD->hasAttr<NakedAttr>()) {
14708       for (const Stmt *S : Body->children()) {
14709         // Allow local register variables without initializer as they don't
14710         // require prologue.
14711         bool RegisterVariables = false;
14712         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14713           for (const auto *Decl : DS->decls()) {
14714             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14715               RegisterVariables =
14716                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14717               if (!RegisterVariables)
14718                 break;
14719             }
14720           }
14721         }
14722         if (RegisterVariables)
14723           continue;
14724         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14725           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14726           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14727           FD->setInvalidDecl();
14728           break;
14729         }
14730       }
14731     }
14732 
14733     assert(ExprCleanupObjects.size() ==
14734                ExprEvalContexts.back().NumCleanupObjects &&
14735            "Leftover temporaries in function");
14736     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14737     assert(MaybeODRUseExprs.empty() &&
14738            "Leftover expressions for odr-use checking");
14739   }
14740 
14741   if (!IsInstantiation)
14742     PopDeclContext();
14743 
14744   PopFunctionScopeInfo(ActivePolicy, dcl);
14745   // If any errors have occurred, clear out any temporaries that may have
14746   // been leftover. This ensures that these temporaries won't be picked up for
14747   // deletion in some later function.
14748   if (hasUncompilableErrorOccurred()) {
14749     DiscardCleanupsInEvaluationContext();
14750   }
14751 
14752   if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14753     auto ES = getEmissionStatus(FD);
14754     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14755         ES == Sema::FunctionEmissionStatus::Unknown)
14756       DeclsToCheckForDeferredDiags.push_back(FD);
14757   }
14758 
14759   return dcl;
14760 }
14761 
14762 /// When we finish delayed parsing of an attribute, we must attach it to the
14763 /// relevant Decl.
14764 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14765                                        ParsedAttributes &Attrs) {
14766   // Always attach attributes to the underlying decl.
14767   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14768     D = TD->getTemplatedDecl();
14769   ProcessDeclAttributeList(S, D, Attrs);
14770 
14771   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14772     if (Method->isStatic())
14773       checkThisInStaticMemberFunctionAttributes(Method);
14774 }
14775 
14776 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14777 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14778 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14779                                           IdentifierInfo &II, Scope *S) {
14780   // Find the scope in which the identifier is injected and the corresponding
14781   // DeclContext.
14782   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14783   // In that case, we inject the declaration into the translation unit scope
14784   // instead.
14785   Scope *BlockScope = S;
14786   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14787     BlockScope = BlockScope->getParent();
14788 
14789   Scope *ContextScope = BlockScope;
14790   while (!ContextScope->getEntity())
14791     ContextScope = ContextScope->getParent();
14792   ContextRAII SavedContext(*this, ContextScope->getEntity());
14793 
14794   // Before we produce a declaration for an implicitly defined
14795   // function, see whether there was a locally-scoped declaration of
14796   // this name as a function or variable. If so, use that
14797   // (non-visible) declaration, and complain about it.
14798   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14799   if (ExternCPrev) {
14800     // We still need to inject the function into the enclosing block scope so
14801     // that later (non-call) uses can see it.
14802     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14803 
14804     // C89 footnote 38:
14805     //   If in fact it is not defined as having type "function returning int",
14806     //   the behavior is undefined.
14807     if (!isa<FunctionDecl>(ExternCPrev) ||
14808         !Context.typesAreCompatible(
14809             cast<FunctionDecl>(ExternCPrev)->getType(),
14810             Context.getFunctionNoProtoType(Context.IntTy))) {
14811       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14812           << ExternCPrev << !getLangOpts().C99;
14813       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14814       return ExternCPrev;
14815     }
14816   }
14817 
14818   // Extension in C99.  Legal in C90, but warn about it.
14819   unsigned diag_id;
14820   if (II.getName().startswith("__builtin_"))
14821     diag_id = diag::warn_builtin_unknown;
14822   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14823   else if (getLangOpts().OpenCL)
14824     diag_id = diag::err_opencl_implicit_function_decl;
14825   else if (getLangOpts().C99)
14826     diag_id = diag::ext_implicit_function_decl;
14827   else
14828     diag_id = diag::warn_implicit_function_decl;
14829   Diag(Loc, diag_id) << &II;
14830 
14831   // If we found a prior declaration of this function, don't bother building
14832   // another one. We've already pushed that one into scope, so there's nothing
14833   // more to do.
14834   if (ExternCPrev)
14835     return ExternCPrev;
14836 
14837   // Because typo correction is expensive, only do it if the implicit
14838   // function declaration is going to be treated as an error.
14839   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14840     TypoCorrection Corrected;
14841     DeclFilterCCC<FunctionDecl> CCC{};
14842     if (S && (Corrected =
14843                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14844                               S, nullptr, CCC, CTK_NonError)))
14845       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14846                    /*ErrorRecovery*/false);
14847   }
14848 
14849   // Set a Declarator for the implicit definition: int foo();
14850   const char *Dummy;
14851   AttributeFactory attrFactory;
14852   DeclSpec DS(attrFactory);
14853   unsigned DiagID;
14854   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14855                                   Context.getPrintingPolicy());
14856   (void)Error; // Silence warning.
14857   assert(!Error && "Error setting up implicit decl!");
14858   SourceLocation NoLoc;
14859   Declarator D(DS, DeclaratorContext::Block);
14860   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14861                                              /*IsAmbiguous=*/false,
14862                                              /*LParenLoc=*/NoLoc,
14863                                              /*Params=*/nullptr,
14864                                              /*NumParams=*/0,
14865                                              /*EllipsisLoc=*/NoLoc,
14866                                              /*RParenLoc=*/NoLoc,
14867                                              /*RefQualifierIsLvalueRef=*/true,
14868                                              /*RefQualifierLoc=*/NoLoc,
14869                                              /*MutableLoc=*/NoLoc, EST_None,
14870                                              /*ESpecRange=*/SourceRange(),
14871                                              /*Exceptions=*/nullptr,
14872                                              /*ExceptionRanges=*/nullptr,
14873                                              /*NumExceptions=*/0,
14874                                              /*NoexceptExpr=*/nullptr,
14875                                              /*ExceptionSpecTokens=*/nullptr,
14876                                              /*DeclsInPrototype=*/None, Loc,
14877                                              Loc, D),
14878                 std::move(DS.getAttributes()), SourceLocation());
14879   D.SetIdentifier(&II, Loc);
14880 
14881   // Insert this function into the enclosing block scope.
14882   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14883   FD->setImplicit();
14884 
14885   AddKnownFunctionAttributes(FD);
14886 
14887   return FD;
14888 }
14889 
14890 /// If this function is a C++ replaceable global allocation function
14891 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14892 /// adds any function attributes that we know a priori based on the standard.
14893 ///
14894 /// We need to check for duplicate attributes both here and where user-written
14895 /// attributes are applied to declarations.
14896 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14897     FunctionDecl *FD) {
14898   if (FD->isInvalidDecl())
14899     return;
14900 
14901   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14902       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14903     return;
14904 
14905   Optional<unsigned> AlignmentParam;
14906   bool IsNothrow = false;
14907   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14908     return;
14909 
14910   // C++2a [basic.stc.dynamic.allocation]p4:
14911   //   An allocation function that has a non-throwing exception specification
14912   //   indicates failure by returning a null pointer value. Any other allocation
14913   //   function never returns a null pointer value and indicates failure only by
14914   //   throwing an exception [...]
14915   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14916     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14917 
14918   // C++2a [basic.stc.dynamic.allocation]p2:
14919   //   An allocation function attempts to allocate the requested amount of
14920   //   storage. [...] If the request succeeds, the value returned by a
14921   //   replaceable allocation function is a [...] pointer value p0 different
14922   //   from any previously returned value p1 [...]
14923   //
14924   // However, this particular information is being added in codegen,
14925   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14926 
14927   // C++2a [basic.stc.dynamic.allocation]p2:
14928   //   An allocation function attempts to allocate the requested amount of
14929   //   storage. If it is successful, it returns the address of the start of a
14930   //   block of storage whose length in bytes is at least as large as the
14931   //   requested size.
14932   if (!FD->hasAttr<AllocSizeAttr>()) {
14933     FD->addAttr(AllocSizeAttr::CreateImplicit(
14934         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14935         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14936   }
14937 
14938   // C++2a [basic.stc.dynamic.allocation]p3:
14939   //   For an allocation function [...], the pointer returned on a successful
14940   //   call shall represent the address of storage that is aligned as follows:
14941   //   (3.1) If the allocation function takes an argument of type
14942   //         std​::​align_­val_­t, the storage will have the alignment
14943   //         specified by the value of this argument.
14944   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14945     FD->addAttr(AllocAlignAttr::CreateImplicit(
14946         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14947   }
14948 
14949   // FIXME:
14950   // C++2a [basic.stc.dynamic.allocation]p3:
14951   //   For an allocation function [...], the pointer returned on a successful
14952   //   call shall represent the address of storage that is aligned as follows:
14953   //   (3.2) Otherwise, if the allocation function is named operator new[],
14954   //         the storage is aligned for any object that does not have
14955   //         new-extended alignment ([basic.align]) and is no larger than the
14956   //         requested size.
14957   //   (3.3) Otherwise, the storage is aligned for any object that does not
14958   //         have new-extended alignment and is of the requested size.
14959 }
14960 
14961 /// Adds any function attributes that we know a priori based on
14962 /// the declaration of this function.
14963 ///
14964 /// These attributes can apply both to implicitly-declared builtins
14965 /// (like __builtin___printf_chk) or to library-declared functions
14966 /// like NSLog or printf.
14967 ///
14968 /// We need to check for duplicate attributes both here and where user-written
14969 /// attributes are applied to declarations.
14970 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14971   if (FD->isInvalidDecl())
14972     return;
14973 
14974   // If this is a built-in function, map its builtin attributes to
14975   // actual attributes.
14976   if (unsigned BuiltinID = FD->getBuiltinID()) {
14977     // Handle printf-formatting attributes.
14978     unsigned FormatIdx;
14979     bool HasVAListArg;
14980     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14981       if (!FD->hasAttr<FormatAttr>()) {
14982         const char *fmt = "printf";
14983         unsigned int NumParams = FD->getNumParams();
14984         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14985             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14986           fmt = "NSString";
14987         FD->addAttr(FormatAttr::CreateImplicit(Context,
14988                                                &Context.Idents.get(fmt),
14989                                                FormatIdx+1,
14990                                                HasVAListArg ? 0 : FormatIdx+2,
14991                                                FD->getLocation()));
14992       }
14993     }
14994     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14995                                              HasVAListArg)) {
14996      if (!FD->hasAttr<FormatAttr>())
14997        FD->addAttr(FormatAttr::CreateImplicit(Context,
14998                                               &Context.Idents.get("scanf"),
14999                                               FormatIdx+1,
15000                                               HasVAListArg ? 0 : FormatIdx+2,
15001                                               FD->getLocation()));
15002     }
15003 
15004     // Handle automatically recognized callbacks.
15005     SmallVector<int, 4> Encoding;
15006     if (!FD->hasAttr<CallbackAttr>() &&
15007         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15008       FD->addAttr(CallbackAttr::CreateImplicit(
15009           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15010 
15011     // Mark const if we don't care about errno and that is the only thing
15012     // preventing the function from being const. This allows IRgen to use LLVM
15013     // intrinsics for such functions.
15014     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15015         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15016       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15017 
15018     // We make "fma" on some platforms const because we know it does not set
15019     // errno in those environments even though it could set errno based on the
15020     // C standard.
15021     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15022     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15023         !FD->hasAttr<ConstAttr>()) {
15024       switch (BuiltinID) {
15025       case Builtin::BI__builtin_fma:
15026       case Builtin::BI__builtin_fmaf:
15027       case Builtin::BI__builtin_fmal:
15028       case Builtin::BIfma:
15029       case Builtin::BIfmaf:
15030       case Builtin::BIfmal:
15031         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15032         break;
15033       default:
15034         break;
15035       }
15036     }
15037 
15038     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15039         !FD->hasAttr<ReturnsTwiceAttr>())
15040       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15041                                          FD->getLocation()));
15042     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15043       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15044     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15045       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15046     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15047       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15048     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15049         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15050       // Add the appropriate attribute, depending on the CUDA compilation mode
15051       // and which target the builtin belongs to. For example, during host
15052       // compilation, aux builtins are __device__, while the rest are __host__.
15053       if (getLangOpts().CUDAIsDevice !=
15054           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15055         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15056       else
15057         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15058     }
15059   }
15060 
15061   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15062 
15063   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15064   // throw, add an implicit nothrow attribute to any extern "C" function we come
15065   // across.
15066   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15067       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15068     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15069     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15070       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15071   }
15072 
15073   IdentifierInfo *Name = FD->getIdentifier();
15074   if (!Name)
15075     return;
15076   if ((!getLangOpts().CPlusPlus &&
15077        FD->getDeclContext()->isTranslationUnit()) ||
15078       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15079        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15080        LinkageSpecDecl::lang_c)) {
15081     // Okay: this could be a libc/libm/Objective-C function we know
15082     // about.
15083   } else
15084     return;
15085 
15086   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15087     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15088     // target-specific builtins, perhaps?
15089     if (!FD->hasAttr<FormatAttr>())
15090       FD->addAttr(FormatAttr::CreateImplicit(Context,
15091                                              &Context.Idents.get("printf"), 2,
15092                                              Name->isStr("vasprintf") ? 0 : 3,
15093                                              FD->getLocation()));
15094   }
15095 
15096   if (Name->isStr("__CFStringMakeConstantString")) {
15097     // We already have a __builtin___CFStringMakeConstantString,
15098     // but builds that use -fno-constant-cfstrings don't go through that.
15099     if (!FD->hasAttr<FormatArgAttr>())
15100       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15101                                                 FD->getLocation()));
15102   }
15103 }
15104 
15105 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15106                                     TypeSourceInfo *TInfo) {
15107   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15108   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15109 
15110   if (!TInfo) {
15111     assert(D.isInvalidType() && "no declarator info for valid type");
15112     TInfo = Context.getTrivialTypeSourceInfo(T);
15113   }
15114 
15115   // Scope manipulation handled by caller.
15116   TypedefDecl *NewTD =
15117       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15118                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15119 
15120   // Bail out immediately if we have an invalid declaration.
15121   if (D.isInvalidType()) {
15122     NewTD->setInvalidDecl();
15123     return NewTD;
15124   }
15125 
15126   if (D.getDeclSpec().isModulePrivateSpecified()) {
15127     if (CurContext->isFunctionOrMethod())
15128       Diag(NewTD->getLocation(), diag::err_module_private_local)
15129           << 2 << NewTD
15130           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15131           << FixItHint::CreateRemoval(
15132                  D.getDeclSpec().getModulePrivateSpecLoc());
15133     else
15134       NewTD->setModulePrivate();
15135   }
15136 
15137   // C++ [dcl.typedef]p8:
15138   //   If the typedef declaration defines an unnamed class (or
15139   //   enum), the first typedef-name declared by the declaration
15140   //   to be that class type (or enum type) is used to denote the
15141   //   class type (or enum type) for linkage purposes only.
15142   // We need to check whether the type was declared in the declaration.
15143   switch (D.getDeclSpec().getTypeSpecType()) {
15144   case TST_enum:
15145   case TST_struct:
15146   case TST_interface:
15147   case TST_union:
15148   case TST_class: {
15149     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15150     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15151     break;
15152   }
15153 
15154   default:
15155     break;
15156   }
15157 
15158   return NewTD;
15159 }
15160 
15161 /// Check that this is a valid underlying type for an enum declaration.
15162 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15163   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15164   QualType T = TI->getType();
15165 
15166   if (T->isDependentType())
15167     return false;
15168 
15169   // This doesn't use 'isIntegralType' despite the error message mentioning
15170   // integral type because isIntegralType would also allow enum types in C.
15171   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15172     if (BT->isInteger())
15173       return false;
15174 
15175   if (T->isExtIntType())
15176     return false;
15177 
15178   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15179 }
15180 
15181 /// Check whether this is a valid redeclaration of a previous enumeration.
15182 /// \return true if the redeclaration was invalid.
15183 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15184                                   QualType EnumUnderlyingTy, bool IsFixed,
15185                                   const EnumDecl *Prev) {
15186   if (IsScoped != Prev->isScoped()) {
15187     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15188       << Prev->isScoped();
15189     Diag(Prev->getLocation(), diag::note_previous_declaration);
15190     return true;
15191   }
15192 
15193   if (IsFixed && Prev->isFixed()) {
15194     if (!EnumUnderlyingTy->isDependentType() &&
15195         !Prev->getIntegerType()->isDependentType() &&
15196         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15197                                         Prev->getIntegerType())) {
15198       // TODO: Highlight the underlying type of the redeclaration.
15199       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15200         << EnumUnderlyingTy << Prev->getIntegerType();
15201       Diag(Prev->getLocation(), diag::note_previous_declaration)
15202           << Prev->getIntegerTypeRange();
15203       return true;
15204     }
15205   } else if (IsFixed != Prev->isFixed()) {
15206     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15207       << Prev->isFixed();
15208     Diag(Prev->getLocation(), diag::note_previous_declaration);
15209     return true;
15210   }
15211 
15212   return false;
15213 }
15214 
15215 /// Get diagnostic %select index for tag kind for
15216 /// redeclaration diagnostic message.
15217 /// WARNING: Indexes apply to particular diagnostics only!
15218 ///
15219 /// \returns diagnostic %select index.
15220 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15221   switch (Tag) {
15222   case TTK_Struct: return 0;
15223   case TTK_Interface: return 1;
15224   case TTK_Class:  return 2;
15225   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15226   }
15227 }
15228 
15229 /// Determine if tag kind is a class-key compatible with
15230 /// class for redeclaration (class, struct, or __interface).
15231 ///
15232 /// \returns true iff the tag kind is compatible.
15233 static bool isClassCompatTagKind(TagTypeKind Tag)
15234 {
15235   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15236 }
15237 
15238 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15239                                              TagTypeKind TTK) {
15240   if (isa<TypedefDecl>(PrevDecl))
15241     return NTK_Typedef;
15242   else if (isa<TypeAliasDecl>(PrevDecl))
15243     return NTK_TypeAlias;
15244   else if (isa<ClassTemplateDecl>(PrevDecl))
15245     return NTK_Template;
15246   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15247     return NTK_TypeAliasTemplate;
15248   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15249     return NTK_TemplateTemplateArgument;
15250   switch (TTK) {
15251   case TTK_Struct:
15252   case TTK_Interface:
15253   case TTK_Class:
15254     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15255   case TTK_Union:
15256     return NTK_NonUnion;
15257   case TTK_Enum:
15258     return NTK_NonEnum;
15259   }
15260   llvm_unreachable("invalid TTK");
15261 }
15262 
15263 /// Determine whether a tag with a given kind is acceptable
15264 /// as a redeclaration of the given tag declaration.
15265 ///
15266 /// \returns true if the new tag kind is acceptable, false otherwise.
15267 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15268                                         TagTypeKind NewTag, bool isDefinition,
15269                                         SourceLocation NewTagLoc,
15270                                         const IdentifierInfo *Name) {
15271   // C++ [dcl.type.elab]p3:
15272   //   The class-key or enum keyword present in the
15273   //   elaborated-type-specifier shall agree in kind with the
15274   //   declaration to which the name in the elaborated-type-specifier
15275   //   refers. This rule also applies to the form of
15276   //   elaborated-type-specifier that declares a class-name or
15277   //   friend class since it can be construed as referring to the
15278   //   definition of the class. Thus, in any
15279   //   elaborated-type-specifier, the enum keyword shall be used to
15280   //   refer to an enumeration (7.2), the union class-key shall be
15281   //   used to refer to a union (clause 9), and either the class or
15282   //   struct class-key shall be used to refer to a class (clause 9)
15283   //   declared using the class or struct class-key.
15284   TagTypeKind OldTag = Previous->getTagKind();
15285   if (OldTag != NewTag &&
15286       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15287     return false;
15288 
15289   // Tags are compatible, but we might still want to warn on mismatched tags.
15290   // Non-class tags can't be mismatched at this point.
15291   if (!isClassCompatTagKind(NewTag))
15292     return true;
15293 
15294   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15295   // by our warning analysis. We don't want to warn about mismatches with (eg)
15296   // declarations in system headers that are designed to be specialized, but if
15297   // a user asks us to warn, we should warn if their code contains mismatched
15298   // declarations.
15299   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15300     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15301                                       Loc);
15302   };
15303   if (IsIgnoredLoc(NewTagLoc))
15304     return true;
15305 
15306   auto IsIgnored = [&](const TagDecl *Tag) {
15307     return IsIgnoredLoc(Tag->getLocation());
15308   };
15309   while (IsIgnored(Previous)) {
15310     Previous = Previous->getPreviousDecl();
15311     if (!Previous)
15312       return true;
15313     OldTag = Previous->getTagKind();
15314   }
15315 
15316   bool isTemplate = false;
15317   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15318     isTemplate = Record->getDescribedClassTemplate();
15319 
15320   if (inTemplateInstantiation()) {
15321     if (OldTag != NewTag) {
15322       // In a template instantiation, do not offer fix-its for tag mismatches
15323       // since they usually mess up the template instead of fixing the problem.
15324       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15325         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15326         << getRedeclDiagFromTagKind(OldTag);
15327       // FIXME: Note previous location?
15328     }
15329     return true;
15330   }
15331 
15332   if (isDefinition) {
15333     // On definitions, check all previous tags and issue a fix-it for each
15334     // one that doesn't match the current tag.
15335     if (Previous->getDefinition()) {
15336       // Don't suggest fix-its for redefinitions.
15337       return true;
15338     }
15339 
15340     bool previousMismatch = false;
15341     for (const TagDecl *I : Previous->redecls()) {
15342       if (I->getTagKind() != NewTag) {
15343         // Ignore previous declarations for which the warning was disabled.
15344         if (IsIgnored(I))
15345           continue;
15346 
15347         if (!previousMismatch) {
15348           previousMismatch = true;
15349           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15350             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15351             << getRedeclDiagFromTagKind(I->getTagKind());
15352         }
15353         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15354           << getRedeclDiagFromTagKind(NewTag)
15355           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15356                TypeWithKeyword::getTagTypeKindName(NewTag));
15357       }
15358     }
15359     return true;
15360   }
15361 
15362   // Identify the prevailing tag kind: this is the kind of the definition (if
15363   // there is a non-ignored definition), or otherwise the kind of the prior
15364   // (non-ignored) declaration.
15365   const TagDecl *PrevDef = Previous->getDefinition();
15366   if (PrevDef && IsIgnored(PrevDef))
15367     PrevDef = nullptr;
15368   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15369   if (Redecl->getTagKind() != NewTag) {
15370     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15371       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15372       << getRedeclDiagFromTagKind(OldTag);
15373     Diag(Redecl->getLocation(), diag::note_previous_use);
15374 
15375     // If there is a previous definition, suggest a fix-it.
15376     if (PrevDef) {
15377       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15378         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15379         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15380              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15381     }
15382   }
15383 
15384   return true;
15385 }
15386 
15387 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15388 /// from an outer enclosing namespace or file scope inside a friend declaration.
15389 /// This should provide the commented out code in the following snippet:
15390 ///   namespace N {
15391 ///     struct X;
15392 ///     namespace M {
15393 ///       struct Y { friend struct /*N::*/ X; };
15394 ///     }
15395 ///   }
15396 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15397                                          SourceLocation NameLoc) {
15398   // While the decl is in a namespace, do repeated lookup of that name and see
15399   // if we get the same namespace back.  If we do not, continue until
15400   // translation unit scope, at which point we have a fully qualified NNS.
15401   SmallVector<IdentifierInfo *, 4> Namespaces;
15402   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15403   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15404     // This tag should be declared in a namespace, which can only be enclosed by
15405     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15406     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15407     if (!Namespace || Namespace->isAnonymousNamespace())
15408       return FixItHint();
15409     IdentifierInfo *II = Namespace->getIdentifier();
15410     Namespaces.push_back(II);
15411     NamedDecl *Lookup = SemaRef.LookupSingleName(
15412         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15413     if (Lookup == Namespace)
15414       break;
15415   }
15416 
15417   // Once we have all the namespaces, reverse them to go outermost first, and
15418   // build an NNS.
15419   SmallString<64> Insertion;
15420   llvm::raw_svector_ostream OS(Insertion);
15421   if (DC->isTranslationUnit())
15422     OS << "::";
15423   std::reverse(Namespaces.begin(), Namespaces.end());
15424   for (auto *II : Namespaces)
15425     OS << II->getName() << "::";
15426   return FixItHint::CreateInsertion(NameLoc, Insertion);
15427 }
15428 
15429 /// Determine whether a tag originally declared in context \p OldDC can
15430 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15431 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15432 /// using-declaration).
15433 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15434                                          DeclContext *NewDC) {
15435   OldDC = OldDC->getRedeclContext();
15436   NewDC = NewDC->getRedeclContext();
15437 
15438   if (OldDC->Equals(NewDC))
15439     return true;
15440 
15441   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15442   // encloses the other).
15443   if (S.getLangOpts().MSVCCompat &&
15444       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15445     return true;
15446 
15447   return false;
15448 }
15449 
15450 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15451 /// former case, Name will be non-null.  In the later case, Name will be null.
15452 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15453 /// reference/declaration/definition of a tag.
15454 ///
15455 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15456 /// trailing-type-specifier) other than one in an alias-declaration.
15457 ///
15458 /// \param SkipBody If non-null, will be set to indicate if the caller should
15459 /// skip the definition of this tag and treat it as if it were a declaration.
15460 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15461                      SourceLocation KWLoc, CXXScopeSpec &SS,
15462                      IdentifierInfo *Name, SourceLocation NameLoc,
15463                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15464                      SourceLocation ModulePrivateLoc,
15465                      MultiTemplateParamsArg TemplateParameterLists,
15466                      bool &OwnedDecl, bool &IsDependent,
15467                      SourceLocation ScopedEnumKWLoc,
15468                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15469                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15470                      SkipBodyInfo *SkipBody) {
15471   // If this is not a definition, it must have a name.
15472   IdentifierInfo *OrigName = Name;
15473   assert((Name != nullptr || TUK == TUK_Definition) &&
15474          "Nameless record must be a definition!");
15475   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15476 
15477   OwnedDecl = false;
15478   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15479   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15480 
15481   // FIXME: Check member specializations more carefully.
15482   bool isMemberSpecialization = false;
15483   bool Invalid = false;
15484 
15485   // We only need to do this matching if we have template parameters
15486   // or a scope specifier, which also conveniently avoids this work
15487   // for non-C++ cases.
15488   if (TemplateParameterLists.size() > 0 ||
15489       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15490     if (TemplateParameterList *TemplateParams =
15491             MatchTemplateParametersToScopeSpecifier(
15492                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15493                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15494       if (Kind == TTK_Enum) {
15495         Diag(KWLoc, diag::err_enum_template);
15496         return nullptr;
15497       }
15498 
15499       if (TemplateParams->size() > 0) {
15500         // This is a declaration or definition of a class template (which may
15501         // be a member of another template).
15502 
15503         if (Invalid)
15504           return nullptr;
15505 
15506         OwnedDecl = false;
15507         DeclResult Result = CheckClassTemplate(
15508             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15509             AS, ModulePrivateLoc,
15510             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15511             TemplateParameterLists.data(), SkipBody);
15512         return Result.get();
15513       } else {
15514         // The "template<>" header is extraneous.
15515         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15516           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15517         isMemberSpecialization = true;
15518       }
15519     }
15520 
15521     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15522         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15523       return nullptr;
15524   }
15525 
15526   // Figure out the underlying type if this a enum declaration. We need to do
15527   // this early, because it's needed to detect if this is an incompatible
15528   // redeclaration.
15529   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15530   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15531 
15532   if (Kind == TTK_Enum) {
15533     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15534       // No underlying type explicitly specified, or we failed to parse the
15535       // type, default to int.
15536       EnumUnderlying = Context.IntTy.getTypePtr();
15537     } else if (UnderlyingType.get()) {
15538       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15539       // integral type; any cv-qualification is ignored.
15540       TypeSourceInfo *TI = nullptr;
15541       GetTypeFromParser(UnderlyingType.get(), &TI);
15542       EnumUnderlying = TI;
15543 
15544       if (CheckEnumUnderlyingType(TI))
15545         // Recover by falling back to int.
15546         EnumUnderlying = Context.IntTy.getTypePtr();
15547 
15548       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15549                                           UPPC_FixedUnderlyingType))
15550         EnumUnderlying = Context.IntTy.getTypePtr();
15551 
15552     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15553       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15554       // of 'int'. However, if this is an unfixed forward declaration, don't set
15555       // the underlying type unless the user enables -fms-compatibility. This
15556       // makes unfixed forward declared enums incomplete and is more conforming.
15557       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15558         EnumUnderlying = Context.IntTy.getTypePtr();
15559     }
15560   }
15561 
15562   DeclContext *SearchDC = CurContext;
15563   DeclContext *DC = CurContext;
15564   bool isStdBadAlloc = false;
15565   bool isStdAlignValT = false;
15566 
15567   RedeclarationKind Redecl = forRedeclarationInCurContext();
15568   if (TUK == TUK_Friend || TUK == TUK_Reference)
15569     Redecl = NotForRedeclaration;
15570 
15571   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15572   /// implemented asks for structural equivalence checking, the returned decl
15573   /// here is passed back to the parser, allowing the tag body to be parsed.
15574   auto createTagFromNewDecl = [&]() -> TagDecl * {
15575     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15576     // If there is an identifier, use the location of the identifier as the
15577     // location of the decl, otherwise use the location of the struct/union
15578     // keyword.
15579     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15580     TagDecl *New = nullptr;
15581 
15582     if (Kind == TTK_Enum) {
15583       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15584                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15585       // If this is an undefined enum, bail.
15586       if (TUK != TUK_Definition && !Invalid)
15587         return nullptr;
15588       if (EnumUnderlying) {
15589         EnumDecl *ED = cast<EnumDecl>(New);
15590         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15591           ED->setIntegerTypeSourceInfo(TI);
15592         else
15593           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15594         ED->setPromotionType(ED->getIntegerType());
15595       }
15596     } else { // struct/union
15597       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15598                                nullptr);
15599     }
15600 
15601     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15602       // Add alignment attributes if necessary; these attributes are checked
15603       // when the ASTContext lays out the structure.
15604       //
15605       // It is important for implementing the correct semantics that this
15606       // happen here (in ActOnTag). The #pragma pack stack is
15607       // maintained as a result of parser callbacks which can occur at
15608       // many points during the parsing of a struct declaration (because
15609       // the #pragma tokens are effectively skipped over during the
15610       // parsing of the struct).
15611       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15612         AddAlignmentAttributesForRecord(RD);
15613         AddMsStructLayoutForRecord(RD);
15614       }
15615     }
15616     New->setLexicalDeclContext(CurContext);
15617     return New;
15618   };
15619 
15620   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15621   if (Name && SS.isNotEmpty()) {
15622     // We have a nested-name tag ('struct foo::bar').
15623 
15624     // Check for invalid 'foo::'.
15625     if (SS.isInvalid()) {
15626       Name = nullptr;
15627       goto CreateNewDecl;
15628     }
15629 
15630     // If this is a friend or a reference to a class in a dependent
15631     // context, don't try to make a decl for it.
15632     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15633       DC = computeDeclContext(SS, false);
15634       if (!DC) {
15635         IsDependent = true;
15636         return nullptr;
15637       }
15638     } else {
15639       DC = computeDeclContext(SS, true);
15640       if (!DC) {
15641         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15642           << SS.getRange();
15643         return nullptr;
15644       }
15645     }
15646 
15647     if (RequireCompleteDeclContext(SS, DC))
15648       return nullptr;
15649 
15650     SearchDC = DC;
15651     // Look-up name inside 'foo::'.
15652     LookupQualifiedName(Previous, DC);
15653 
15654     if (Previous.isAmbiguous())
15655       return nullptr;
15656 
15657     if (Previous.empty()) {
15658       // Name lookup did not find anything. However, if the
15659       // nested-name-specifier refers to the current instantiation,
15660       // and that current instantiation has any dependent base
15661       // classes, we might find something at instantiation time: treat
15662       // this as a dependent elaborated-type-specifier.
15663       // But this only makes any sense for reference-like lookups.
15664       if (Previous.wasNotFoundInCurrentInstantiation() &&
15665           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15666         IsDependent = true;
15667         return nullptr;
15668       }
15669 
15670       // A tag 'foo::bar' must already exist.
15671       Diag(NameLoc, diag::err_not_tag_in_scope)
15672         << Kind << Name << DC << SS.getRange();
15673       Name = nullptr;
15674       Invalid = true;
15675       goto CreateNewDecl;
15676     }
15677   } else if (Name) {
15678     // C++14 [class.mem]p14:
15679     //   If T is the name of a class, then each of the following shall have a
15680     //   name different from T:
15681     //    -- every member of class T that is itself a type
15682     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15683         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15684       return nullptr;
15685 
15686     // If this is a named struct, check to see if there was a previous forward
15687     // declaration or definition.
15688     // FIXME: We're looking into outer scopes here, even when we
15689     // shouldn't be. Doing so can result in ambiguities that we
15690     // shouldn't be diagnosing.
15691     LookupName(Previous, S);
15692 
15693     // When declaring or defining a tag, ignore ambiguities introduced
15694     // by types using'ed into this scope.
15695     if (Previous.isAmbiguous() &&
15696         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15697       LookupResult::Filter F = Previous.makeFilter();
15698       while (F.hasNext()) {
15699         NamedDecl *ND = F.next();
15700         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15701                 SearchDC->getRedeclContext()))
15702           F.erase();
15703       }
15704       F.done();
15705     }
15706 
15707     // C++11 [namespace.memdef]p3:
15708     //   If the name in a friend declaration is neither qualified nor
15709     //   a template-id and the declaration is a function or an
15710     //   elaborated-type-specifier, the lookup to determine whether
15711     //   the entity has been previously declared shall not consider
15712     //   any scopes outside the innermost enclosing namespace.
15713     //
15714     // MSVC doesn't implement the above rule for types, so a friend tag
15715     // declaration may be a redeclaration of a type declared in an enclosing
15716     // scope.  They do implement this rule for friend functions.
15717     //
15718     // Does it matter that this should be by scope instead of by
15719     // semantic context?
15720     if (!Previous.empty() && TUK == TUK_Friend) {
15721       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15722       LookupResult::Filter F = Previous.makeFilter();
15723       bool FriendSawTagOutsideEnclosingNamespace = false;
15724       while (F.hasNext()) {
15725         NamedDecl *ND = F.next();
15726         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15727         if (DC->isFileContext() &&
15728             !EnclosingNS->Encloses(ND->getDeclContext())) {
15729           if (getLangOpts().MSVCCompat)
15730             FriendSawTagOutsideEnclosingNamespace = true;
15731           else
15732             F.erase();
15733         }
15734       }
15735       F.done();
15736 
15737       // Diagnose this MSVC extension in the easy case where lookup would have
15738       // unambiguously found something outside the enclosing namespace.
15739       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15740         NamedDecl *ND = Previous.getFoundDecl();
15741         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15742             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15743       }
15744     }
15745 
15746     // Note:  there used to be some attempt at recovery here.
15747     if (Previous.isAmbiguous())
15748       return nullptr;
15749 
15750     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15751       // FIXME: This makes sure that we ignore the contexts associated
15752       // with C structs, unions, and enums when looking for a matching
15753       // tag declaration or definition. See the similar lookup tweak
15754       // in Sema::LookupName; is there a better way to deal with this?
15755       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15756         SearchDC = SearchDC->getParent();
15757     }
15758   }
15759 
15760   if (Previous.isSingleResult() &&
15761       Previous.getFoundDecl()->isTemplateParameter()) {
15762     // Maybe we will complain about the shadowed template parameter.
15763     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15764     // Just pretend that we didn't see the previous declaration.
15765     Previous.clear();
15766   }
15767 
15768   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15769       DC->Equals(getStdNamespace())) {
15770     if (Name->isStr("bad_alloc")) {
15771       // This is a declaration of or a reference to "std::bad_alloc".
15772       isStdBadAlloc = true;
15773 
15774       // If std::bad_alloc has been implicitly declared (but made invisible to
15775       // name lookup), fill in this implicit declaration as the previous
15776       // declaration, so that the declarations get chained appropriately.
15777       if (Previous.empty() && StdBadAlloc)
15778         Previous.addDecl(getStdBadAlloc());
15779     } else if (Name->isStr("align_val_t")) {
15780       isStdAlignValT = true;
15781       if (Previous.empty() && StdAlignValT)
15782         Previous.addDecl(getStdAlignValT());
15783     }
15784   }
15785 
15786   // If we didn't find a previous declaration, and this is a reference
15787   // (or friend reference), move to the correct scope.  In C++, we
15788   // also need to do a redeclaration lookup there, just in case
15789   // there's a shadow friend decl.
15790   if (Name && Previous.empty() &&
15791       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15792     if (Invalid) goto CreateNewDecl;
15793     assert(SS.isEmpty());
15794 
15795     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15796       // C++ [basic.scope.pdecl]p5:
15797       //   -- for an elaborated-type-specifier of the form
15798       //
15799       //          class-key identifier
15800       //
15801       //      if the elaborated-type-specifier is used in the
15802       //      decl-specifier-seq or parameter-declaration-clause of a
15803       //      function defined in namespace scope, the identifier is
15804       //      declared as a class-name in the namespace that contains
15805       //      the declaration; otherwise, except as a friend
15806       //      declaration, the identifier is declared in the smallest
15807       //      non-class, non-function-prototype scope that contains the
15808       //      declaration.
15809       //
15810       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15811       // C structs and unions.
15812       //
15813       // It is an error in C++ to declare (rather than define) an enum
15814       // type, including via an elaborated type specifier.  We'll
15815       // diagnose that later; for now, declare the enum in the same
15816       // scope as we would have picked for any other tag type.
15817       //
15818       // GNU C also supports this behavior as part of its incomplete
15819       // enum types extension, while GNU C++ does not.
15820       //
15821       // Find the context where we'll be declaring the tag.
15822       // FIXME: We would like to maintain the current DeclContext as the
15823       // lexical context,
15824       SearchDC = getTagInjectionContext(SearchDC);
15825 
15826       // Find the scope where we'll be declaring the tag.
15827       S = getTagInjectionScope(S, getLangOpts());
15828     } else {
15829       assert(TUK == TUK_Friend);
15830       // C++ [namespace.memdef]p3:
15831       //   If a friend declaration in a non-local class first declares a
15832       //   class or function, the friend class or function is a member of
15833       //   the innermost enclosing namespace.
15834       SearchDC = SearchDC->getEnclosingNamespaceContext();
15835     }
15836 
15837     // In C++, we need to do a redeclaration lookup to properly
15838     // diagnose some problems.
15839     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15840     // hidden declaration so that we don't get ambiguity errors when using a
15841     // type declared by an elaborated-type-specifier.  In C that is not correct
15842     // and we should instead merge compatible types found by lookup.
15843     if (getLangOpts().CPlusPlus) {
15844       // FIXME: This can perform qualified lookups into function contexts,
15845       // which are meaningless.
15846       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15847       LookupQualifiedName(Previous, SearchDC);
15848     } else {
15849       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15850       LookupName(Previous, S);
15851     }
15852   }
15853 
15854   // If we have a known previous declaration to use, then use it.
15855   if (Previous.empty() && SkipBody && SkipBody->Previous)
15856     Previous.addDecl(SkipBody->Previous);
15857 
15858   if (!Previous.empty()) {
15859     NamedDecl *PrevDecl = Previous.getFoundDecl();
15860     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15861 
15862     // It's okay to have a tag decl in the same scope as a typedef
15863     // which hides a tag decl in the same scope.  Finding this
15864     // insanity with a redeclaration lookup can only actually happen
15865     // in C++.
15866     //
15867     // This is also okay for elaborated-type-specifiers, which is
15868     // technically forbidden by the current standard but which is
15869     // okay according to the likely resolution of an open issue;
15870     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15871     if (getLangOpts().CPlusPlus) {
15872       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15873         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15874           TagDecl *Tag = TT->getDecl();
15875           if (Tag->getDeclName() == Name &&
15876               Tag->getDeclContext()->getRedeclContext()
15877                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15878             PrevDecl = Tag;
15879             Previous.clear();
15880             Previous.addDecl(Tag);
15881             Previous.resolveKind();
15882           }
15883         }
15884       }
15885     }
15886 
15887     // If this is a redeclaration of a using shadow declaration, it must
15888     // declare a tag in the same context. In MSVC mode, we allow a
15889     // redefinition if either context is within the other.
15890     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15891       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15892       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15893           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15894           !(OldTag && isAcceptableTagRedeclContext(
15895                           *this, OldTag->getDeclContext(), SearchDC))) {
15896         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15897         Diag(Shadow->getTargetDecl()->getLocation(),
15898              diag::note_using_decl_target);
15899         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15900             << 0;
15901         // Recover by ignoring the old declaration.
15902         Previous.clear();
15903         goto CreateNewDecl;
15904       }
15905     }
15906 
15907     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15908       // If this is a use of a previous tag, or if the tag is already declared
15909       // in the same scope (so that the definition/declaration completes or
15910       // rementions the tag), reuse the decl.
15911       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15912           isDeclInScope(DirectPrevDecl, SearchDC, S,
15913                         SS.isNotEmpty() || isMemberSpecialization)) {
15914         // Make sure that this wasn't declared as an enum and now used as a
15915         // struct or something similar.
15916         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15917                                           TUK == TUK_Definition, KWLoc,
15918                                           Name)) {
15919           bool SafeToContinue
15920             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15921                Kind != TTK_Enum);
15922           if (SafeToContinue)
15923             Diag(KWLoc, diag::err_use_with_wrong_tag)
15924               << Name
15925               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15926                                               PrevTagDecl->getKindName());
15927           else
15928             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15929           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15930 
15931           if (SafeToContinue)
15932             Kind = PrevTagDecl->getTagKind();
15933           else {
15934             // Recover by making this an anonymous redefinition.
15935             Name = nullptr;
15936             Previous.clear();
15937             Invalid = true;
15938           }
15939         }
15940 
15941         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15942           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15943           if (TUK == TUK_Reference || TUK == TUK_Friend)
15944             return PrevTagDecl;
15945 
15946           QualType EnumUnderlyingTy;
15947           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15948             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15949           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15950             EnumUnderlyingTy = QualType(T, 0);
15951 
15952           // All conflicts with previous declarations are recovered by
15953           // returning the previous declaration, unless this is a definition,
15954           // in which case we want the caller to bail out.
15955           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15956                                      ScopedEnum, EnumUnderlyingTy,
15957                                      IsFixed, PrevEnum))
15958             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15959         }
15960 
15961         // C++11 [class.mem]p1:
15962         //   A member shall not be declared twice in the member-specification,
15963         //   except that a nested class or member class template can be declared
15964         //   and then later defined.
15965         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15966             S->isDeclScope(PrevDecl)) {
15967           Diag(NameLoc, diag::ext_member_redeclared);
15968           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15969         }
15970 
15971         if (!Invalid) {
15972           // If this is a use, just return the declaration we found, unless
15973           // we have attributes.
15974           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15975             if (!Attrs.empty()) {
15976               // FIXME: Diagnose these attributes. For now, we create a new
15977               // declaration to hold them.
15978             } else if (TUK == TUK_Reference &&
15979                        (PrevTagDecl->getFriendObjectKind() ==
15980                             Decl::FOK_Undeclared ||
15981                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15982                        SS.isEmpty()) {
15983               // This declaration is a reference to an existing entity, but
15984               // has different visibility from that entity: it either makes
15985               // a friend visible or it makes a type visible in a new module.
15986               // In either case, create a new declaration. We only do this if
15987               // the declaration would have meant the same thing if no prior
15988               // declaration were found, that is, if it was found in the same
15989               // scope where we would have injected a declaration.
15990               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15991                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15992                 return PrevTagDecl;
15993               // This is in the injected scope, create a new declaration in
15994               // that scope.
15995               S = getTagInjectionScope(S, getLangOpts());
15996             } else {
15997               return PrevTagDecl;
15998             }
15999           }
16000 
16001           // Diagnose attempts to redefine a tag.
16002           if (TUK == TUK_Definition) {
16003             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16004               // If we're defining a specialization and the previous definition
16005               // is from an implicit instantiation, don't emit an error
16006               // here; we'll catch this in the general case below.
16007               bool IsExplicitSpecializationAfterInstantiation = false;
16008               if (isMemberSpecialization) {
16009                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16010                   IsExplicitSpecializationAfterInstantiation =
16011                     RD->getTemplateSpecializationKind() !=
16012                     TSK_ExplicitSpecialization;
16013                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16014                   IsExplicitSpecializationAfterInstantiation =
16015                     ED->getTemplateSpecializationKind() !=
16016                     TSK_ExplicitSpecialization;
16017               }
16018 
16019               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16020               // not keep more that one definition around (merge them). However,
16021               // ensure the decl passes the structural compatibility check in
16022               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16023               NamedDecl *Hidden = nullptr;
16024               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16025                 // There is a definition of this tag, but it is not visible. We
16026                 // explicitly make use of C++'s one definition rule here, and
16027                 // assume that this definition is identical to the hidden one
16028                 // we already have. Make the existing definition visible and
16029                 // use it in place of this one.
16030                 if (!getLangOpts().CPlusPlus) {
16031                   // Postpone making the old definition visible until after we
16032                   // complete parsing the new one and do the structural
16033                   // comparison.
16034                   SkipBody->CheckSameAsPrevious = true;
16035                   SkipBody->New = createTagFromNewDecl();
16036                   SkipBody->Previous = Def;
16037                   return Def;
16038                 } else {
16039                   SkipBody->ShouldSkip = true;
16040                   SkipBody->Previous = Def;
16041                   makeMergedDefinitionVisible(Hidden);
16042                   // Carry on and handle it like a normal definition. We'll
16043                   // skip starting the definitiion later.
16044                 }
16045               } else if (!IsExplicitSpecializationAfterInstantiation) {
16046                 // A redeclaration in function prototype scope in C isn't
16047                 // visible elsewhere, so merely issue a warning.
16048                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16049                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16050                 else
16051                   Diag(NameLoc, diag::err_redefinition) << Name;
16052                 notePreviousDefinition(Def,
16053                                        NameLoc.isValid() ? NameLoc : KWLoc);
16054                 // If this is a redefinition, recover by making this
16055                 // struct be anonymous, which will make any later
16056                 // references get the previous definition.
16057                 Name = nullptr;
16058                 Previous.clear();
16059                 Invalid = true;
16060               }
16061             } else {
16062               // If the type is currently being defined, complain
16063               // about a nested redefinition.
16064               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16065               if (TD->isBeingDefined()) {
16066                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16067                 Diag(PrevTagDecl->getLocation(),
16068                      diag::note_previous_definition);
16069                 Name = nullptr;
16070                 Previous.clear();
16071                 Invalid = true;
16072               }
16073             }
16074 
16075             // Okay, this is definition of a previously declared or referenced
16076             // tag. We're going to create a new Decl for it.
16077           }
16078 
16079           // Okay, we're going to make a redeclaration.  If this is some kind
16080           // of reference, make sure we build the redeclaration in the same DC
16081           // as the original, and ignore the current access specifier.
16082           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16083             SearchDC = PrevTagDecl->getDeclContext();
16084             AS = AS_none;
16085           }
16086         }
16087         // If we get here we have (another) forward declaration or we
16088         // have a definition.  Just create a new decl.
16089 
16090       } else {
16091         // If we get here, this is a definition of a new tag type in a nested
16092         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16093         // new decl/type.  We set PrevDecl to NULL so that the entities
16094         // have distinct types.
16095         Previous.clear();
16096       }
16097       // If we get here, we're going to create a new Decl. If PrevDecl
16098       // is non-NULL, it's a definition of the tag declared by
16099       // PrevDecl. If it's NULL, we have a new definition.
16100 
16101     // Otherwise, PrevDecl is not a tag, but was found with tag
16102     // lookup.  This is only actually possible in C++, where a few
16103     // things like templates still live in the tag namespace.
16104     } else {
16105       // Use a better diagnostic if an elaborated-type-specifier
16106       // found the wrong kind of type on the first
16107       // (non-redeclaration) lookup.
16108       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16109           !Previous.isForRedeclaration()) {
16110         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16111         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16112                                                        << Kind;
16113         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16114         Invalid = true;
16115 
16116       // Otherwise, only diagnose if the declaration is in scope.
16117       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16118                                 SS.isNotEmpty() || isMemberSpecialization)) {
16119         // do nothing
16120 
16121       // Diagnose implicit declarations introduced by elaborated types.
16122       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16123         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16124         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16125         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16126         Invalid = true;
16127 
16128       // Otherwise it's a declaration.  Call out a particularly common
16129       // case here.
16130       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16131         unsigned Kind = 0;
16132         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16133         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16134           << Name << Kind << TND->getUnderlyingType();
16135         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16136         Invalid = true;
16137 
16138       // Otherwise, diagnose.
16139       } else {
16140         // The tag name clashes with something else in the target scope,
16141         // issue an error and recover by making this tag be anonymous.
16142         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16143         notePreviousDefinition(PrevDecl, NameLoc);
16144         Name = nullptr;
16145         Invalid = true;
16146       }
16147 
16148       // The existing declaration isn't relevant to us; we're in a
16149       // new scope, so clear out the previous declaration.
16150       Previous.clear();
16151     }
16152   }
16153 
16154 CreateNewDecl:
16155 
16156   TagDecl *PrevDecl = nullptr;
16157   if (Previous.isSingleResult())
16158     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16159 
16160   // If there is an identifier, use the location of the identifier as the
16161   // location of the decl, otherwise use the location of the struct/union
16162   // keyword.
16163   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16164 
16165   // Otherwise, create a new declaration. If there is a previous
16166   // declaration of the same entity, the two will be linked via
16167   // PrevDecl.
16168   TagDecl *New;
16169 
16170   if (Kind == TTK_Enum) {
16171     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16172     // enum X { A, B, C } D;    D should chain to X.
16173     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16174                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16175                            ScopedEnumUsesClassTag, IsFixed);
16176 
16177     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16178       StdAlignValT = cast<EnumDecl>(New);
16179 
16180     // If this is an undefined enum, warn.
16181     if (TUK != TUK_Definition && !Invalid) {
16182       TagDecl *Def;
16183       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16184         // C++0x: 7.2p2: opaque-enum-declaration.
16185         // Conflicts are diagnosed above. Do nothing.
16186       }
16187       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16188         Diag(Loc, diag::ext_forward_ref_enum_def)
16189           << New;
16190         Diag(Def->getLocation(), diag::note_previous_definition);
16191       } else {
16192         unsigned DiagID = diag::ext_forward_ref_enum;
16193         if (getLangOpts().MSVCCompat)
16194           DiagID = diag::ext_ms_forward_ref_enum;
16195         else if (getLangOpts().CPlusPlus)
16196           DiagID = diag::err_forward_ref_enum;
16197         Diag(Loc, DiagID);
16198       }
16199     }
16200 
16201     if (EnumUnderlying) {
16202       EnumDecl *ED = cast<EnumDecl>(New);
16203       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16204         ED->setIntegerTypeSourceInfo(TI);
16205       else
16206         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16207       ED->setPromotionType(ED->getIntegerType());
16208       assert(ED->isComplete() && "enum with type should be complete");
16209     }
16210   } else {
16211     // struct/union/class
16212 
16213     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16214     // struct X { int A; } D;    D should chain to X.
16215     if (getLangOpts().CPlusPlus) {
16216       // FIXME: Look for a way to use RecordDecl for simple structs.
16217       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16218                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16219 
16220       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16221         StdBadAlloc = cast<CXXRecordDecl>(New);
16222     } else
16223       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16224                                cast_or_null<RecordDecl>(PrevDecl));
16225   }
16226 
16227   // C++11 [dcl.type]p3:
16228   //   A type-specifier-seq shall not define a class or enumeration [...].
16229   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16230       TUK == TUK_Definition) {
16231     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16232       << Context.getTagDeclType(New);
16233     Invalid = true;
16234   }
16235 
16236   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16237       DC->getDeclKind() == Decl::Enum) {
16238     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16239       << Context.getTagDeclType(New);
16240     Invalid = true;
16241   }
16242 
16243   // Maybe add qualifier info.
16244   if (SS.isNotEmpty()) {
16245     if (SS.isSet()) {
16246       // If this is either a declaration or a definition, check the
16247       // nested-name-specifier against the current context.
16248       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16249           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16250                                        isMemberSpecialization))
16251         Invalid = true;
16252 
16253       New->setQualifierInfo(SS.getWithLocInContext(Context));
16254       if (TemplateParameterLists.size() > 0) {
16255         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16256       }
16257     }
16258     else
16259       Invalid = true;
16260   }
16261 
16262   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16263     // Add alignment attributes if necessary; these attributes are checked when
16264     // the ASTContext lays out the structure.
16265     //
16266     // It is important for implementing the correct semantics that this
16267     // happen here (in ActOnTag). The #pragma pack stack is
16268     // maintained as a result of parser callbacks which can occur at
16269     // many points during the parsing of a struct declaration (because
16270     // the #pragma tokens are effectively skipped over during the
16271     // parsing of the struct).
16272     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16273       AddAlignmentAttributesForRecord(RD);
16274       AddMsStructLayoutForRecord(RD);
16275     }
16276   }
16277 
16278   if (ModulePrivateLoc.isValid()) {
16279     if (isMemberSpecialization)
16280       Diag(New->getLocation(), diag::err_module_private_specialization)
16281         << 2
16282         << FixItHint::CreateRemoval(ModulePrivateLoc);
16283     // __module_private__ does not apply to local classes. However, we only
16284     // diagnose this as an error when the declaration specifiers are
16285     // freestanding. Here, we just ignore the __module_private__.
16286     else if (!SearchDC->isFunctionOrMethod())
16287       New->setModulePrivate();
16288   }
16289 
16290   // If this is a specialization of a member class (of a class template),
16291   // check the specialization.
16292   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16293     Invalid = true;
16294 
16295   // If we're declaring or defining a tag in function prototype scope in C,
16296   // note that this type can only be used within the function and add it to
16297   // the list of decls to inject into the function definition scope.
16298   if ((Name || Kind == TTK_Enum) &&
16299       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16300     if (getLangOpts().CPlusPlus) {
16301       // C++ [dcl.fct]p6:
16302       //   Types shall not be defined in return or parameter types.
16303       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16304         Diag(Loc, diag::err_type_defined_in_param_type)
16305             << Name;
16306         Invalid = true;
16307       }
16308     } else if (!PrevDecl) {
16309       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16310     }
16311   }
16312 
16313   if (Invalid)
16314     New->setInvalidDecl();
16315 
16316   // Set the lexical context. If the tag has a C++ scope specifier, the
16317   // lexical context will be different from the semantic context.
16318   New->setLexicalDeclContext(CurContext);
16319 
16320   // Mark this as a friend decl if applicable.
16321   // In Microsoft mode, a friend declaration also acts as a forward
16322   // declaration so we always pass true to setObjectOfFriendDecl to make
16323   // the tag name visible.
16324   if (TUK == TUK_Friend)
16325     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16326 
16327   // Set the access specifier.
16328   if (!Invalid && SearchDC->isRecord())
16329     SetMemberAccessSpecifier(New, PrevDecl, AS);
16330 
16331   if (PrevDecl)
16332     CheckRedeclarationModuleOwnership(New, PrevDecl);
16333 
16334   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16335     New->startDefinition();
16336 
16337   ProcessDeclAttributeList(S, New, Attrs);
16338   AddPragmaAttributes(S, New);
16339 
16340   // If this has an identifier, add it to the scope stack.
16341   if (TUK == TUK_Friend) {
16342     // We might be replacing an existing declaration in the lookup tables;
16343     // if so, borrow its access specifier.
16344     if (PrevDecl)
16345       New->setAccess(PrevDecl->getAccess());
16346 
16347     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16348     DC->makeDeclVisibleInContext(New);
16349     if (Name) // can be null along some error paths
16350       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16351         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16352   } else if (Name) {
16353     S = getNonFieldDeclScope(S);
16354     PushOnScopeChains(New, S, true);
16355   } else {
16356     CurContext->addDecl(New);
16357   }
16358 
16359   // If this is the C FILE type, notify the AST context.
16360   if (IdentifierInfo *II = New->getIdentifier())
16361     if (!New->isInvalidDecl() &&
16362         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16363         II->isStr("FILE"))
16364       Context.setFILEDecl(New);
16365 
16366   if (PrevDecl)
16367     mergeDeclAttributes(New, PrevDecl);
16368 
16369   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16370     inferGslOwnerPointerAttribute(CXXRD);
16371 
16372   // If there's a #pragma GCC visibility in scope, set the visibility of this
16373   // record.
16374   AddPushedVisibilityAttribute(New);
16375 
16376   if (isMemberSpecialization && !New->isInvalidDecl())
16377     CompleteMemberSpecialization(New, Previous);
16378 
16379   OwnedDecl = true;
16380   // In C++, don't return an invalid declaration. We can't recover well from
16381   // the cases where we make the type anonymous.
16382   if (Invalid && getLangOpts().CPlusPlus) {
16383     if (New->isBeingDefined())
16384       if (auto RD = dyn_cast<RecordDecl>(New))
16385         RD->completeDefinition();
16386     return nullptr;
16387   } else if (SkipBody && SkipBody->ShouldSkip) {
16388     return SkipBody->Previous;
16389   } else {
16390     return New;
16391   }
16392 }
16393 
16394 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16395   AdjustDeclIfTemplate(TagD);
16396   TagDecl *Tag = cast<TagDecl>(TagD);
16397 
16398   // Enter the tag context.
16399   PushDeclContext(S, Tag);
16400 
16401   ActOnDocumentableDecl(TagD);
16402 
16403   // If there's a #pragma GCC visibility in scope, set the visibility of this
16404   // record.
16405   AddPushedVisibilityAttribute(Tag);
16406 }
16407 
16408 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16409                                     SkipBodyInfo &SkipBody) {
16410   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16411     return false;
16412 
16413   // Make the previous decl visible.
16414   makeMergedDefinitionVisible(SkipBody.Previous);
16415   return true;
16416 }
16417 
16418 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16419   assert(isa<ObjCContainerDecl>(IDecl) &&
16420          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16421   DeclContext *OCD = cast<DeclContext>(IDecl);
16422   assert(OCD->getLexicalParent() == CurContext &&
16423       "The next DeclContext should be lexically contained in the current one.");
16424   CurContext = OCD;
16425   return IDecl;
16426 }
16427 
16428 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16429                                            SourceLocation FinalLoc,
16430                                            bool IsFinalSpelledSealed,
16431                                            SourceLocation LBraceLoc) {
16432   AdjustDeclIfTemplate(TagD);
16433   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16434 
16435   FieldCollector->StartClass();
16436 
16437   if (!Record->getIdentifier())
16438     return;
16439 
16440   if (FinalLoc.isValid())
16441     Record->addAttr(FinalAttr::Create(
16442         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16443         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16444 
16445   // C++ [class]p2:
16446   //   [...] The class-name is also inserted into the scope of the
16447   //   class itself; this is known as the injected-class-name. For
16448   //   purposes of access checking, the injected-class-name is treated
16449   //   as if it were a public member name.
16450   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16451       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16452       Record->getLocation(), Record->getIdentifier(),
16453       /*PrevDecl=*/nullptr,
16454       /*DelayTypeCreation=*/true);
16455   Context.getTypeDeclType(InjectedClassName, Record);
16456   InjectedClassName->setImplicit();
16457   InjectedClassName->setAccess(AS_public);
16458   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16459       InjectedClassName->setDescribedClassTemplate(Template);
16460   PushOnScopeChains(InjectedClassName, S);
16461   assert(InjectedClassName->isInjectedClassName() &&
16462          "Broken injected-class-name");
16463 }
16464 
16465 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16466                                     SourceRange BraceRange) {
16467   AdjustDeclIfTemplate(TagD);
16468   TagDecl *Tag = cast<TagDecl>(TagD);
16469   Tag->setBraceRange(BraceRange);
16470 
16471   // Make sure we "complete" the definition even it is invalid.
16472   if (Tag->isBeingDefined()) {
16473     assert(Tag->isInvalidDecl() && "We should already have completed it");
16474     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16475       RD->completeDefinition();
16476   }
16477 
16478   if (isa<CXXRecordDecl>(Tag)) {
16479     FieldCollector->FinishClass();
16480   }
16481 
16482   // Exit this scope of this tag's definition.
16483   PopDeclContext();
16484 
16485   if (getCurLexicalContext()->isObjCContainer() &&
16486       Tag->getDeclContext()->isFileContext())
16487     Tag->setTopLevelDeclInObjCContainer();
16488 
16489   // Notify the consumer that we've defined a tag.
16490   if (!Tag->isInvalidDecl())
16491     Consumer.HandleTagDeclDefinition(Tag);
16492 }
16493 
16494 void Sema::ActOnObjCContainerFinishDefinition() {
16495   // Exit this scope of this interface definition.
16496   PopDeclContext();
16497 }
16498 
16499 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16500   assert(DC == CurContext && "Mismatch of container contexts");
16501   OriginalLexicalContext = DC;
16502   ActOnObjCContainerFinishDefinition();
16503 }
16504 
16505 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16506   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16507   OriginalLexicalContext = nullptr;
16508 }
16509 
16510 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16511   AdjustDeclIfTemplate(TagD);
16512   TagDecl *Tag = cast<TagDecl>(TagD);
16513   Tag->setInvalidDecl();
16514 
16515   // Make sure we "complete" the definition even it is invalid.
16516   if (Tag->isBeingDefined()) {
16517     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16518       RD->completeDefinition();
16519   }
16520 
16521   // We're undoing ActOnTagStartDefinition here, not
16522   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16523   // the FieldCollector.
16524 
16525   PopDeclContext();
16526 }
16527 
16528 // Note that FieldName may be null for anonymous bitfields.
16529 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16530                                 IdentifierInfo *FieldName,
16531                                 QualType FieldTy, bool IsMsStruct,
16532                                 Expr *BitWidth, bool *ZeroWidth) {
16533   assert(BitWidth);
16534   if (BitWidth->containsErrors())
16535     return ExprError();
16536 
16537   // Default to true; that shouldn't confuse checks for emptiness
16538   if (ZeroWidth)
16539     *ZeroWidth = true;
16540 
16541   // C99 6.7.2.1p4 - verify the field type.
16542   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16543   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16544     // Handle incomplete and sizeless types with a specific error.
16545     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16546                                  diag::err_field_incomplete_or_sizeless))
16547       return ExprError();
16548     if (FieldName)
16549       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16550         << FieldName << FieldTy << BitWidth->getSourceRange();
16551     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16552       << FieldTy << BitWidth->getSourceRange();
16553   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16554                                              UPPC_BitFieldWidth))
16555     return ExprError();
16556 
16557   // If the bit-width is type- or value-dependent, don't try to check
16558   // it now.
16559   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16560     return BitWidth;
16561 
16562   llvm::APSInt Value;
16563   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16564   if (ICE.isInvalid())
16565     return ICE;
16566   BitWidth = ICE.get();
16567 
16568   if (Value != 0 && ZeroWidth)
16569     *ZeroWidth = false;
16570 
16571   // Zero-width bitfield is ok for anonymous field.
16572   if (Value == 0 && FieldName)
16573     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16574 
16575   if (Value.isSigned() && Value.isNegative()) {
16576     if (FieldName)
16577       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16578                << FieldName << Value.toString(10);
16579     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16580       << Value.toString(10);
16581   }
16582 
16583   // The size of the bit-field must not exceed our maximum permitted object
16584   // size.
16585   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16586     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16587            << !FieldName << FieldName << Value.toString(10);
16588   }
16589 
16590   if (!FieldTy->isDependentType()) {
16591     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16592     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16593     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16594 
16595     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16596     // ABI.
16597     bool CStdConstraintViolation =
16598         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16599     bool MSBitfieldViolation =
16600         Value.ugt(TypeStorageSize) &&
16601         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16602     if (CStdConstraintViolation || MSBitfieldViolation) {
16603       unsigned DiagWidth =
16604           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16605       if (FieldName)
16606         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16607                << FieldName << Value.toString(10)
16608                << !CStdConstraintViolation << DiagWidth;
16609 
16610       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16611              << Value.toString(10) << !CStdConstraintViolation
16612              << DiagWidth;
16613     }
16614 
16615     // Warn on types where the user might conceivably expect to get all
16616     // specified bits as value bits: that's all integral types other than
16617     // 'bool'.
16618     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16619       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16620           << FieldName << Value.toString(10)
16621           << (unsigned)TypeWidth;
16622     }
16623   }
16624 
16625   return BitWidth;
16626 }
16627 
16628 /// ActOnField - Each field of a C struct/union is passed into this in order
16629 /// to create a FieldDecl object for it.
16630 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16631                        Declarator &D, Expr *BitfieldWidth) {
16632   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16633                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16634                                /*InitStyle=*/ICIS_NoInit, AS_public);
16635   return Res;
16636 }
16637 
16638 /// HandleField - Analyze a field of a C struct or a C++ data member.
16639 ///
16640 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16641                              SourceLocation DeclStart,
16642                              Declarator &D, Expr *BitWidth,
16643                              InClassInitStyle InitStyle,
16644                              AccessSpecifier AS) {
16645   if (D.isDecompositionDeclarator()) {
16646     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16647     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16648       << Decomp.getSourceRange();
16649     return nullptr;
16650   }
16651 
16652   IdentifierInfo *II = D.getIdentifier();
16653   SourceLocation Loc = DeclStart;
16654   if (II) Loc = D.getIdentifierLoc();
16655 
16656   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16657   QualType T = TInfo->getType();
16658   if (getLangOpts().CPlusPlus) {
16659     CheckExtraCXXDefaultArguments(D);
16660 
16661     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16662                                         UPPC_DataMemberType)) {
16663       D.setInvalidType();
16664       T = Context.IntTy;
16665       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16666     }
16667   }
16668 
16669   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16670 
16671   if (D.getDeclSpec().isInlineSpecified())
16672     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16673         << getLangOpts().CPlusPlus17;
16674   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16675     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16676          diag::err_invalid_thread)
16677       << DeclSpec::getSpecifierName(TSCS);
16678 
16679   // Check to see if this name was declared as a member previously
16680   NamedDecl *PrevDecl = nullptr;
16681   LookupResult Previous(*this, II, Loc, LookupMemberName,
16682                         ForVisibleRedeclaration);
16683   LookupName(Previous, S);
16684   switch (Previous.getResultKind()) {
16685     case LookupResult::Found:
16686     case LookupResult::FoundUnresolvedValue:
16687       PrevDecl = Previous.getAsSingle<NamedDecl>();
16688       break;
16689 
16690     case LookupResult::FoundOverloaded:
16691       PrevDecl = Previous.getRepresentativeDecl();
16692       break;
16693 
16694     case LookupResult::NotFound:
16695     case LookupResult::NotFoundInCurrentInstantiation:
16696     case LookupResult::Ambiguous:
16697       break;
16698   }
16699   Previous.suppressDiagnostics();
16700 
16701   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16702     // Maybe we will complain about the shadowed template parameter.
16703     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16704     // Just pretend that we didn't see the previous declaration.
16705     PrevDecl = nullptr;
16706   }
16707 
16708   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16709     PrevDecl = nullptr;
16710 
16711   bool Mutable
16712     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16713   SourceLocation TSSL = D.getBeginLoc();
16714   FieldDecl *NewFD
16715     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16716                      TSSL, AS, PrevDecl, &D);
16717 
16718   if (NewFD->isInvalidDecl())
16719     Record->setInvalidDecl();
16720 
16721   if (D.getDeclSpec().isModulePrivateSpecified())
16722     NewFD->setModulePrivate();
16723 
16724   if (NewFD->isInvalidDecl() && PrevDecl) {
16725     // Don't introduce NewFD into scope; there's already something
16726     // with the same name in the same scope.
16727   } else if (II) {
16728     PushOnScopeChains(NewFD, S);
16729   } else
16730     Record->addDecl(NewFD);
16731 
16732   return NewFD;
16733 }
16734 
16735 /// Build a new FieldDecl and check its well-formedness.
16736 ///
16737 /// This routine builds a new FieldDecl given the fields name, type,
16738 /// record, etc. \p PrevDecl should refer to any previous declaration
16739 /// with the same name and in the same scope as the field to be
16740 /// created.
16741 ///
16742 /// \returns a new FieldDecl.
16743 ///
16744 /// \todo The Declarator argument is a hack. It will be removed once
16745 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16746                                 TypeSourceInfo *TInfo,
16747                                 RecordDecl *Record, SourceLocation Loc,
16748                                 bool Mutable, Expr *BitWidth,
16749                                 InClassInitStyle InitStyle,
16750                                 SourceLocation TSSL,
16751                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16752                                 Declarator *D) {
16753   IdentifierInfo *II = Name.getAsIdentifierInfo();
16754   bool InvalidDecl = false;
16755   if (D) InvalidDecl = D->isInvalidType();
16756 
16757   // If we receive a broken type, recover by assuming 'int' and
16758   // marking this declaration as invalid.
16759   if (T.isNull() || T->containsErrors()) {
16760     InvalidDecl = true;
16761     T = Context.IntTy;
16762   }
16763 
16764   QualType EltTy = Context.getBaseElementType(T);
16765   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16766     if (RequireCompleteSizedType(Loc, EltTy,
16767                                  diag::err_field_incomplete_or_sizeless)) {
16768       // Fields of incomplete type force their record to be invalid.
16769       Record->setInvalidDecl();
16770       InvalidDecl = true;
16771     } else {
16772       NamedDecl *Def;
16773       EltTy->isIncompleteType(&Def);
16774       if (Def && Def->isInvalidDecl()) {
16775         Record->setInvalidDecl();
16776         InvalidDecl = true;
16777       }
16778     }
16779   }
16780 
16781   // TR 18037 does not allow fields to be declared with address space
16782   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16783       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16784     Diag(Loc, diag::err_field_with_address_space);
16785     Record->setInvalidDecl();
16786     InvalidDecl = true;
16787   }
16788 
16789   if (LangOpts.OpenCL) {
16790     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16791     // used as structure or union field: image, sampler, event or block types.
16792     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16793         T->isBlockPointerType()) {
16794       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16795       Record->setInvalidDecl();
16796       InvalidDecl = true;
16797     }
16798     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16799     if (BitWidth) {
16800       Diag(Loc, diag::err_opencl_bitfields);
16801       InvalidDecl = true;
16802     }
16803   }
16804 
16805   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16806   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16807       T.hasQualifiers()) {
16808     InvalidDecl = true;
16809     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16810   }
16811 
16812   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16813   // than a variably modified type.
16814   if (!InvalidDecl && T->isVariablyModifiedType()) {
16815     if (!tryToFixVariablyModifiedVarType(
16816             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16817       InvalidDecl = true;
16818   }
16819 
16820   // Fields can not have abstract class types
16821   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16822                                              diag::err_abstract_type_in_decl,
16823                                              AbstractFieldType))
16824     InvalidDecl = true;
16825 
16826   bool ZeroWidth = false;
16827   if (InvalidDecl)
16828     BitWidth = nullptr;
16829   // If this is declared as a bit-field, check the bit-field.
16830   if (BitWidth) {
16831     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16832                               &ZeroWidth).get();
16833     if (!BitWidth) {
16834       InvalidDecl = true;
16835       BitWidth = nullptr;
16836       ZeroWidth = false;
16837     }
16838   }
16839 
16840   // Check that 'mutable' is consistent with the type of the declaration.
16841   if (!InvalidDecl && Mutable) {
16842     unsigned DiagID = 0;
16843     if (T->isReferenceType())
16844       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16845                                         : diag::err_mutable_reference;
16846     else if (T.isConstQualified())
16847       DiagID = diag::err_mutable_const;
16848 
16849     if (DiagID) {
16850       SourceLocation ErrLoc = Loc;
16851       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16852         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16853       Diag(ErrLoc, DiagID);
16854       if (DiagID != diag::ext_mutable_reference) {
16855         Mutable = false;
16856         InvalidDecl = true;
16857       }
16858     }
16859   }
16860 
16861   // C++11 [class.union]p8 (DR1460):
16862   //   At most one variant member of a union may have a
16863   //   brace-or-equal-initializer.
16864   if (InitStyle != ICIS_NoInit)
16865     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16866 
16867   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16868                                        BitWidth, Mutable, InitStyle);
16869   if (InvalidDecl)
16870     NewFD->setInvalidDecl();
16871 
16872   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16873     Diag(Loc, diag::err_duplicate_member) << II;
16874     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16875     NewFD->setInvalidDecl();
16876   }
16877 
16878   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16879     if (Record->isUnion()) {
16880       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16881         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16882         if (RDecl->getDefinition()) {
16883           // C++ [class.union]p1: An object of a class with a non-trivial
16884           // constructor, a non-trivial copy constructor, a non-trivial
16885           // destructor, or a non-trivial copy assignment operator
16886           // cannot be a member of a union, nor can an array of such
16887           // objects.
16888           if (CheckNontrivialField(NewFD))
16889             NewFD->setInvalidDecl();
16890         }
16891       }
16892 
16893       // C++ [class.union]p1: If a union contains a member of reference type,
16894       // the program is ill-formed, except when compiling with MSVC extensions
16895       // enabled.
16896       if (EltTy->isReferenceType()) {
16897         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16898                                     diag::ext_union_member_of_reference_type :
16899                                     diag::err_union_member_of_reference_type)
16900           << NewFD->getDeclName() << EltTy;
16901         if (!getLangOpts().MicrosoftExt)
16902           NewFD->setInvalidDecl();
16903       }
16904     }
16905   }
16906 
16907   // FIXME: We need to pass in the attributes given an AST
16908   // representation, not a parser representation.
16909   if (D) {
16910     // FIXME: The current scope is almost... but not entirely... correct here.
16911     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16912 
16913     if (NewFD->hasAttrs())
16914       CheckAlignasUnderalignment(NewFD);
16915   }
16916 
16917   // In auto-retain/release, infer strong retension for fields of
16918   // retainable type.
16919   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16920     NewFD->setInvalidDecl();
16921 
16922   if (T.isObjCGCWeak())
16923     Diag(Loc, diag::warn_attribute_weak_on_field);
16924 
16925   // PPC MMA non-pointer types are not allowed as field types.
16926   if (Context.getTargetInfo().getTriple().isPPC64() &&
16927       CheckPPCMMAType(T, NewFD->getLocation()))
16928     NewFD->setInvalidDecl();
16929 
16930   NewFD->setAccess(AS);
16931   return NewFD;
16932 }
16933 
16934 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16935   assert(FD);
16936   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16937 
16938   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16939     return false;
16940 
16941   QualType EltTy = Context.getBaseElementType(FD->getType());
16942   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16943     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16944     if (RDecl->getDefinition()) {
16945       // We check for copy constructors before constructors
16946       // because otherwise we'll never get complaints about
16947       // copy constructors.
16948 
16949       CXXSpecialMember member = CXXInvalid;
16950       // We're required to check for any non-trivial constructors. Since the
16951       // implicit default constructor is suppressed if there are any
16952       // user-declared constructors, we just need to check that there is a
16953       // trivial default constructor and a trivial copy constructor. (We don't
16954       // worry about move constructors here, since this is a C++98 check.)
16955       if (RDecl->hasNonTrivialCopyConstructor())
16956         member = CXXCopyConstructor;
16957       else if (!RDecl->hasTrivialDefaultConstructor())
16958         member = CXXDefaultConstructor;
16959       else if (RDecl->hasNonTrivialCopyAssignment())
16960         member = CXXCopyAssignment;
16961       else if (RDecl->hasNonTrivialDestructor())
16962         member = CXXDestructor;
16963 
16964       if (member != CXXInvalid) {
16965         if (!getLangOpts().CPlusPlus11 &&
16966             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16967           // Objective-C++ ARC: it is an error to have a non-trivial field of
16968           // a union. However, system headers in Objective-C programs
16969           // occasionally have Objective-C lifetime objects within unions,
16970           // and rather than cause the program to fail, we make those
16971           // members unavailable.
16972           SourceLocation Loc = FD->getLocation();
16973           if (getSourceManager().isInSystemHeader(Loc)) {
16974             if (!FD->hasAttr<UnavailableAttr>())
16975               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16976                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16977             return false;
16978           }
16979         }
16980 
16981         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16982                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16983                diag::err_illegal_union_or_anon_struct_member)
16984           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16985         DiagnoseNontrivial(RDecl, member);
16986         return !getLangOpts().CPlusPlus11;
16987       }
16988     }
16989   }
16990 
16991   return false;
16992 }
16993 
16994 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16995 ///  AST enum value.
16996 static ObjCIvarDecl::AccessControl
16997 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16998   switch (ivarVisibility) {
16999   default: llvm_unreachable("Unknown visitibility kind");
17000   case tok::objc_private: return ObjCIvarDecl::Private;
17001   case tok::objc_public: return ObjCIvarDecl::Public;
17002   case tok::objc_protected: return ObjCIvarDecl::Protected;
17003   case tok::objc_package: return ObjCIvarDecl::Package;
17004   }
17005 }
17006 
17007 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17008 /// in order to create an IvarDecl object for it.
17009 Decl *Sema::ActOnIvar(Scope *S,
17010                                 SourceLocation DeclStart,
17011                                 Declarator &D, Expr *BitfieldWidth,
17012                                 tok::ObjCKeywordKind Visibility) {
17013 
17014   IdentifierInfo *II = D.getIdentifier();
17015   Expr *BitWidth = (Expr*)BitfieldWidth;
17016   SourceLocation Loc = DeclStart;
17017   if (II) Loc = D.getIdentifierLoc();
17018 
17019   // FIXME: Unnamed fields can be handled in various different ways, for
17020   // example, unnamed unions inject all members into the struct namespace!
17021 
17022   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17023   QualType T = TInfo->getType();
17024 
17025   if (BitWidth) {
17026     // 6.7.2.1p3, 6.7.2.1p4
17027     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17028     if (!BitWidth)
17029       D.setInvalidType();
17030   } else {
17031     // Not a bitfield.
17032 
17033     // validate II.
17034 
17035   }
17036   if (T->isReferenceType()) {
17037     Diag(Loc, diag::err_ivar_reference_type);
17038     D.setInvalidType();
17039   }
17040   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17041   // than a variably modified type.
17042   else if (T->isVariablyModifiedType()) {
17043     if (!tryToFixVariablyModifiedVarType(
17044             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17045       D.setInvalidType();
17046   }
17047 
17048   // Get the visibility (access control) for this ivar.
17049   ObjCIvarDecl::AccessControl ac =
17050     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17051                                         : ObjCIvarDecl::None;
17052   // Must set ivar's DeclContext to its enclosing interface.
17053   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17054   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17055     return nullptr;
17056   ObjCContainerDecl *EnclosingContext;
17057   if (ObjCImplementationDecl *IMPDecl =
17058       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17059     if (LangOpts.ObjCRuntime.isFragile()) {
17060     // Case of ivar declared in an implementation. Context is that of its class.
17061       EnclosingContext = IMPDecl->getClassInterface();
17062       assert(EnclosingContext && "Implementation has no class interface!");
17063     }
17064     else
17065       EnclosingContext = EnclosingDecl;
17066   } else {
17067     if (ObjCCategoryDecl *CDecl =
17068         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17069       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17070         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17071         return nullptr;
17072       }
17073     }
17074     EnclosingContext = EnclosingDecl;
17075   }
17076 
17077   // Construct the decl.
17078   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17079                                              DeclStart, Loc, II, T,
17080                                              TInfo, ac, (Expr *)BitfieldWidth);
17081 
17082   if (II) {
17083     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17084                                            ForVisibleRedeclaration);
17085     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17086         && !isa<TagDecl>(PrevDecl)) {
17087       Diag(Loc, diag::err_duplicate_member) << II;
17088       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17089       NewID->setInvalidDecl();
17090     }
17091   }
17092 
17093   // Process attributes attached to the ivar.
17094   ProcessDeclAttributes(S, NewID, D);
17095 
17096   if (D.isInvalidType())
17097     NewID->setInvalidDecl();
17098 
17099   // In ARC, infer 'retaining' for ivars of retainable type.
17100   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17101     NewID->setInvalidDecl();
17102 
17103   if (D.getDeclSpec().isModulePrivateSpecified())
17104     NewID->setModulePrivate();
17105 
17106   if (II) {
17107     // FIXME: When interfaces are DeclContexts, we'll need to add
17108     // these to the interface.
17109     S->AddDecl(NewID);
17110     IdResolver.AddDecl(NewID);
17111   }
17112 
17113   if (LangOpts.ObjCRuntime.isNonFragile() &&
17114       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17115     Diag(Loc, diag::warn_ivars_in_interface);
17116 
17117   return NewID;
17118 }
17119 
17120 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17121 /// class and class extensions. For every class \@interface and class
17122 /// extension \@interface, if the last ivar is a bitfield of any type,
17123 /// then add an implicit `char :0` ivar to the end of that interface.
17124 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17125                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17126   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17127     return;
17128 
17129   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17130   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17131 
17132   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17133     return;
17134   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17135   if (!ID) {
17136     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17137       if (!CD->IsClassExtension())
17138         return;
17139     }
17140     // No need to add this to end of @implementation.
17141     else
17142       return;
17143   }
17144   // All conditions are met. Add a new bitfield to the tail end of ivars.
17145   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17146   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17147 
17148   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17149                               DeclLoc, DeclLoc, nullptr,
17150                               Context.CharTy,
17151                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17152                                                                DeclLoc),
17153                               ObjCIvarDecl::Private, BW,
17154                               true);
17155   AllIvarDecls.push_back(Ivar);
17156 }
17157 
17158 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17159                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17160                        SourceLocation RBrac,
17161                        const ParsedAttributesView &Attrs) {
17162   assert(EnclosingDecl && "missing record or interface decl");
17163 
17164   // If this is an Objective-C @implementation or category and we have
17165   // new fields here we should reset the layout of the interface since
17166   // it will now change.
17167   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17168     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17169     switch (DC->getKind()) {
17170     default: break;
17171     case Decl::ObjCCategory:
17172       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17173       break;
17174     case Decl::ObjCImplementation:
17175       Context.
17176         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17177       break;
17178     }
17179   }
17180 
17181   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17182   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17183 
17184   // Start counting up the number of named members; make sure to include
17185   // members of anonymous structs and unions in the total.
17186   unsigned NumNamedMembers = 0;
17187   if (Record) {
17188     for (const auto *I : Record->decls()) {
17189       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17190         if (IFD->getDeclName())
17191           ++NumNamedMembers;
17192     }
17193   }
17194 
17195   // Verify that all the fields are okay.
17196   SmallVector<FieldDecl*, 32> RecFields;
17197 
17198   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17199        i != end; ++i) {
17200     FieldDecl *FD = cast<FieldDecl>(*i);
17201 
17202     // Get the type for the field.
17203     const Type *FDTy = FD->getType().getTypePtr();
17204 
17205     if (!FD->isAnonymousStructOrUnion()) {
17206       // Remember all fields written by the user.
17207       RecFields.push_back(FD);
17208     }
17209 
17210     // If the field is already invalid for some reason, don't emit more
17211     // diagnostics about it.
17212     if (FD->isInvalidDecl()) {
17213       EnclosingDecl->setInvalidDecl();
17214       continue;
17215     }
17216 
17217     // C99 6.7.2.1p2:
17218     //   A structure or union shall not contain a member with
17219     //   incomplete or function type (hence, a structure shall not
17220     //   contain an instance of itself, but may contain a pointer to
17221     //   an instance of itself), except that the last member of a
17222     //   structure with more than one named member may have incomplete
17223     //   array type; such a structure (and any union containing,
17224     //   possibly recursively, a member that is such a structure)
17225     //   shall not be a member of a structure or an element of an
17226     //   array.
17227     bool IsLastField = (i + 1 == Fields.end());
17228     if (FDTy->isFunctionType()) {
17229       // Field declared as a function.
17230       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17231         << FD->getDeclName();
17232       FD->setInvalidDecl();
17233       EnclosingDecl->setInvalidDecl();
17234       continue;
17235     } else if (FDTy->isIncompleteArrayType() &&
17236                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17237       if (Record) {
17238         // Flexible array member.
17239         // Microsoft and g++ is more permissive regarding flexible array.
17240         // It will accept flexible array in union and also
17241         // as the sole element of a struct/class.
17242         unsigned DiagID = 0;
17243         if (!Record->isUnion() && !IsLastField) {
17244           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17245             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17246           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17247           FD->setInvalidDecl();
17248           EnclosingDecl->setInvalidDecl();
17249           continue;
17250         } else if (Record->isUnion())
17251           DiagID = getLangOpts().MicrosoftExt
17252                        ? diag::ext_flexible_array_union_ms
17253                        : getLangOpts().CPlusPlus
17254                              ? diag::ext_flexible_array_union_gnu
17255                              : diag::err_flexible_array_union;
17256         else if (NumNamedMembers < 1)
17257           DiagID = getLangOpts().MicrosoftExt
17258                        ? diag::ext_flexible_array_empty_aggregate_ms
17259                        : getLangOpts().CPlusPlus
17260                              ? diag::ext_flexible_array_empty_aggregate_gnu
17261                              : diag::err_flexible_array_empty_aggregate;
17262 
17263         if (DiagID)
17264           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17265                                           << Record->getTagKind();
17266         // While the layout of types that contain virtual bases is not specified
17267         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17268         // virtual bases after the derived members.  This would make a flexible
17269         // array member declared at the end of an object not adjacent to the end
17270         // of the type.
17271         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17272           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17273               << FD->getDeclName() << Record->getTagKind();
17274         if (!getLangOpts().C99)
17275           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17276             << FD->getDeclName() << Record->getTagKind();
17277 
17278         // If the element type has a non-trivial destructor, we would not
17279         // implicitly destroy the elements, so disallow it for now.
17280         //
17281         // FIXME: GCC allows this. We should probably either implicitly delete
17282         // the destructor of the containing class, or just allow this.
17283         QualType BaseElem = Context.getBaseElementType(FD->getType());
17284         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17285           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17286             << FD->getDeclName() << FD->getType();
17287           FD->setInvalidDecl();
17288           EnclosingDecl->setInvalidDecl();
17289           continue;
17290         }
17291         // Okay, we have a legal flexible array member at the end of the struct.
17292         Record->setHasFlexibleArrayMember(true);
17293       } else {
17294         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17295         // unless they are followed by another ivar. That check is done
17296         // elsewhere, after synthesized ivars are known.
17297       }
17298     } else if (!FDTy->isDependentType() &&
17299                RequireCompleteSizedType(
17300                    FD->getLocation(), FD->getType(),
17301                    diag::err_field_incomplete_or_sizeless)) {
17302       // Incomplete type
17303       FD->setInvalidDecl();
17304       EnclosingDecl->setInvalidDecl();
17305       continue;
17306     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17307       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17308         // A type which contains a flexible array member is considered to be a
17309         // flexible array member.
17310         Record->setHasFlexibleArrayMember(true);
17311         if (!Record->isUnion()) {
17312           // If this is a struct/class and this is not the last element, reject
17313           // it.  Note that GCC supports variable sized arrays in the middle of
17314           // structures.
17315           if (!IsLastField)
17316             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17317               << FD->getDeclName() << FD->getType();
17318           else {
17319             // We support flexible arrays at the end of structs in
17320             // other structs as an extension.
17321             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17322               << FD->getDeclName();
17323           }
17324         }
17325       }
17326       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17327           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17328                                  diag::err_abstract_type_in_decl,
17329                                  AbstractIvarType)) {
17330         // Ivars can not have abstract class types
17331         FD->setInvalidDecl();
17332       }
17333       if (Record && FDTTy->getDecl()->hasObjectMember())
17334         Record->setHasObjectMember(true);
17335       if (Record && FDTTy->getDecl()->hasVolatileMember())
17336         Record->setHasVolatileMember(true);
17337     } else if (FDTy->isObjCObjectType()) {
17338       /// A field cannot be an Objective-c object
17339       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17340         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17341       QualType T = Context.getObjCObjectPointerType(FD->getType());
17342       FD->setType(T);
17343     } else if (Record && Record->isUnion() &&
17344                FD->getType().hasNonTrivialObjCLifetime() &&
17345                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17346                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17347                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17348                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17349       // For backward compatibility, fields of C unions declared in system
17350       // headers that have non-trivial ObjC ownership qualifications are marked
17351       // as unavailable unless the qualifier is explicit and __strong. This can
17352       // break ABI compatibility between programs compiled with ARC and MRR, but
17353       // is a better option than rejecting programs using those unions under
17354       // ARC.
17355       FD->addAttr(UnavailableAttr::CreateImplicit(
17356           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17357           FD->getLocation()));
17358     } else if (getLangOpts().ObjC &&
17359                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17360                !Record->hasObjectMember()) {
17361       if (FD->getType()->isObjCObjectPointerType() ||
17362           FD->getType().isObjCGCStrong())
17363         Record->setHasObjectMember(true);
17364       else if (Context.getAsArrayType(FD->getType())) {
17365         QualType BaseType = Context.getBaseElementType(FD->getType());
17366         if (BaseType->isRecordType() &&
17367             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17368           Record->setHasObjectMember(true);
17369         else if (BaseType->isObjCObjectPointerType() ||
17370                  BaseType.isObjCGCStrong())
17371                Record->setHasObjectMember(true);
17372       }
17373     }
17374 
17375     if (Record && !getLangOpts().CPlusPlus &&
17376         !shouldIgnoreForRecordTriviality(FD)) {
17377       QualType FT = FD->getType();
17378       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17379         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17380         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17381             Record->isUnion())
17382           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17383       }
17384       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17385       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17386         Record->setNonTrivialToPrimitiveCopy(true);
17387         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17388           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17389       }
17390       if (FT.isDestructedType()) {
17391         Record->setNonTrivialToPrimitiveDestroy(true);
17392         Record->setParamDestroyedInCallee(true);
17393         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17394           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17395       }
17396 
17397       if (const auto *RT = FT->getAs<RecordType>()) {
17398         if (RT->getDecl()->getArgPassingRestrictions() ==
17399             RecordDecl::APK_CanNeverPassInRegs)
17400           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17401       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17402         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17403     }
17404 
17405     if (Record && FD->getType().isVolatileQualified())
17406       Record->setHasVolatileMember(true);
17407     // Keep track of the number of named members.
17408     if (FD->getIdentifier())
17409       ++NumNamedMembers;
17410   }
17411 
17412   // Okay, we successfully defined 'Record'.
17413   if (Record) {
17414     bool Completed = false;
17415     if (CXXRecord) {
17416       if (!CXXRecord->isInvalidDecl()) {
17417         // Set access bits correctly on the directly-declared conversions.
17418         for (CXXRecordDecl::conversion_iterator
17419                I = CXXRecord->conversion_begin(),
17420                E = CXXRecord->conversion_end(); I != E; ++I)
17421           I.setAccess((*I)->getAccess());
17422       }
17423 
17424       // Add any implicitly-declared members to this class.
17425       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17426 
17427       if (!CXXRecord->isDependentType()) {
17428         if (!CXXRecord->isInvalidDecl()) {
17429           // If we have virtual base classes, we may end up finding multiple
17430           // final overriders for a given virtual function. Check for this
17431           // problem now.
17432           if (CXXRecord->getNumVBases()) {
17433             CXXFinalOverriderMap FinalOverriders;
17434             CXXRecord->getFinalOverriders(FinalOverriders);
17435 
17436             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17437                                              MEnd = FinalOverriders.end();
17438                  M != MEnd; ++M) {
17439               for (OverridingMethods::iterator SO = M->second.begin(),
17440                                             SOEnd = M->second.end();
17441                    SO != SOEnd; ++SO) {
17442                 assert(SO->second.size() > 0 &&
17443                        "Virtual function without overriding functions?");
17444                 if (SO->second.size() == 1)
17445                   continue;
17446 
17447                 // C++ [class.virtual]p2:
17448                 //   In a derived class, if a virtual member function of a base
17449                 //   class subobject has more than one final overrider the
17450                 //   program is ill-formed.
17451                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17452                   << (const NamedDecl *)M->first << Record;
17453                 Diag(M->first->getLocation(),
17454                      diag::note_overridden_virtual_function);
17455                 for (OverridingMethods::overriding_iterator
17456                           OM = SO->second.begin(),
17457                        OMEnd = SO->second.end();
17458                      OM != OMEnd; ++OM)
17459                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17460                     << (const NamedDecl *)M->first << OM->Method->getParent();
17461 
17462                 Record->setInvalidDecl();
17463               }
17464             }
17465             CXXRecord->completeDefinition(&FinalOverriders);
17466             Completed = true;
17467           }
17468         }
17469       }
17470     }
17471 
17472     if (!Completed)
17473       Record->completeDefinition();
17474 
17475     // Handle attributes before checking the layout.
17476     ProcessDeclAttributeList(S, Record, Attrs);
17477 
17478     // We may have deferred checking for a deleted destructor. Check now.
17479     if (CXXRecord) {
17480       auto *Dtor = CXXRecord->getDestructor();
17481       if (Dtor && Dtor->isImplicit() &&
17482           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17483         CXXRecord->setImplicitDestructorIsDeleted();
17484         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17485       }
17486     }
17487 
17488     if (Record->hasAttrs()) {
17489       CheckAlignasUnderalignment(Record);
17490 
17491       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17492         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17493                                            IA->getRange(), IA->getBestCase(),
17494                                            IA->getInheritanceModel());
17495     }
17496 
17497     // Check if the structure/union declaration is a type that can have zero
17498     // size in C. For C this is a language extension, for C++ it may cause
17499     // compatibility problems.
17500     bool CheckForZeroSize;
17501     if (!getLangOpts().CPlusPlus) {
17502       CheckForZeroSize = true;
17503     } else {
17504       // For C++ filter out types that cannot be referenced in C code.
17505       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17506       CheckForZeroSize =
17507           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17508           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17509           CXXRecord->isCLike();
17510     }
17511     if (CheckForZeroSize) {
17512       bool ZeroSize = true;
17513       bool IsEmpty = true;
17514       unsigned NonBitFields = 0;
17515       for (RecordDecl::field_iterator I = Record->field_begin(),
17516                                       E = Record->field_end();
17517            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17518         IsEmpty = false;
17519         if (I->isUnnamedBitfield()) {
17520           if (!I->isZeroLengthBitField(Context))
17521             ZeroSize = false;
17522         } else {
17523           ++NonBitFields;
17524           QualType FieldType = I->getType();
17525           if (FieldType->isIncompleteType() ||
17526               !Context.getTypeSizeInChars(FieldType).isZero())
17527             ZeroSize = false;
17528         }
17529       }
17530 
17531       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17532       // allowed in C++, but warn if its declaration is inside
17533       // extern "C" block.
17534       if (ZeroSize) {
17535         Diag(RecLoc, getLangOpts().CPlusPlus ?
17536                          diag::warn_zero_size_struct_union_in_extern_c :
17537                          diag::warn_zero_size_struct_union_compat)
17538           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17539       }
17540 
17541       // Structs without named members are extension in C (C99 6.7.2.1p7),
17542       // but are accepted by GCC.
17543       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17544         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17545                                diag::ext_no_named_members_in_struct_union)
17546           << Record->isUnion();
17547       }
17548     }
17549   } else {
17550     ObjCIvarDecl **ClsFields =
17551       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17552     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17553       ID->setEndOfDefinitionLoc(RBrac);
17554       // Add ivar's to class's DeclContext.
17555       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17556         ClsFields[i]->setLexicalDeclContext(ID);
17557         ID->addDecl(ClsFields[i]);
17558       }
17559       // Must enforce the rule that ivars in the base classes may not be
17560       // duplicates.
17561       if (ID->getSuperClass())
17562         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17563     } else if (ObjCImplementationDecl *IMPDecl =
17564                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17565       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17566       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17567         // Ivar declared in @implementation never belongs to the implementation.
17568         // Only it is in implementation's lexical context.
17569         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17570       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17571       IMPDecl->setIvarLBraceLoc(LBrac);
17572       IMPDecl->setIvarRBraceLoc(RBrac);
17573     } else if (ObjCCategoryDecl *CDecl =
17574                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17575       // case of ivars in class extension; all other cases have been
17576       // reported as errors elsewhere.
17577       // FIXME. Class extension does not have a LocEnd field.
17578       // CDecl->setLocEnd(RBrac);
17579       // Add ivar's to class extension's DeclContext.
17580       // Diagnose redeclaration of private ivars.
17581       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17582       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17583         if (IDecl) {
17584           if (const ObjCIvarDecl *ClsIvar =
17585               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17586             Diag(ClsFields[i]->getLocation(),
17587                  diag::err_duplicate_ivar_declaration);
17588             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17589             continue;
17590           }
17591           for (const auto *Ext : IDecl->known_extensions()) {
17592             if (const ObjCIvarDecl *ClsExtIvar
17593                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17594               Diag(ClsFields[i]->getLocation(),
17595                    diag::err_duplicate_ivar_declaration);
17596               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17597               continue;
17598             }
17599           }
17600         }
17601         ClsFields[i]->setLexicalDeclContext(CDecl);
17602         CDecl->addDecl(ClsFields[i]);
17603       }
17604       CDecl->setIvarLBraceLoc(LBrac);
17605       CDecl->setIvarRBraceLoc(RBrac);
17606     }
17607   }
17608 }
17609 
17610 /// Determine whether the given integral value is representable within
17611 /// the given type T.
17612 static bool isRepresentableIntegerValue(ASTContext &Context,
17613                                         llvm::APSInt &Value,
17614                                         QualType T) {
17615   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17616          "Integral type required!");
17617   unsigned BitWidth = Context.getIntWidth(T);
17618 
17619   if (Value.isUnsigned() || Value.isNonNegative()) {
17620     if (T->isSignedIntegerOrEnumerationType())
17621       --BitWidth;
17622     return Value.getActiveBits() <= BitWidth;
17623   }
17624   return Value.getMinSignedBits() <= BitWidth;
17625 }
17626 
17627 // Given an integral type, return the next larger integral type
17628 // (or a NULL type of no such type exists).
17629 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17630   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17631   // enum checking below.
17632   assert((T->isIntegralType(Context) ||
17633          T->isEnumeralType()) && "Integral type required!");
17634   const unsigned NumTypes = 4;
17635   QualType SignedIntegralTypes[NumTypes] = {
17636     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17637   };
17638   QualType UnsignedIntegralTypes[NumTypes] = {
17639     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17640     Context.UnsignedLongLongTy
17641   };
17642 
17643   unsigned BitWidth = Context.getTypeSize(T);
17644   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17645                                                         : UnsignedIntegralTypes;
17646   for (unsigned I = 0; I != NumTypes; ++I)
17647     if (Context.getTypeSize(Types[I]) > BitWidth)
17648       return Types[I];
17649 
17650   return QualType();
17651 }
17652 
17653 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17654                                           EnumConstantDecl *LastEnumConst,
17655                                           SourceLocation IdLoc,
17656                                           IdentifierInfo *Id,
17657                                           Expr *Val) {
17658   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17659   llvm::APSInt EnumVal(IntWidth);
17660   QualType EltTy;
17661 
17662   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17663     Val = nullptr;
17664 
17665   if (Val)
17666     Val = DefaultLvalueConversion(Val).get();
17667 
17668   if (Val) {
17669     if (Enum->isDependentType() || Val->isTypeDependent())
17670       EltTy = Context.DependentTy;
17671     else {
17672       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17673       // underlying type, but do allow it in all other contexts.
17674       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17675         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17676         // constant-expression in the enumerator-definition shall be a converted
17677         // constant expression of the underlying type.
17678         EltTy = Enum->getIntegerType();
17679         ExprResult Converted =
17680           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17681                                            CCEK_Enumerator);
17682         if (Converted.isInvalid())
17683           Val = nullptr;
17684         else
17685           Val = Converted.get();
17686       } else if (!Val->isValueDependent() &&
17687                  !(Val =
17688                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17689                            .get())) {
17690         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17691       } else {
17692         if (Enum->isComplete()) {
17693           EltTy = Enum->getIntegerType();
17694 
17695           // In Obj-C and Microsoft mode, require the enumeration value to be
17696           // representable in the underlying type of the enumeration. In C++11,
17697           // we perform a non-narrowing conversion as part of converted constant
17698           // expression checking.
17699           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17700             if (Context.getTargetInfo()
17701                     .getTriple()
17702                     .isWindowsMSVCEnvironment()) {
17703               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17704             } else {
17705               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17706             }
17707           }
17708 
17709           // Cast to the underlying type.
17710           Val = ImpCastExprToType(Val, EltTy,
17711                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17712                                                          : CK_IntegralCast)
17713                     .get();
17714         } else if (getLangOpts().CPlusPlus) {
17715           // C++11 [dcl.enum]p5:
17716           //   If the underlying type is not fixed, the type of each enumerator
17717           //   is the type of its initializing value:
17718           //     - If an initializer is specified for an enumerator, the
17719           //       initializing value has the same type as the expression.
17720           EltTy = Val->getType();
17721         } else {
17722           // C99 6.7.2.2p2:
17723           //   The expression that defines the value of an enumeration constant
17724           //   shall be an integer constant expression that has a value
17725           //   representable as an int.
17726 
17727           // Complain if the value is not representable in an int.
17728           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17729             Diag(IdLoc, diag::ext_enum_value_not_int)
17730               << EnumVal.toString(10) << Val->getSourceRange()
17731               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17732           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17733             // Force the type of the expression to 'int'.
17734             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17735           }
17736           EltTy = Val->getType();
17737         }
17738       }
17739     }
17740   }
17741 
17742   if (!Val) {
17743     if (Enum->isDependentType())
17744       EltTy = Context.DependentTy;
17745     else if (!LastEnumConst) {
17746       // C++0x [dcl.enum]p5:
17747       //   If the underlying type is not fixed, the type of each enumerator
17748       //   is the type of its initializing value:
17749       //     - If no initializer is specified for the first enumerator, the
17750       //       initializing value has an unspecified integral type.
17751       //
17752       // GCC uses 'int' for its unspecified integral type, as does
17753       // C99 6.7.2.2p3.
17754       if (Enum->isFixed()) {
17755         EltTy = Enum->getIntegerType();
17756       }
17757       else {
17758         EltTy = Context.IntTy;
17759       }
17760     } else {
17761       // Assign the last value + 1.
17762       EnumVal = LastEnumConst->getInitVal();
17763       ++EnumVal;
17764       EltTy = LastEnumConst->getType();
17765 
17766       // Check for overflow on increment.
17767       if (EnumVal < LastEnumConst->getInitVal()) {
17768         // C++0x [dcl.enum]p5:
17769         //   If the underlying type is not fixed, the type of each enumerator
17770         //   is the type of its initializing value:
17771         //
17772         //     - Otherwise the type of the initializing value is the same as
17773         //       the type of the initializing value of the preceding enumerator
17774         //       unless the incremented value is not representable in that type,
17775         //       in which case the type is an unspecified integral type
17776         //       sufficient to contain the incremented value. If no such type
17777         //       exists, the program is ill-formed.
17778         QualType T = getNextLargerIntegralType(Context, EltTy);
17779         if (T.isNull() || Enum->isFixed()) {
17780           // There is no integral type larger enough to represent this
17781           // value. Complain, then allow the value to wrap around.
17782           EnumVal = LastEnumConst->getInitVal();
17783           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17784           ++EnumVal;
17785           if (Enum->isFixed())
17786             // When the underlying type is fixed, this is ill-formed.
17787             Diag(IdLoc, diag::err_enumerator_wrapped)
17788               << EnumVal.toString(10)
17789               << EltTy;
17790           else
17791             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17792               << EnumVal.toString(10);
17793         } else {
17794           EltTy = T;
17795         }
17796 
17797         // Retrieve the last enumerator's value, extent that type to the
17798         // type that is supposed to be large enough to represent the incremented
17799         // value, then increment.
17800         EnumVal = LastEnumConst->getInitVal();
17801         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17802         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17803         ++EnumVal;
17804 
17805         // If we're not in C++, diagnose the overflow of enumerator values,
17806         // which in C99 means that the enumerator value is not representable in
17807         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17808         // permits enumerator values that are representable in some larger
17809         // integral type.
17810         if (!getLangOpts().CPlusPlus && !T.isNull())
17811           Diag(IdLoc, diag::warn_enum_value_overflow);
17812       } else if (!getLangOpts().CPlusPlus &&
17813                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17814         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17815         Diag(IdLoc, diag::ext_enum_value_not_int)
17816           << EnumVal.toString(10) << 1;
17817       }
17818     }
17819   }
17820 
17821   if (!EltTy->isDependentType()) {
17822     // Make the enumerator value match the signedness and size of the
17823     // enumerator's type.
17824     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17825     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17826   }
17827 
17828   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17829                                   Val, EnumVal);
17830 }
17831 
17832 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17833                                                 SourceLocation IILoc) {
17834   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17835       !getLangOpts().CPlusPlus)
17836     return SkipBodyInfo();
17837 
17838   // We have an anonymous enum definition. Look up the first enumerator to
17839   // determine if we should merge the definition with an existing one and
17840   // skip the body.
17841   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17842                                          forRedeclarationInCurContext());
17843   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17844   if (!PrevECD)
17845     return SkipBodyInfo();
17846 
17847   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17848   NamedDecl *Hidden;
17849   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17850     SkipBodyInfo Skip;
17851     Skip.Previous = Hidden;
17852     return Skip;
17853   }
17854 
17855   return SkipBodyInfo();
17856 }
17857 
17858 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17859                               SourceLocation IdLoc, IdentifierInfo *Id,
17860                               const ParsedAttributesView &Attrs,
17861                               SourceLocation EqualLoc, Expr *Val) {
17862   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17863   EnumConstantDecl *LastEnumConst =
17864     cast_or_null<EnumConstantDecl>(lastEnumConst);
17865 
17866   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17867   // we find one that is.
17868   S = getNonFieldDeclScope(S);
17869 
17870   // Verify that there isn't already something declared with this name in this
17871   // scope.
17872   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17873   LookupName(R, S);
17874   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17875 
17876   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17877     // Maybe we will complain about the shadowed template parameter.
17878     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17879     // Just pretend that we didn't see the previous declaration.
17880     PrevDecl = nullptr;
17881   }
17882 
17883   // C++ [class.mem]p15:
17884   // If T is the name of a class, then each of the following shall have a name
17885   // different from T:
17886   // - every enumerator of every member of class T that is an unscoped
17887   // enumerated type
17888   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17889     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17890                             DeclarationNameInfo(Id, IdLoc));
17891 
17892   EnumConstantDecl *New =
17893     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17894   if (!New)
17895     return nullptr;
17896 
17897   if (PrevDecl) {
17898     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17899       // Check for other kinds of shadowing not already handled.
17900       CheckShadow(New, PrevDecl, R);
17901     }
17902 
17903     // When in C++, we may get a TagDecl with the same name; in this case the
17904     // enum constant will 'hide' the tag.
17905     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17906            "Received TagDecl when not in C++!");
17907     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17908       if (isa<EnumConstantDecl>(PrevDecl))
17909         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17910       else
17911         Diag(IdLoc, diag::err_redefinition) << Id;
17912       notePreviousDefinition(PrevDecl, IdLoc);
17913       return nullptr;
17914     }
17915   }
17916 
17917   // Process attributes.
17918   ProcessDeclAttributeList(S, New, Attrs);
17919   AddPragmaAttributes(S, New);
17920 
17921   // Register this decl in the current scope stack.
17922   New->setAccess(TheEnumDecl->getAccess());
17923   PushOnScopeChains(New, S);
17924 
17925   ActOnDocumentableDecl(New);
17926 
17927   return New;
17928 }
17929 
17930 // Returns true when the enum initial expression does not trigger the
17931 // duplicate enum warning.  A few common cases are exempted as follows:
17932 // Element2 = Element1
17933 // Element2 = Element1 + 1
17934 // Element2 = Element1 - 1
17935 // Where Element2 and Element1 are from the same enum.
17936 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17937   Expr *InitExpr = ECD->getInitExpr();
17938   if (!InitExpr)
17939     return true;
17940   InitExpr = InitExpr->IgnoreImpCasts();
17941 
17942   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17943     if (!BO->isAdditiveOp())
17944       return true;
17945     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17946     if (!IL)
17947       return true;
17948     if (IL->getValue() != 1)
17949       return true;
17950 
17951     InitExpr = BO->getLHS();
17952   }
17953 
17954   // This checks if the elements are from the same enum.
17955   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17956   if (!DRE)
17957     return true;
17958 
17959   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17960   if (!EnumConstant)
17961     return true;
17962 
17963   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17964       Enum)
17965     return true;
17966 
17967   return false;
17968 }
17969 
17970 // Emits a warning when an element is implicitly set a value that
17971 // a previous element has already been set to.
17972 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17973                                         EnumDecl *Enum, QualType EnumType) {
17974   // Avoid anonymous enums
17975   if (!Enum->getIdentifier())
17976     return;
17977 
17978   // Only check for small enums.
17979   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17980     return;
17981 
17982   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17983     return;
17984 
17985   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17986   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17987 
17988   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17989 
17990   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17991   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17992 
17993   // Use int64_t as a key to avoid needing special handling for map keys.
17994   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17995     llvm::APSInt Val = D->getInitVal();
17996     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17997   };
17998 
17999   DuplicatesVector DupVector;
18000   ValueToVectorMap EnumMap;
18001 
18002   // Populate the EnumMap with all values represented by enum constants without
18003   // an initializer.
18004   for (auto *Element : Elements) {
18005     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18006 
18007     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18008     // this constant.  Skip this enum since it may be ill-formed.
18009     if (!ECD) {
18010       return;
18011     }
18012 
18013     // Constants with initalizers are handled in the next loop.
18014     if (ECD->getInitExpr())
18015       continue;
18016 
18017     // Duplicate values are handled in the next loop.
18018     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18019   }
18020 
18021   if (EnumMap.size() == 0)
18022     return;
18023 
18024   // Create vectors for any values that has duplicates.
18025   for (auto *Element : Elements) {
18026     // The last loop returned if any constant was null.
18027     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18028     if (!ValidDuplicateEnum(ECD, Enum))
18029       continue;
18030 
18031     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18032     if (Iter == EnumMap.end())
18033       continue;
18034 
18035     DeclOrVector& Entry = Iter->second;
18036     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18037       // Ensure constants are different.
18038       if (D == ECD)
18039         continue;
18040 
18041       // Create new vector and push values onto it.
18042       auto Vec = std::make_unique<ECDVector>();
18043       Vec->push_back(D);
18044       Vec->push_back(ECD);
18045 
18046       // Update entry to point to the duplicates vector.
18047       Entry = Vec.get();
18048 
18049       // Store the vector somewhere we can consult later for quick emission of
18050       // diagnostics.
18051       DupVector.emplace_back(std::move(Vec));
18052       continue;
18053     }
18054 
18055     ECDVector *Vec = Entry.get<ECDVector*>();
18056     // Make sure constants are not added more than once.
18057     if (*Vec->begin() == ECD)
18058       continue;
18059 
18060     Vec->push_back(ECD);
18061   }
18062 
18063   // Emit diagnostics.
18064   for (const auto &Vec : DupVector) {
18065     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18066 
18067     // Emit warning for one enum constant.
18068     auto *FirstECD = Vec->front();
18069     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18070       << FirstECD << FirstECD->getInitVal().toString(10)
18071       << FirstECD->getSourceRange();
18072 
18073     // Emit one note for each of the remaining enum constants with
18074     // the same value.
18075     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18076       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18077         << ECD << ECD->getInitVal().toString(10)
18078         << ECD->getSourceRange();
18079   }
18080 }
18081 
18082 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18083                              bool AllowMask) const {
18084   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18085   assert(ED->isCompleteDefinition() && "expected enum definition");
18086 
18087   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18088   llvm::APInt &FlagBits = R.first->second;
18089 
18090   if (R.second) {
18091     for (auto *E : ED->enumerators()) {
18092       const auto &EVal = E->getInitVal();
18093       // Only single-bit enumerators introduce new flag values.
18094       if (EVal.isPowerOf2())
18095         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18096     }
18097   }
18098 
18099   // A value is in a flag enum if either its bits are a subset of the enum's
18100   // flag bits (the first condition) or we are allowing masks and the same is
18101   // true of its complement (the second condition). When masks are allowed, we
18102   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18103   //
18104   // While it's true that any value could be used as a mask, the assumption is
18105   // that a mask will have all of the insignificant bits set. Anything else is
18106   // likely a logic error.
18107   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18108   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18109 }
18110 
18111 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18112                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18113                          const ParsedAttributesView &Attrs) {
18114   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18115   QualType EnumType = Context.getTypeDeclType(Enum);
18116 
18117   ProcessDeclAttributeList(S, Enum, Attrs);
18118 
18119   if (Enum->isDependentType()) {
18120     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18121       EnumConstantDecl *ECD =
18122         cast_or_null<EnumConstantDecl>(Elements[i]);
18123       if (!ECD) continue;
18124 
18125       ECD->setType(EnumType);
18126     }
18127 
18128     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18129     return;
18130   }
18131 
18132   // TODO: If the result value doesn't fit in an int, it must be a long or long
18133   // long value.  ISO C does not support this, but GCC does as an extension,
18134   // emit a warning.
18135   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18136   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18137   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18138 
18139   // Verify that all the values are okay, compute the size of the values, and
18140   // reverse the list.
18141   unsigned NumNegativeBits = 0;
18142   unsigned NumPositiveBits = 0;
18143 
18144   // Keep track of whether all elements have type int.
18145   bool AllElementsInt = true;
18146 
18147   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18148     EnumConstantDecl *ECD =
18149       cast_or_null<EnumConstantDecl>(Elements[i]);
18150     if (!ECD) continue;  // Already issued a diagnostic.
18151 
18152     const llvm::APSInt &InitVal = ECD->getInitVal();
18153 
18154     // Keep track of the size of positive and negative values.
18155     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18156       NumPositiveBits = std::max(NumPositiveBits,
18157                                  (unsigned)InitVal.getActiveBits());
18158     else
18159       NumNegativeBits = std::max(NumNegativeBits,
18160                                  (unsigned)InitVal.getMinSignedBits());
18161 
18162     // Keep track of whether every enum element has type int (very common).
18163     if (AllElementsInt)
18164       AllElementsInt = ECD->getType() == Context.IntTy;
18165   }
18166 
18167   // Figure out the type that should be used for this enum.
18168   QualType BestType;
18169   unsigned BestWidth;
18170 
18171   // C++0x N3000 [conv.prom]p3:
18172   //   An rvalue of an unscoped enumeration type whose underlying
18173   //   type is not fixed can be converted to an rvalue of the first
18174   //   of the following types that can represent all the values of
18175   //   the enumeration: int, unsigned int, long int, unsigned long
18176   //   int, long long int, or unsigned long long int.
18177   // C99 6.4.4.3p2:
18178   //   An identifier declared as an enumeration constant has type int.
18179   // The C99 rule is modified by a gcc extension
18180   QualType BestPromotionType;
18181 
18182   bool Packed = Enum->hasAttr<PackedAttr>();
18183   // -fshort-enums is the equivalent to specifying the packed attribute on all
18184   // enum definitions.
18185   if (LangOpts.ShortEnums)
18186     Packed = true;
18187 
18188   // If the enum already has a type because it is fixed or dictated by the
18189   // target, promote that type instead of analyzing the enumerators.
18190   if (Enum->isComplete()) {
18191     BestType = Enum->getIntegerType();
18192     if (BestType->isPromotableIntegerType())
18193       BestPromotionType = Context.getPromotedIntegerType(BestType);
18194     else
18195       BestPromotionType = BestType;
18196 
18197     BestWidth = Context.getIntWidth(BestType);
18198   }
18199   else if (NumNegativeBits) {
18200     // If there is a negative value, figure out the smallest integer type (of
18201     // int/long/longlong) that fits.
18202     // If it's packed, check also if it fits a char or a short.
18203     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18204       BestType = Context.SignedCharTy;
18205       BestWidth = CharWidth;
18206     } else if (Packed && NumNegativeBits <= ShortWidth &&
18207                NumPositiveBits < ShortWidth) {
18208       BestType = Context.ShortTy;
18209       BestWidth = ShortWidth;
18210     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18211       BestType = Context.IntTy;
18212       BestWidth = IntWidth;
18213     } else {
18214       BestWidth = Context.getTargetInfo().getLongWidth();
18215 
18216       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18217         BestType = Context.LongTy;
18218       } else {
18219         BestWidth = Context.getTargetInfo().getLongLongWidth();
18220 
18221         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18222           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18223         BestType = Context.LongLongTy;
18224       }
18225     }
18226     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18227   } else {
18228     // If there is no negative value, figure out the smallest type that fits
18229     // all of the enumerator values.
18230     // If it's packed, check also if it fits a char or a short.
18231     if (Packed && NumPositiveBits <= CharWidth) {
18232       BestType = Context.UnsignedCharTy;
18233       BestPromotionType = Context.IntTy;
18234       BestWidth = CharWidth;
18235     } else if (Packed && NumPositiveBits <= ShortWidth) {
18236       BestType = Context.UnsignedShortTy;
18237       BestPromotionType = Context.IntTy;
18238       BestWidth = ShortWidth;
18239     } else if (NumPositiveBits <= IntWidth) {
18240       BestType = Context.UnsignedIntTy;
18241       BestWidth = IntWidth;
18242       BestPromotionType
18243         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18244                            ? Context.UnsignedIntTy : Context.IntTy;
18245     } else if (NumPositiveBits <=
18246                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18247       BestType = Context.UnsignedLongTy;
18248       BestPromotionType
18249         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18250                            ? Context.UnsignedLongTy : Context.LongTy;
18251     } else {
18252       BestWidth = Context.getTargetInfo().getLongLongWidth();
18253       assert(NumPositiveBits <= BestWidth &&
18254              "How could an initializer get larger than ULL?");
18255       BestType = Context.UnsignedLongLongTy;
18256       BestPromotionType
18257         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18258                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18259     }
18260   }
18261 
18262   // Loop over all of the enumerator constants, changing their types to match
18263   // the type of the enum if needed.
18264   for (auto *D : Elements) {
18265     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18266     if (!ECD) continue;  // Already issued a diagnostic.
18267 
18268     // Standard C says the enumerators have int type, but we allow, as an
18269     // extension, the enumerators to be larger than int size.  If each
18270     // enumerator value fits in an int, type it as an int, otherwise type it the
18271     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18272     // that X has type 'int', not 'unsigned'.
18273 
18274     // Determine whether the value fits into an int.
18275     llvm::APSInt InitVal = ECD->getInitVal();
18276 
18277     // If it fits into an integer type, force it.  Otherwise force it to match
18278     // the enum decl type.
18279     QualType NewTy;
18280     unsigned NewWidth;
18281     bool NewSign;
18282     if (!getLangOpts().CPlusPlus &&
18283         !Enum->isFixed() &&
18284         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18285       NewTy = Context.IntTy;
18286       NewWidth = IntWidth;
18287       NewSign = true;
18288     } else if (ECD->getType() == BestType) {
18289       // Already the right type!
18290       if (getLangOpts().CPlusPlus)
18291         // C++ [dcl.enum]p4: Following the closing brace of an
18292         // enum-specifier, each enumerator has the type of its
18293         // enumeration.
18294         ECD->setType(EnumType);
18295       continue;
18296     } else {
18297       NewTy = BestType;
18298       NewWidth = BestWidth;
18299       NewSign = BestType->isSignedIntegerOrEnumerationType();
18300     }
18301 
18302     // Adjust the APSInt value.
18303     InitVal = InitVal.extOrTrunc(NewWidth);
18304     InitVal.setIsSigned(NewSign);
18305     ECD->setInitVal(InitVal);
18306 
18307     // Adjust the Expr initializer and type.
18308     if (ECD->getInitExpr() &&
18309         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18310       ECD->setInitExpr(ImplicitCastExpr::Create(
18311           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18312           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18313     if (getLangOpts().CPlusPlus)
18314       // C++ [dcl.enum]p4: Following the closing brace of an
18315       // enum-specifier, each enumerator has the type of its
18316       // enumeration.
18317       ECD->setType(EnumType);
18318     else
18319       ECD->setType(NewTy);
18320   }
18321 
18322   Enum->completeDefinition(BestType, BestPromotionType,
18323                            NumPositiveBits, NumNegativeBits);
18324 
18325   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18326 
18327   if (Enum->isClosedFlag()) {
18328     for (Decl *D : Elements) {
18329       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18330       if (!ECD) continue;  // Already issued a diagnostic.
18331 
18332       llvm::APSInt InitVal = ECD->getInitVal();
18333       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18334           !IsValueInFlagEnum(Enum, InitVal, true))
18335         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18336           << ECD << Enum;
18337     }
18338   }
18339 
18340   // Now that the enum type is defined, ensure it's not been underaligned.
18341   if (Enum->hasAttrs())
18342     CheckAlignasUnderalignment(Enum);
18343 }
18344 
18345 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18346                                   SourceLocation StartLoc,
18347                                   SourceLocation EndLoc) {
18348   StringLiteral *AsmString = cast<StringLiteral>(expr);
18349 
18350   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18351                                                    AsmString, StartLoc,
18352                                                    EndLoc);
18353   CurContext->addDecl(New);
18354   return New;
18355 }
18356 
18357 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18358                                       IdentifierInfo* AliasName,
18359                                       SourceLocation PragmaLoc,
18360                                       SourceLocation NameLoc,
18361                                       SourceLocation AliasNameLoc) {
18362   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18363                                          LookupOrdinaryName);
18364   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18365                            AttributeCommonInfo::AS_Pragma);
18366   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18367       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18368 
18369   // If a declaration that:
18370   // 1) declares a function or a variable
18371   // 2) has external linkage
18372   // already exists, add a label attribute to it.
18373   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18374     if (isDeclExternC(PrevDecl))
18375       PrevDecl->addAttr(Attr);
18376     else
18377       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18378           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18379   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18380   } else
18381     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18382 }
18383 
18384 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18385                              SourceLocation PragmaLoc,
18386                              SourceLocation NameLoc) {
18387   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18388 
18389   if (PrevDecl) {
18390     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18391   } else {
18392     (void)WeakUndeclaredIdentifiers.insert(
18393       std::pair<IdentifierInfo*,WeakInfo>
18394         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18395   }
18396 }
18397 
18398 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18399                                 IdentifierInfo* AliasName,
18400                                 SourceLocation PragmaLoc,
18401                                 SourceLocation NameLoc,
18402                                 SourceLocation AliasNameLoc) {
18403   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18404                                     LookupOrdinaryName);
18405   WeakInfo W = WeakInfo(Name, NameLoc);
18406 
18407   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18408     if (!PrevDecl->hasAttr<AliasAttr>())
18409       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18410         DeclApplyPragmaWeak(TUScope, ND, W);
18411   } else {
18412     (void)WeakUndeclaredIdentifiers.insert(
18413       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18414   }
18415 }
18416 
18417 Decl *Sema::getObjCDeclContext() const {
18418   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18419 }
18420 
18421 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18422                                                      bool Final) {
18423   assert(FD && "Expected non-null FunctionDecl");
18424 
18425   // SYCL functions can be template, so we check if they have appropriate
18426   // attribute prior to checking if it is a template.
18427   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18428     return FunctionEmissionStatus::Emitted;
18429 
18430   // Templates are emitted when they're instantiated.
18431   if (FD->isDependentContext())
18432     return FunctionEmissionStatus::TemplateDiscarded;
18433 
18434   // Check whether this function is an externally visible definition.
18435   auto IsEmittedForExternalSymbol = [this, FD]() {
18436     // We have to check the GVA linkage of the function's *definition* -- if we
18437     // only have a declaration, we don't know whether or not the function will
18438     // be emitted, because (say) the definition could include "inline".
18439     FunctionDecl *Def = FD->getDefinition();
18440 
18441     return Def && !isDiscardableGVALinkage(
18442                       getASTContext().GetGVALinkageForFunction(Def));
18443   };
18444 
18445   if (LangOpts.OpenMPIsDevice) {
18446     // In OpenMP device mode we will not emit host only functions, or functions
18447     // we don't need due to their linkage.
18448     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18449         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18450     // DevTy may be changed later by
18451     //  #pragma omp declare target to(*) device_type(*).
18452     // Therefore DevTyhaving no value does not imply host. The emission status
18453     // will be checked again at the end of compilation unit with Final = true.
18454     if (DevTy.hasValue())
18455       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18456         return FunctionEmissionStatus::OMPDiscarded;
18457     // If we have an explicit value for the device type, or we are in a target
18458     // declare context, we need to emit all extern and used symbols.
18459     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18460       if (IsEmittedForExternalSymbol())
18461         return FunctionEmissionStatus::Emitted;
18462     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18463     // we'll omit it.
18464     if (Final)
18465       return FunctionEmissionStatus::OMPDiscarded;
18466   } else if (LangOpts.OpenMP > 45) {
18467     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18468     // function. In 5.0, no_host was introduced which might cause a function to
18469     // be ommitted.
18470     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18471         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18472     if (DevTy.hasValue())
18473       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18474         return FunctionEmissionStatus::OMPDiscarded;
18475   }
18476 
18477   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18478     return FunctionEmissionStatus::Emitted;
18479 
18480   if (LangOpts.CUDA) {
18481     // When compiling for device, host functions are never emitted.  Similarly,
18482     // when compiling for host, device and global functions are never emitted.
18483     // (Technically, we do emit a host-side stub for global functions, but this
18484     // doesn't count for our purposes here.)
18485     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18486     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18487       return FunctionEmissionStatus::CUDADiscarded;
18488     if (!LangOpts.CUDAIsDevice &&
18489         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18490       return FunctionEmissionStatus::CUDADiscarded;
18491 
18492     if (IsEmittedForExternalSymbol())
18493       return FunctionEmissionStatus::Emitted;
18494   }
18495 
18496   // Otherwise, the function is known-emitted if it's in our set of
18497   // known-emitted functions.
18498   return FunctionEmissionStatus::Unknown;
18499 }
18500 
18501 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18502   // Host-side references to a __global__ function refer to the stub, so the
18503   // function itself is never emitted and therefore should not be marked.
18504   // If we have host fn calls kernel fn calls host+device, the HD function
18505   // does not get instantiated on the host. We model this by omitting at the
18506   // call to the kernel from the callgraph. This ensures that, when compiling
18507   // for host, only HD functions actually called from the host get marked as
18508   // known-emitted.
18509   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18510          IdentifyCUDATarget(Callee) == CFT_Global;
18511 }
18512