1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439         if (!IIDecl ||
440             (*Res)->getLocation().getRawEncoding() <
441               IIDecl->getLocation().getRawEncoding())
442           IIDecl = *Res;
443       }
444     }
445 
446     if (!IIDecl) {
447       // None of the entities we found is a type, so there is no way
448       // to even assume that the result is a type. In this case, don't
449       // complain about the ambiguity. The parser will either try to
450       // perform this lookup again (e.g., as an object name), which
451       // will produce the ambiguity, or will complain that it expected
452       // a type name.
453       Result.suppressDiagnostics();
454       return nullptr;
455     }
456 
457     // We found a type within the ambiguous lookup; diagnose the
458     // ambiguity and then return that type. This might be the right
459     // answer, or it might not be, but it suppresses any attempt to
460     // perform the name lookup again.
461     break;
462 
463   case LookupResult::Found:
464     IIDecl = Result.getFoundDecl();
465     break;
466   }
467 
468   assert(IIDecl && "Didn't find decl");
469 
470   QualType T;
471   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472     // C++ [class.qual]p2: A lookup that would find the injected-class-name
473     // instead names the constructors of the class, except when naming a class.
474     // This is ill-formed when we're not actually forming a ctor or dtor name.
475     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478         FoundRD->isInjectedClassName() &&
479         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481           << &II << /*Type*/1;
482 
483     DiagnoseUseOfDecl(IIDecl, NameLoc);
484 
485     T = Context.getTypeDeclType(TD);
486     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489     if (!HasTrailingDot)
490       T = Context.getObjCInterfaceType(IDecl);
491   } else if (AllowDeducedTemplate) {
492     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494                                                        QualType(), false);
495   }
496 
497   if (T.isNull()) {
498     // If it's not plausibly a type, suppress diagnostics.
499     Result.suppressDiagnostics();
500     return nullptr;
501   }
502 
503   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504   // constructor or destructor name (in such a case, the scope specifier
505   // will be attached to the enclosing Expr or Decl node).
506   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507       !isa<ObjCInterfaceDecl>(IIDecl)) {
508     if (WantNontrivialTypeSourceInfo) {
509       // Construct a type with type-source information.
510       TypeLocBuilder Builder;
511       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512 
513       T = getElaboratedType(ETK_None, *SS, T);
514       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515       ElabTL.setElaboratedKeywordLoc(SourceLocation());
516       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518     } else {
519       T = getElaboratedType(ETK_None, *SS, T);
520     }
521   }
522 
523   return ParsedType::make(T);
524 }
525 
526 // Builds a fake NNS for the given decl context.
527 static NestedNameSpecifier *
528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529   for (;; DC = DC->getLookupParent()) {
530     DC = DC->getPrimaryContext();
531     auto *ND = dyn_cast<NamespaceDecl>(DC);
532     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533       return NestedNameSpecifier::Create(Context, nullptr, ND);
534     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536                                          RD->getTypeForDecl());
537     else if (isa<TranslationUnitDecl>(DC))
538       return NestedNameSpecifier::GlobalSpecifier(Context);
539   }
540   llvm_unreachable("something isn't in TU scope?");
541 }
542 
543 /// Find the parent class with dependent bases of the innermost enclosing method
544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545 /// up allowing unqualified dependent type names at class-level, which MSVC
546 /// correctly rejects.
547 static const CXXRecordDecl *
548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552       if (MD->getParent()->hasAnyDependentBases())
553         return MD->getParent();
554   }
555   return nullptr;
556 }
557 
558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559                                           SourceLocation NameLoc,
560                                           bool IsTemplateTypeArg) {
561   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
562 
563   NestedNameSpecifier *NNS = nullptr;
564   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565     // If we weren't able to parse a default template argument, delay lookup
566     // until instantiation time by making a non-dependent DependentTypeName. We
567     // pretend we saw a NestedNameSpecifier referring to the current scope, and
568     // lookup is retried.
569     // FIXME: This hurts our diagnostic quality, since we get errors like "no
570     // type named 'Foo' in 'current_namespace'" when the user didn't write any
571     // name specifiers.
572     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574   } else if (const CXXRecordDecl *RD =
575                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576     // Build a DependentNameType that will perform lookup into RD at
577     // instantiation time.
578     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579                                       RD->getTypeForDecl());
580 
581     // Diagnose that this identifier was undeclared, and retry the lookup during
582     // template instantiation.
583     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584                                                                       << RD;
585   } else {
586     // This is not a situation that we should recover from.
587     return ParsedType();
588   }
589 
590   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591 
592   // Build type location information.  We synthesized the qualifier, so we have
593   // to build a fake NestedNameSpecifierLoc.
594   NestedNameSpecifierLocBuilder NNSLocBuilder;
595   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597 
598   TypeLocBuilder Builder;
599   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600   DepTL.setNameLoc(NameLoc);
601   DepTL.setElaboratedKeywordLoc(SourceLocation());
602   DepTL.setQualifierLoc(QualifierLoc);
603   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604 }
605 
606 /// isTagName() - This method is called *for error recovery purposes only*
607 /// to determine if the specified name is a valid tag name ("struct foo").  If
608 /// so, this returns the TST for the tag corresponding to it (TST_enum,
609 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
610 /// cases in C where the user forgot to specify the tag.
611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612   // Do a tag name lookup in this scope.
613   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614   LookupName(R, S, false);
615   R.suppressDiagnostics();
616   if (R.getResultKind() == LookupResult::Found)
617     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618       switch (TD->getTagKind()) {
619       case TTK_Struct: return DeclSpec::TST_struct;
620       case TTK_Interface: return DeclSpec::TST_interface;
621       case TTK_Union:  return DeclSpec::TST_union;
622       case TTK_Class:  return DeclSpec::TST_class;
623       case TTK_Enum:   return DeclSpec::TST_enum;
624       }
625     }
626 
627   return DeclSpec::TST_unspecified;
628 }
629 
630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
632 /// then downgrade the missing typename error to a warning.
633 /// This is needed for MSVC compatibility; Example:
634 /// @code
635 /// template<class T> class A {
636 /// public:
637 ///   typedef int TYPE;
638 /// };
639 /// template<class T> class B : public A<T> {
640 /// public:
641 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
642 /// };
643 /// @endcode
644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645   if (CurContext->isRecord()) {
646     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647       return true;
648 
649     const Type *Ty = SS->getScopeRep()->getAsType();
650 
651     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652     for (const auto &Base : RD->bases())
653       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654         return true;
655     return S->isFunctionPrototypeScope();
656   }
657   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658 }
659 
660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661                                    SourceLocation IILoc,
662                                    Scope *S,
663                                    CXXScopeSpec *SS,
664                                    ParsedType &SuggestedType,
665                                    bool IsTemplateName) {
666   // Don't report typename errors for editor placeholders.
667   if (II->isEditorPlaceholder())
668     return;
669   // We don't have anything to suggest (yet).
670   SuggestedType = nullptr;
671 
672   // There may have been a typo in the name of the type. Look up typo
673   // results, in case we have something that we can suggest.
674   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675                            /*AllowTemplates=*/IsTemplateName,
676                            /*AllowNonTemplates=*/!IsTemplateName);
677   if (TypoCorrection Corrected =
678           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679                       CCC, CTK_ErrorRecovery)) {
680     // FIXME: Support error recovery for the template-name case.
681     bool CanRecover = !IsTemplateName;
682     if (Corrected.isKeyword()) {
683       // We corrected to a keyword.
684       diagnoseTypo(Corrected,
685                    PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                         : diag::err_unknown_typename_suggest)
687                        << II);
688       II = Corrected.getCorrectionAsIdentifierInfo();
689     } else {
690       // We found a similarly-named type or interface; suggest that.
691       if (!SS || !SS->isSet()) {
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName ? diag::err_no_template_suggest
694                                           : diag::err_unknown_typename_suggest)
695                          << II, CanRecover);
696       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699                                 II->getName().equals(CorrectedStr);
700         diagnoseTypo(Corrected,
701                      PDiag(IsTemplateName
702                                ? diag::err_no_member_template_suggest
703                                : diag::err_unknown_nested_typename_suggest)
704                          << II << DC << DroppedSpecifier << SS->getRange(),
705                      CanRecover);
706       } else {
707         llvm_unreachable("could not have corrected a typo here");
708       }
709 
710       if (!CanRecover)
711         return;
712 
713       CXXScopeSpec tmpSS;
714       if (Corrected.getCorrectionSpecifier())
715         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716                           SourceRange(IILoc));
717       // FIXME: Support class template argument deduction here.
718       SuggestedType =
719           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721                       /*IsCtorOrDtorName=*/false,
722                       /*WantNontrivialTypeSourceInfo=*/true);
723     }
724     return;
725   }
726 
727   if (getLangOpts().CPlusPlus && !IsTemplateName) {
728     // See if II is a class template that the user forgot to pass arguments to.
729     UnqualifiedId Name;
730     Name.setIdentifier(II, IILoc);
731     CXXScopeSpec EmptySS;
732     TemplateTy TemplateResult;
733     bool MemberOfUnknownSpecialization;
734     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735                        Name, nullptr, true, TemplateResult,
736                        MemberOfUnknownSpecialization) == TNK_Type_template) {
737       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738       return;
739     }
740   }
741 
742   // FIXME: Should we move the logic that tries to recover from a missing tag
743   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744 
745   if (!SS || (!SS->isSet() && !SS->isInvalid()))
746     Diag(IILoc, IsTemplateName ? diag::err_no_template
747                                : diag::err_unknown_typename)
748         << II;
749   else if (DeclContext *DC = computeDeclContext(*SS, false))
750     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751                                : diag::err_typename_nested_not_found)
752         << II << DC << SS->getRange();
753   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754     SuggestedType =
755         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756   } else if (isDependentScopeSpecifier(*SS)) {
757     unsigned DiagID = diag::err_typename_missing;
758     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759       DiagID = diag::ext_typename_missing;
760 
761     Diag(SS->getRange().getBegin(), DiagID)
762       << SS->getScopeRep() << II->getName()
763       << SourceRange(SS->getRange().getBegin(), IILoc)
764       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765     SuggestedType = ActOnTypenameType(S, SourceLocation(),
766                                       *SS, *II, IILoc).get();
767   } else {
768     assert(SS && SS->isInvalid() &&
769            "Invalid scope specifier has already been diagnosed");
770   }
771 }
772 
773 /// Determine whether the given result set contains either a type name
774 /// or
775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777                        NextToken.is(tok::less);
778 
779   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781       return true;
782 
783     if (CheckTemplate && isa<TemplateDecl>(*I))
784       return true;
785   }
786 
787   return false;
788 }
789 
790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791                                     Scope *S, CXXScopeSpec &SS,
792                                     IdentifierInfo *&Name,
793                                     SourceLocation NameLoc) {
794   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795   SemaRef.LookupParsedName(R, S, &SS);
796   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797     StringRef FixItTagName;
798     switch (Tag->getTagKind()) {
799       case TTK_Class:
800         FixItTagName = "class ";
801         break;
802 
803       case TTK_Enum:
804         FixItTagName = "enum ";
805         break;
806 
807       case TTK_Struct:
808         FixItTagName = "struct ";
809         break;
810 
811       case TTK_Interface:
812         FixItTagName = "__interface ";
813         break;
814 
815       case TTK_Union:
816         FixItTagName = "union ";
817         break;
818     }
819 
820     StringRef TagName = FixItTagName.drop_back();
821     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824 
825     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826          I != IEnd; ++I)
827       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828         << Name << TagName;
829 
830     // Replace lookup results with just the tag decl.
831     Result.clear(Sema::LookupTagName);
832     SemaRef.LookupParsedName(Result, S, &SS);
833     return true;
834   }
835 
836   return false;
837 }
838 
839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841                                   QualType T, SourceLocation NameLoc) {
842   ASTContext &Context = S.Context;
843 
844   TypeLocBuilder Builder;
845   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846 
847   T = S.getElaboratedType(ETK_None, SS, T);
848   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849   ElabTL.setElaboratedKeywordLoc(SourceLocation());
850   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852 }
853 
854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855                                             IdentifierInfo *&Name,
856                                             SourceLocation NameLoc,
857                                             const Token &NextToken,
858                                             CorrectionCandidateCallback *CCC) {
859   DeclarationNameInfo NameInfo(Name, NameLoc);
860   ObjCMethodDecl *CurMethod = getCurMethodDecl();
861 
862   assert(NextToken.isNot(tok::coloncolon) &&
863          "parse nested name specifiers before calling ClassifyName");
864   if (getLangOpts().CPlusPlus && SS.isSet() &&
865       isCurrentClassName(*Name, S, &SS)) {
866     // Per [class.qual]p2, this names the constructors of SS, not the
867     // injected-class-name. We don't have a classification for that.
868     // There's not much point caching this result, since the parser
869     // will reject it later.
870     return NameClassification::Unknown();
871   }
872 
873   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874   LookupParsedName(Result, S, &SS, !CurMethod);
875 
876   if (SS.isInvalid())
877     return NameClassification::Error();
878 
879   // For unqualified lookup in a class template in MSVC mode, look into
880   // dependent base classes where the primary class template is known.
881   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882     if (ParsedType TypeInBase =
883             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884       return TypeInBase;
885   }
886 
887   // Perform lookup for Objective-C instance variables (including automatically
888   // synthesized instance variables), if we're in an Objective-C method.
889   // FIXME: This lookup really, really needs to be folded in to the normal
890   // unqualified lookup mechanism.
891   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893     if (Ivar.isInvalid())
894       return NameClassification::Error();
895     if (Ivar.isUsable())
896       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897 
898     // We defer builtin creation until after ivar lookup inside ObjC methods.
899     if (Result.empty())
900       LookupBuiltin(Result);
901   }
902 
903   bool SecondTry = false;
904   bool IsFilteredTemplateName = false;
905 
906 Corrected:
907   switch (Result.getResultKind()) {
908   case LookupResult::NotFound:
909     // If an unqualified-id is followed by a '(', then we have a function
910     // call.
911     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912       // In C++, this is an ADL-only call.
913       // FIXME: Reference?
914       if (getLangOpts().CPlusPlus)
915         return NameClassification::UndeclaredNonType();
916 
917       // C90 6.3.2.2:
918       //   If the expression that precedes the parenthesized argument list in a
919       //   function call consists solely of an identifier, and if no
920       //   declaration is visible for this identifier, the identifier is
921       //   implicitly declared exactly as if, in the innermost block containing
922       //   the function call, the declaration
923       //
924       //     extern int identifier ();
925       //
926       //   appeared.
927       //
928       // We also allow this in C99 as an extension.
929       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930         return NameClassification::NonType(D);
931     }
932 
933     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934       // In C++20 onwards, this could be an ADL-only call to a function
935       // template, and we're required to assume that this is a template name.
936       //
937       // FIXME: Find a way to still do typo correction in this case.
938       TemplateName Template =
939           Context.getAssumedTemplateName(NameInfo.getName());
940       return NameClassification::UndeclaredTemplate(Template);
941     }
942 
943     // In C, we first see whether there is a tag type by the same name, in
944     // which case it's likely that the user just forgot to write "enum",
945     // "struct", or "union".
946     if (!getLangOpts().CPlusPlus && !SecondTry &&
947         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948       break;
949     }
950 
951     // Perform typo correction to determine if there is another name that is
952     // close to this name.
953     if (!SecondTry && CCC) {
954       SecondTry = true;
955       if (TypoCorrection Corrected =
956               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957                           &SS, *CCC, CTK_ErrorRecovery)) {
958         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959         unsigned QualifiedDiag = diag::err_no_member_suggest;
960 
961         NamedDecl *FirstDecl = Corrected.getFoundDecl();
962         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965           UnqualifiedDiag = diag::err_no_template_suggest;
966           QualifiedDiag = diag::err_no_member_template_suggest;
967         } else if (UnderlyingFirstDecl &&
968                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
969                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971           UnqualifiedDiag = diag::err_unknown_typename_suggest;
972           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973         }
974 
975         if (SS.isEmpty()) {
976           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977         } else {// FIXME: is this even reachable? Test it.
978           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980                                   Name->getName().equals(CorrectedStr);
981           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982                                     << Name << computeDeclContext(SS, false)
983                                     << DroppedSpecifier << SS.getRange());
984         }
985 
986         // Update the name, so that the caller has the new name.
987         Name = Corrected.getCorrectionAsIdentifierInfo();
988 
989         // Typo correction corrected to a keyword.
990         if (Corrected.isKeyword())
991           return Name;
992 
993         // Also update the LookupResult...
994         // FIXME: This should probably go away at some point
995         Result.clear();
996         Result.setLookupName(Corrected.getCorrection());
997         if (FirstDecl)
998           Result.addDecl(FirstDecl);
999 
1000         // If we found an Objective-C instance variable, let
1001         // LookupInObjCMethod build the appropriate expression to
1002         // reference the ivar.
1003         // FIXME: This is a gross hack.
1004         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005           DeclResult R =
1006               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007           if (R.isInvalid())
1008             return NameClassification::Error();
1009           if (R.isUsable())
1010             return NameClassification::NonType(Ivar);
1011         }
1012 
1013         goto Corrected;
1014       }
1015     }
1016 
1017     // We failed to correct; just fall through and let the parser deal with it.
1018     Result.suppressDiagnostics();
1019     return NameClassification::Unknown();
1020 
1021   case LookupResult::NotFoundInCurrentInstantiation: {
1022     // We performed name lookup into the current instantiation, and there were
1023     // dependent bases, so we treat this result the same way as any other
1024     // dependent nested-name-specifier.
1025 
1026     // C++ [temp.res]p2:
1027     //   A name used in a template declaration or definition and that is
1028     //   dependent on a template-parameter is assumed not to name a type
1029     //   unless the applicable name lookup finds a type name or the name is
1030     //   qualified by the keyword typename.
1031     //
1032     // FIXME: If the next token is '<', we might want to ask the parser to
1033     // perform some heroics to see if we actually have a
1034     // template-argument-list, which would indicate a missing 'template'
1035     // keyword here.
1036     return NameClassification::DependentNonType();
1037   }
1038 
1039   case LookupResult::Found:
1040   case LookupResult::FoundOverloaded:
1041   case LookupResult::FoundUnresolvedValue:
1042     break;
1043 
1044   case LookupResult::Ambiguous:
1045     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                       /*AllowDependent=*/false)) {
1048       // C++ [temp.local]p3:
1049       //   A lookup that finds an injected-class-name (10.2) can result in an
1050       //   ambiguity in certain cases (for example, if it is found in more than
1051       //   one base class). If all of the injected-class-names that are found
1052       //   refer to specializations of the same class template, and if the name
1053       //   is followed by a template-argument-list, the reference refers to the
1054       //   class template itself and not a specialization thereof, and is not
1055       //   ambiguous.
1056       //
1057       // This filtering can make an ambiguous result into an unambiguous one,
1058       // so try again after filtering out template names.
1059       FilterAcceptableTemplateNames(Result);
1060       if (!Result.isAmbiguous()) {
1061         IsFilteredTemplateName = true;
1062         break;
1063       }
1064     }
1065 
1066     // Diagnose the ambiguity and return an error.
1067     return NameClassification::Error();
1068   }
1069 
1070   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071       (IsFilteredTemplateName ||
1072        hasAnyAcceptableTemplateNames(
1073            Result, /*AllowFunctionTemplates=*/true,
1074            /*AllowDependent=*/false,
1075            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076                getLangOpts().CPlusPlus20))) {
1077     // C++ [temp.names]p3:
1078     //   After name lookup (3.4) finds that a name is a template-name or that
1079     //   an operator-function-id or a literal- operator-id refers to a set of
1080     //   overloaded functions any member of which is a function template if
1081     //   this is followed by a <, the < is always taken as the delimiter of a
1082     //   template-argument-list and never as the less-than operator.
1083     // C++2a [temp.names]p2:
1084     //   A name is also considered to refer to a template if it is an
1085     //   unqualified-id followed by a < and name lookup finds either one
1086     //   or more functions or finds nothing.
1087     if (!IsFilteredTemplateName)
1088       FilterAcceptableTemplateNames(Result);
1089 
1090     bool IsFunctionTemplate;
1091     bool IsVarTemplate;
1092     TemplateName Template;
1093     if (Result.end() - Result.begin() > 1) {
1094       IsFunctionTemplate = true;
1095       Template = Context.getOverloadedTemplateName(Result.begin(),
1096                                                    Result.end());
1097     } else if (!Result.empty()) {
1098       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099           *Result.begin(), /*AllowFunctionTemplates=*/true,
1100           /*AllowDependent=*/false));
1101       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102       IsVarTemplate = isa<VarTemplateDecl>(TD);
1103 
1104       if (SS.isNotEmpty())
1105         Template =
1106             Context.getQualifiedTemplateName(SS.getScopeRep(),
1107                                              /*TemplateKeyword=*/false, TD);
1108       else
1109         Template = TemplateName(TD);
1110     } else {
1111       // All results were non-template functions. This is a function template
1112       // name.
1113       IsFunctionTemplate = true;
1114       Template = Context.getAssumedTemplateName(NameInfo.getName());
1115     }
1116 
1117     if (IsFunctionTemplate) {
1118       // Function templates always go through overload resolution, at which
1119       // point we'll perform the various checks (e.g., accessibility) we need
1120       // to based on which function we selected.
1121       Result.suppressDiagnostics();
1122 
1123       return NameClassification::FunctionTemplate(Template);
1124     }
1125 
1126     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127                          : NameClassification::TypeTemplate(Template);
1128   }
1129 
1130   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132     DiagnoseUseOfDecl(Type, NameLoc);
1133     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134     QualType T = Context.getTypeDeclType(Type);
1135     if (SS.isNotEmpty())
1136       return buildNestedType(*this, SS, T, NameLoc);
1137     return ParsedType::make(T);
1138   }
1139 
1140   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141   if (!Class) {
1142     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143     if (ObjCCompatibleAliasDecl *Alias =
1144             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145       Class = Alias->getClassInterface();
1146   }
1147 
1148   if (Class) {
1149     DiagnoseUseOfDecl(Class, NameLoc);
1150 
1151     if (NextToken.is(tok::period)) {
1152       // Interface. <something> is parsed as a property reference expression.
1153       // Just return "unknown" as a fall-through for now.
1154       Result.suppressDiagnostics();
1155       return NameClassification::Unknown();
1156     }
1157 
1158     QualType T = Context.getObjCInterfaceType(Class);
1159     return ParsedType::make(T);
1160   }
1161 
1162   if (isa<ConceptDecl>(FirstDecl))
1163     return NameClassification::Concept(
1164         TemplateName(cast<TemplateDecl>(FirstDecl)));
1165 
1166   // We can have a type template here if we're classifying a template argument.
1167   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168       !isa<VarTemplateDecl>(FirstDecl))
1169     return NameClassification::TypeTemplate(
1170         TemplateName(cast<TemplateDecl>(FirstDecl)));
1171 
1172   // Check for a tag type hidden by a non-type decl in a few cases where it
1173   // seems likely a type is wanted instead of the non-type that was found.
1174   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175   if ((NextToken.is(tok::identifier) ||
1176        (NextIsOp &&
1177         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180     DiagnoseUseOfDecl(Type, NameLoc);
1181     QualType T = Context.getTypeDeclType(Type);
1182     if (SS.isNotEmpty())
1183       return buildNestedType(*this, SS, T, NameLoc);
1184     return ParsedType::make(T);
1185   }
1186 
1187   // If we already know which single declaration is referenced, just annotate
1188   // that declaration directly. Defer resolving even non-overloaded class
1189   // member accesses, as we need to defer certain access checks until we know
1190   // the context.
1191   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1193     return NameClassification::NonType(Result.getRepresentativeDecl());
1194 
1195   // Otherwise, this is an overload set that we will need to resolve later.
1196   Result.suppressDiagnostics();
1197   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1198       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1199       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1200       Result.begin(), Result.end()));
1201 }
1202 
1203 ExprResult
1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1205                                              SourceLocation NameLoc) {
1206   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1207   CXXScopeSpec SS;
1208   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1209   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1210 }
1211 
1212 ExprResult
1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1214                                             IdentifierInfo *Name,
1215                                             SourceLocation NameLoc,
1216                                             bool IsAddressOfOperand) {
1217   DeclarationNameInfo NameInfo(Name, NameLoc);
1218   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1219                                     NameInfo, IsAddressOfOperand,
1220                                     /*TemplateArgs=*/nullptr);
1221 }
1222 
1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1224                                               NamedDecl *Found,
1225                                               SourceLocation NameLoc,
1226                                               const Token &NextToken) {
1227   if (getCurMethodDecl() && SS.isEmpty())
1228     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1229       return BuildIvarRefExpr(S, NameLoc, Ivar);
1230 
1231   // Reconstruct the lookup result.
1232   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1233   Result.addDecl(Found);
1234   Result.resolveKind();
1235 
1236   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237   return BuildDeclarationNameExpr(SS, Result, ADL);
1238 }
1239 
1240 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1241   // For an implicit class member access, transform the result into a member
1242   // access expression if necessary.
1243   auto *ULE = cast<UnresolvedLookupExpr>(E);
1244   if ((*ULE->decls_begin())->isCXXClassMember()) {
1245     CXXScopeSpec SS;
1246     SS.Adopt(ULE->getQualifierLoc());
1247 
1248     // Reconstruct the lookup result.
1249     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1250                         LookupOrdinaryName);
1251     Result.setNamingClass(ULE->getNamingClass());
1252     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1253       Result.addDecl(*I, I.getAccess());
1254     Result.resolveKind();
1255     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1256                                            nullptr, S);
1257   }
1258 
1259   // Otherwise, this is already in the form we needed, and no further checks
1260   // are necessary.
1261   return ULE;
1262 }
1263 
1264 Sema::TemplateNameKindForDiagnostics
1265 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1266   auto *TD = Name.getAsTemplateDecl();
1267   if (!TD)
1268     return TemplateNameKindForDiagnostics::DependentTemplate;
1269   if (isa<ClassTemplateDecl>(TD))
1270     return TemplateNameKindForDiagnostics::ClassTemplate;
1271   if (isa<FunctionTemplateDecl>(TD))
1272     return TemplateNameKindForDiagnostics::FunctionTemplate;
1273   if (isa<VarTemplateDecl>(TD))
1274     return TemplateNameKindForDiagnostics::VarTemplate;
1275   if (isa<TypeAliasTemplateDecl>(TD))
1276     return TemplateNameKindForDiagnostics::AliasTemplate;
1277   if (isa<TemplateTemplateParmDecl>(TD))
1278     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1279   if (isa<ConceptDecl>(TD))
1280     return TemplateNameKindForDiagnostics::Concept;
1281   return TemplateNameKindForDiagnostics::DependentTemplate;
1282 }
1283 
1284 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1285   assert(DC->getLexicalParent() == CurContext &&
1286       "The next DeclContext should be lexically contained in the current one.");
1287   CurContext = DC;
1288   S->setEntity(DC);
1289 }
1290 
1291 void Sema::PopDeclContext() {
1292   assert(CurContext && "DeclContext imbalance!");
1293 
1294   CurContext = CurContext->getLexicalParent();
1295   assert(CurContext && "Popped translation unit!");
1296 }
1297 
1298 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1299                                                                     Decl *D) {
1300   // Unlike PushDeclContext, the context to which we return is not necessarily
1301   // the containing DC of TD, because the new context will be some pre-existing
1302   // TagDecl definition instead of a fresh one.
1303   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1304   CurContext = cast<TagDecl>(D)->getDefinition();
1305   assert(CurContext && "skipping definition of undefined tag");
1306   // Start lookups from the parent of the current context; we don't want to look
1307   // into the pre-existing complete definition.
1308   S->setEntity(CurContext->getLookupParent());
1309   return Result;
1310 }
1311 
1312 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1313   CurContext = static_cast<decltype(CurContext)>(Context);
1314 }
1315 
1316 /// EnterDeclaratorContext - Used when we must lookup names in the context
1317 /// of a declarator's nested name specifier.
1318 ///
1319 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1320   // C++0x [basic.lookup.unqual]p13:
1321   //   A name used in the definition of a static data member of class
1322   //   X (after the qualified-id of the static member) is looked up as
1323   //   if the name was used in a member function of X.
1324   // C++0x [basic.lookup.unqual]p14:
1325   //   If a variable member of a namespace is defined outside of the
1326   //   scope of its namespace then any name used in the definition of
1327   //   the variable member (after the declarator-id) is looked up as
1328   //   if the definition of the variable member occurred in its
1329   //   namespace.
1330   // Both of these imply that we should push a scope whose context
1331   // is the semantic context of the declaration.  We can't use
1332   // PushDeclContext here because that context is not necessarily
1333   // lexically contained in the current context.  Fortunately,
1334   // the containing scope should have the appropriate information.
1335 
1336   assert(!S->getEntity() && "scope already has entity");
1337 
1338 #ifndef NDEBUG
1339   Scope *Ancestor = S->getParent();
1340   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1342 #endif
1343 
1344   CurContext = DC;
1345   S->setEntity(DC);
1346 
1347   if (S->getParent()->isTemplateParamScope()) {
1348     // Also set the corresponding entities for all immediately-enclosing
1349     // template parameter scopes.
1350     EnterTemplatedContext(S->getParent(), DC);
1351   }
1352 }
1353 
1354 void Sema::ExitDeclaratorContext(Scope *S) {
1355   assert(S->getEntity() == CurContext && "Context imbalance!");
1356 
1357   // Switch back to the lexical context.  The safety of this is
1358   // enforced by an assert in EnterDeclaratorContext.
1359   Scope *Ancestor = S->getParent();
1360   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361   CurContext = Ancestor->getEntity();
1362 
1363   // We don't need to do anything with the scope, which is going to
1364   // disappear.
1365 }
1366 
1367 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1368   assert(S->isTemplateParamScope() &&
1369          "expected to be initializing a template parameter scope");
1370 
1371   // C++20 [temp.local]p7:
1372   //   In the definition of a member of a class template that appears outside
1373   //   of the class template definition, the name of a member of the class
1374   //   template hides the name of a template-parameter of any enclosing class
1375   //   templates (but not a template-parameter of the member if the member is a
1376   //   class or function template).
1377   // C++20 [temp.local]p9:
1378   //   In the definition of a class template or in the definition of a member
1379   //   of such a template that appears outside of the template definition, for
1380   //   each non-dependent base class (13.8.2.1), if the name of the base class
1381   //   or the name of a member of the base class is the same as the name of a
1382   //   template-parameter, the base class name or member name hides the
1383   //   template-parameter name (6.4.10).
1384   //
1385   // This means that a template parameter scope should be searched immediately
1386   // after searching the DeclContext for which it is a template parameter
1387   // scope. For example, for
1388   //   template<typename T> template<typename U> template<typename V>
1389   //     void N::A<T>::B<U>::f(...)
1390   // we search V then B<U> (and base classes) then U then A<T> (and base
1391   // classes) then T then N then ::.
1392   unsigned ScopeDepth = getTemplateDepth(S);
1393   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1394     DeclContext *SearchDCAfterScope = DC;
1395     for (; DC; DC = DC->getLookupParent()) {
1396       if (const TemplateParameterList *TPL =
1397               cast<Decl>(DC)->getDescribedTemplateParams()) {
1398         unsigned DCDepth = TPL->getDepth() + 1;
1399         if (DCDepth > ScopeDepth)
1400           continue;
1401         if (ScopeDepth == DCDepth)
1402           SearchDCAfterScope = DC = DC->getLookupParent();
1403         break;
1404       }
1405     }
1406     S->setLookupEntity(SearchDCAfterScope);
1407   }
1408 }
1409 
1410 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1411   // We assume that the caller has already called
1412   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1413   FunctionDecl *FD = D->getAsFunction();
1414   if (!FD)
1415     return;
1416 
1417   // Same implementation as PushDeclContext, but enters the context
1418   // from the lexical parent, rather than the top-level class.
1419   assert(CurContext == FD->getLexicalParent() &&
1420     "The next DeclContext should be lexically contained in the current one.");
1421   CurContext = FD;
1422   S->setEntity(CurContext);
1423 
1424   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1425     ParmVarDecl *Param = FD->getParamDecl(P);
1426     // If the parameter has an identifier, then add it to the scope
1427     if (Param->getIdentifier()) {
1428       S->AddDecl(Param);
1429       IdResolver.AddDecl(Param);
1430     }
1431   }
1432 }
1433 
1434 void Sema::ActOnExitFunctionContext() {
1435   // Same implementation as PopDeclContext, but returns to the lexical parent,
1436   // rather than the top-level class.
1437   assert(CurContext && "DeclContext imbalance!");
1438   CurContext = CurContext->getLexicalParent();
1439   assert(CurContext && "Popped translation unit!");
1440 }
1441 
1442 /// Determine whether we allow overloading of the function
1443 /// PrevDecl with another declaration.
1444 ///
1445 /// This routine determines whether overloading is possible, not
1446 /// whether some new function is actually an overload. It will return
1447 /// true in C++ (where we can always provide overloads) or, as an
1448 /// extension, in C when the previous function is already an
1449 /// overloaded function declaration or has the "overloadable"
1450 /// attribute.
1451 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1452                                        ASTContext &Context,
1453                                        const FunctionDecl *New) {
1454   if (Context.getLangOpts().CPlusPlus)
1455     return true;
1456 
1457   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1458     return true;
1459 
1460   return Previous.getResultKind() == LookupResult::Found &&
1461          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1462           New->hasAttr<OverloadableAttr>());
1463 }
1464 
1465 /// Add this decl to the scope shadowed decl chains.
1466 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1467   // Move up the scope chain until we find the nearest enclosing
1468   // non-transparent context. The declaration will be introduced into this
1469   // scope.
1470   while (S->getEntity() && S->getEntity()->isTransparentContext())
1471     S = S->getParent();
1472 
1473   // Add scoped declarations into their context, so that they can be
1474   // found later. Declarations without a context won't be inserted
1475   // into any context.
1476   if (AddToContext)
1477     CurContext->addDecl(D);
1478 
1479   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1480   // are function-local declarations.
1481   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1482       !D->getDeclContext()->getRedeclContext()->Equals(
1483         D->getLexicalDeclContext()->getRedeclContext()) &&
1484       !D->getLexicalDeclContext()->isFunctionOrMethod())
1485     return;
1486 
1487   // Template instantiations should also not be pushed into scope.
1488   if (isa<FunctionDecl>(D) &&
1489       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1490     return;
1491 
1492   // If this replaces anything in the current scope,
1493   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1494                                IEnd = IdResolver.end();
1495   for (; I != IEnd; ++I) {
1496     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1497       S->RemoveDecl(*I);
1498       IdResolver.RemoveDecl(*I);
1499 
1500       // Should only need to replace one decl.
1501       break;
1502     }
1503   }
1504 
1505   S->AddDecl(D);
1506 
1507   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1508     // Implicitly-generated labels may end up getting generated in an order that
1509     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1510     // the label at the appropriate place in the identifier chain.
1511     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1512       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1513       if (IDC == CurContext) {
1514         if (!S->isDeclScope(*I))
1515           continue;
1516       } else if (IDC->Encloses(CurContext))
1517         break;
1518     }
1519 
1520     IdResolver.InsertDeclAfter(I, D);
1521   } else {
1522     IdResolver.AddDecl(D);
1523   }
1524 }
1525 
1526 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1527                          bool AllowInlineNamespace) {
1528   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1529 }
1530 
1531 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1532   DeclContext *TargetDC = DC->getPrimaryContext();
1533   do {
1534     if (DeclContext *ScopeDC = S->getEntity())
1535       if (ScopeDC->getPrimaryContext() == TargetDC)
1536         return S;
1537   } while ((S = S->getParent()));
1538 
1539   return nullptr;
1540 }
1541 
1542 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1543                                             DeclContext*,
1544                                             ASTContext&);
1545 
1546 /// Filters out lookup results that don't fall within the given scope
1547 /// as determined by isDeclInScope.
1548 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1549                                 bool ConsiderLinkage,
1550                                 bool AllowInlineNamespace) {
1551   LookupResult::Filter F = R.makeFilter();
1552   while (F.hasNext()) {
1553     NamedDecl *D = F.next();
1554 
1555     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1556       continue;
1557 
1558     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1559       continue;
1560 
1561     F.erase();
1562   }
1563 
1564   F.done();
1565 }
1566 
1567 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1568 /// have compatible owning modules.
1569 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1570   // FIXME: The Modules TS is not clear about how friend declarations are
1571   // to be treated. It's not meaningful to have different owning modules for
1572   // linkage in redeclarations of the same entity, so for now allow the
1573   // redeclaration and change the owning modules to match.
1574   if (New->getFriendObjectKind() &&
1575       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1576     New->setLocalOwningModule(Old->getOwningModule());
1577     makeMergedDefinitionVisible(New);
1578     return false;
1579   }
1580 
1581   Module *NewM = New->getOwningModule();
1582   Module *OldM = Old->getOwningModule();
1583 
1584   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1585     NewM = NewM->Parent;
1586   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1587     OldM = OldM->Parent;
1588 
1589   if (NewM == OldM)
1590     return false;
1591 
1592   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1593   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1594   if (NewIsModuleInterface || OldIsModuleInterface) {
1595     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1596     //   if a declaration of D [...] appears in the purview of a module, all
1597     //   other such declarations shall appear in the purview of the same module
1598     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1599       << New
1600       << NewIsModuleInterface
1601       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1602       << OldIsModuleInterface
1603       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1604     Diag(Old->getLocation(), diag::note_previous_declaration);
1605     New->setInvalidDecl();
1606     return true;
1607   }
1608 
1609   return false;
1610 }
1611 
1612 static bool isUsingDecl(NamedDecl *D) {
1613   return isa<UsingShadowDecl>(D) ||
1614          isa<UnresolvedUsingTypenameDecl>(D) ||
1615          isa<UnresolvedUsingValueDecl>(D);
1616 }
1617 
1618 /// Removes using shadow declarations from the lookup results.
1619 static void RemoveUsingDecls(LookupResult &R) {
1620   LookupResult::Filter F = R.makeFilter();
1621   while (F.hasNext())
1622     if (isUsingDecl(F.next()))
1623       F.erase();
1624 
1625   F.done();
1626 }
1627 
1628 /// Check for this common pattern:
1629 /// @code
1630 /// class S {
1631 ///   S(const S&); // DO NOT IMPLEMENT
1632 ///   void operator=(const S&); // DO NOT IMPLEMENT
1633 /// };
1634 /// @endcode
1635 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1636   // FIXME: Should check for private access too but access is set after we get
1637   // the decl here.
1638   if (D->doesThisDeclarationHaveABody())
1639     return false;
1640 
1641   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1642     return CD->isCopyConstructor();
1643   return D->isCopyAssignmentOperator();
1644 }
1645 
1646 // We need this to handle
1647 //
1648 // typedef struct {
1649 //   void *foo() { return 0; }
1650 // } A;
1651 //
1652 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1653 // for example. If 'A', foo will have external linkage. If we have '*A',
1654 // foo will have no linkage. Since we can't know until we get to the end
1655 // of the typedef, this function finds out if D might have non-external linkage.
1656 // Callers should verify at the end of the TU if it D has external linkage or
1657 // not.
1658 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1659   const DeclContext *DC = D->getDeclContext();
1660   while (!DC->isTranslationUnit()) {
1661     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1662       if (!RD->hasNameForLinkage())
1663         return true;
1664     }
1665     DC = DC->getParent();
1666   }
1667 
1668   return !D->isExternallyVisible();
1669 }
1670 
1671 // FIXME: This needs to be refactored; some other isInMainFile users want
1672 // these semantics.
1673 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1674   if (S.TUKind != TU_Complete)
1675     return false;
1676   return S.SourceMgr.isInMainFile(Loc);
1677 }
1678 
1679 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1680   assert(D);
1681 
1682   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1683     return false;
1684 
1685   // Ignore all entities declared within templates, and out-of-line definitions
1686   // of members of class templates.
1687   if (D->getDeclContext()->isDependentContext() ||
1688       D->getLexicalDeclContext()->isDependentContext())
1689     return false;
1690 
1691   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1692     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1693       return false;
1694     // A non-out-of-line declaration of a member specialization was implicitly
1695     // instantiated; it's the out-of-line declaration that we're interested in.
1696     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1697         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1698       return false;
1699 
1700     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1701       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1702         return false;
1703     } else {
1704       // 'static inline' functions are defined in headers; don't warn.
1705       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1706         return false;
1707     }
1708 
1709     if (FD->doesThisDeclarationHaveABody() &&
1710         Context.DeclMustBeEmitted(FD))
1711       return false;
1712   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713     // Constants and utility variables are defined in headers with internal
1714     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1715     // like "inline".)
1716     if (!isMainFileLoc(*this, VD->getLocation()))
1717       return false;
1718 
1719     if (Context.DeclMustBeEmitted(VD))
1720       return false;
1721 
1722     if (VD->isStaticDataMember() &&
1723         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1724       return false;
1725     if (VD->isStaticDataMember() &&
1726         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1727         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1728       return false;
1729 
1730     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1731       return false;
1732   } else {
1733     return false;
1734   }
1735 
1736   // Only warn for unused decls internal to the translation unit.
1737   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1738   // for inline functions defined in the main source file, for instance.
1739   return mightHaveNonExternalLinkage(D);
1740 }
1741 
1742 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1743   if (!D)
1744     return;
1745 
1746   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1747     const FunctionDecl *First = FD->getFirstDecl();
1748     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1749       return; // First should already be in the vector.
1750   }
1751 
1752   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753     const VarDecl *First = VD->getFirstDecl();
1754     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1755       return; // First should already be in the vector.
1756   }
1757 
1758   if (ShouldWarnIfUnusedFileScopedDecl(D))
1759     UnusedFileScopedDecls.push_back(D);
1760 }
1761 
1762 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1763   if (D->isInvalidDecl())
1764     return false;
1765 
1766   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1767     // For a decomposition declaration, warn if none of the bindings are
1768     // referenced, instead of if the variable itself is referenced (which
1769     // it is, by the bindings' expressions).
1770     for (auto *BD : DD->bindings())
1771       if (BD->isReferenced())
1772         return false;
1773   } else if (!D->getDeclName()) {
1774     return false;
1775   } else if (D->isReferenced() || D->isUsed()) {
1776     return false;
1777   }
1778 
1779   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1780     return false;
1781 
1782   if (isa<LabelDecl>(D))
1783     return true;
1784 
1785   // Except for labels, we only care about unused decls that are local to
1786   // functions.
1787   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1788   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1789     // For dependent types, the diagnostic is deferred.
1790     WithinFunction =
1791         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1792   if (!WithinFunction)
1793     return false;
1794 
1795   if (isa<TypedefNameDecl>(D))
1796     return true;
1797 
1798   // White-list anything that isn't a local variable.
1799   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1800     return false;
1801 
1802   // Types of valid local variables should be complete, so this should succeed.
1803   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1804 
1805     // White-list anything with an __attribute__((unused)) type.
1806     const auto *Ty = VD->getType().getTypePtr();
1807 
1808     // Only look at the outermost level of typedef.
1809     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1810       if (TT->getDecl()->hasAttr<UnusedAttr>())
1811         return false;
1812     }
1813 
1814     // If we failed to complete the type for some reason, or if the type is
1815     // dependent, don't diagnose the variable.
1816     if (Ty->isIncompleteType() || Ty->isDependentType())
1817       return false;
1818 
1819     // Look at the element type to ensure that the warning behaviour is
1820     // consistent for both scalars and arrays.
1821     Ty = Ty->getBaseElementTypeUnsafe();
1822 
1823     if (const TagType *TT = Ty->getAs<TagType>()) {
1824       const TagDecl *Tag = TT->getDecl();
1825       if (Tag->hasAttr<UnusedAttr>())
1826         return false;
1827 
1828       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1829         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1830           return false;
1831 
1832         if (const Expr *Init = VD->getInit()) {
1833           if (const ExprWithCleanups *Cleanups =
1834                   dyn_cast<ExprWithCleanups>(Init))
1835             Init = Cleanups->getSubExpr();
1836           const CXXConstructExpr *Construct =
1837             dyn_cast<CXXConstructExpr>(Init);
1838           if (Construct && !Construct->isElidable()) {
1839             CXXConstructorDecl *CD = Construct->getConstructor();
1840             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1841                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1842               return false;
1843           }
1844 
1845           // Suppress the warning if we don't know how this is constructed, and
1846           // it could possibly be non-trivial constructor.
1847           if (Init->isTypeDependent())
1848             for (const CXXConstructorDecl *Ctor : RD->ctors())
1849               if (!Ctor->isTrivial())
1850                 return false;
1851         }
1852       }
1853     }
1854 
1855     // TODO: __attribute__((unused)) templates?
1856   }
1857 
1858   return true;
1859 }
1860 
1861 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1862                                      FixItHint &Hint) {
1863   if (isa<LabelDecl>(D)) {
1864     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1865         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1866         true);
1867     if (AfterColon.isInvalid())
1868       return;
1869     Hint = FixItHint::CreateRemoval(
1870         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1871   }
1872 }
1873 
1874 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1875   if (D->getTypeForDecl()->isDependentType())
1876     return;
1877 
1878   for (auto *TmpD : D->decls()) {
1879     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1880       DiagnoseUnusedDecl(T);
1881     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1882       DiagnoseUnusedNestedTypedefs(R);
1883   }
1884 }
1885 
1886 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1887 /// unless they are marked attr(unused).
1888 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1889   if (!ShouldDiagnoseUnusedDecl(D))
1890     return;
1891 
1892   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1893     // typedefs can be referenced later on, so the diagnostics are emitted
1894     // at end-of-translation-unit.
1895     UnusedLocalTypedefNameCandidates.insert(TD);
1896     return;
1897   }
1898 
1899   FixItHint Hint;
1900   GenerateFixForUnusedDecl(D, Context, Hint);
1901 
1902   unsigned DiagID;
1903   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1904     DiagID = diag::warn_unused_exception_param;
1905   else if (isa<LabelDecl>(D))
1906     DiagID = diag::warn_unused_label;
1907   else
1908     DiagID = diag::warn_unused_variable;
1909 
1910   Diag(D->getLocation(), DiagID) << D << Hint;
1911 }
1912 
1913 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1914   // Verify that we have no forward references left.  If so, there was a goto
1915   // or address of a label taken, but no definition of it.  Label fwd
1916   // definitions are indicated with a null substmt which is also not a resolved
1917   // MS inline assembly label name.
1918   bool Diagnose = false;
1919   if (L->isMSAsmLabel())
1920     Diagnose = !L->isResolvedMSAsmLabel();
1921   else
1922     Diagnose = L->getStmt() == nullptr;
1923   if (Diagnose)
1924     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1925 }
1926 
1927 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1928   S->mergeNRVOIntoParent();
1929 
1930   if (S->decl_empty()) return;
1931   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1932          "Scope shouldn't contain decls!");
1933 
1934   for (auto *TmpD : S->decls()) {
1935     assert(TmpD && "This decl didn't get pushed??");
1936 
1937     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1938     NamedDecl *D = cast<NamedDecl>(TmpD);
1939 
1940     // Diagnose unused variables in this scope.
1941     if (!S->hasUnrecoverableErrorOccurred()) {
1942       DiagnoseUnusedDecl(D);
1943       if (const auto *RD = dyn_cast<RecordDecl>(D))
1944         DiagnoseUnusedNestedTypedefs(RD);
1945     }
1946 
1947     if (!D->getDeclName()) continue;
1948 
1949     // If this was a forward reference to a label, verify it was defined.
1950     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1951       CheckPoppedLabel(LD, *this);
1952 
1953     // Remove this name from our lexical scope, and warn on it if we haven't
1954     // already.
1955     IdResolver.RemoveDecl(D);
1956     auto ShadowI = ShadowingDecls.find(D);
1957     if (ShadowI != ShadowingDecls.end()) {
1958       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1959         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1960             << D << FD << FD->getParent();
1961         Diag(FD->getLocation(), diag::note_previous_declaration);
1962       }
1963       ShadowingDecls.erase(ShadowI);
1964     }
1965   }
1966 }
1967 
1968 /// Look for an Objective-C class in the translation unit.
1969 ///
1970 /// \param Id The name of the Objective-C class we're looking for. If
1971 /// typo-correction fixes this name, the Id will be updated
1972 /// to the fixed name.
1973 ///
1974 /// \param IdLoc The location of the name in the translation unit.
1975 ///
1976 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1977 /// if there is no class with the given name.
1978 ///
1979 /// \returns The declaration of the named Objective-C class, or NULL if the
1980 /// class could not be found.
1981 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1982                                               SourceLocation IdLoc,
1983                                               bool DoTypoCorrection) {
1984   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1985   // creation from this context.
1986   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1987 
1988   if (!IDecl && DoTypoCorrection) {
1989     // Perform typo correction at the given location, but only if we
1990     // find an Objective-C class name.
1991     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1992     if (TypoCorrection C =
1993             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1994                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1995       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1996       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1997       Id = IDecl->getIdentifier();
1998     }
1999   }
2000   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2001   // This routine must always return a class definition, if any.
2002   if (Def && Def->getDefinition())
2003       Def = Def->getDefinition();
2004   return Def;
2005 }
2006 
2007 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2008 /// from S, where a non-field would be declared. This routine copes
2009 /// with the difference between C and C++ scoping rules in structs and
2010 /// unions. For example, the following code is well-formed in C but
2011 /// ill-formed in C++:
2012 /// @code
2013 /// struct S6 {
2014 ///   enum { BAR } e;
2015 /// };
2016 ///
2017 /// void test_S6() {
2018 ///   struct S6 a;
2019 ///   a.e = BAR;
2020 /// }
2021 /// @endcode
2022 /// For the declaration of BAR, this routine will return a different
2023 /// scope. The scope S will be the scope of the unnamed enumeration
2024 /// within S6. In C++, this routine will return the scope associated
2025 /// with S6, because the enumeration's scope is a transparent
2026 /// context but structures can contain non-field names. In C, this
2027 /// routine will return the translation unit scope, since the
2028 /// enumeration's scope is a transparent context and structures cannot
2029 /// contain non-field names.
2030 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2031   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2032          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2033          (S->isClassScope() && !getLangOpts().CPlusPlus))
2034     S = S->getParent();
2035   return S;
2036 }
2037 
2038 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2039                                ASTContext::GetBuiltinTypeError Error) {
2040   switch (Error) {
2041   case ASTContext::GE_None:
2042     return "";
2043   case ASTContext::GE_Missing_type:
2044     return BuiltinInfo.getHeaderName(ID);
2045   case ASTContext::GE_Missing_stdio:
2046     return "stdio.h";
2047   case ASTContext::GE_Missing_setjmp:
2048     return "setjmp.h";
2049   case ASTContext::GE_Missing_ucontext:
2050     return "ucontext.h";
2051   }
2052   llvm_unreachable("unhandled error kind");
2053 }
2054 
2055 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2056                                   unsigned ID, SourceLocation Loc) {
2057   DeclContext *Parent = Context.getTranslationUnitDecl();
2058 
2059   if (getLangOpts().CPlusPlus) {
2060     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2061         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2062     CLinkageDecl->setImplicit();
2063     Parent->addDecl(CLinkageDecl);
2064     Parent = CLinkageDecl;
2065   }
2066 
2067   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2068                                            /*TInfo=*/nullptr, SC_Extern, false,
2069                                            Type->isFunctionProtoType());
2070   New->setImplicit();
2071   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2072 
2073   // Create Decl objects for each parameter, adding them to the
2074   // FunctionDecl.
2075   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2076     SmallVector<ParmVarDecl *, 16> Params;
2077     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2078       ParmVarDecl *parm = ParmVarDecl::Create(
2079           Context, New, SourceLocation(), SourceLocation(), nullptr,
2080           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2081       parm->setScopeInfo(0, i);
2082       Params.push_back(parm);
2083     }
2084     New->setParams(Params);
2085   }
2086 
2087   AddKnownFunctionAttributes(New);
2088   return New;
2089 }
2090 
2091 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2092 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2093 /// if we're creating this built-in in anticipation of redeclaring the
2094 /// built-in.
2095 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2096                                      Scope *S, bool ForRedeclaration,
2097                                      SourceLocation Loc) {
2098   LookupNecessaryTypesForBuiltin(S, ID);
2099 
2100   ASTContext::GetBuiltinTypeError Error;
2101   QualType R = Context.GetBuiltinType(ID, Error);
2102   if (Error) {
2103     if (!ForRedeclaration)
2104       return nullptr;
2105 
2106     // If we have a builtin without an associated type we should not emit a
2107     // warning when we were not able to find a type for it.
2108     if (Error == ASTContext::GE_Missing_type)
2109       return nullptr;
2110 
2111     // If we could not find a type for setjmp it is because the jmp_buf type was
2112     // not defined prior to the setjmp declaration.
2113     if (Error == ASTContext::GE_Missing_setjmp) {
2114       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2115           << Context.BuiltinInfo.getName(ID);
2116       return nullptr;
2117     }
2118 
2119     // Generally, we emit a warning that the declaration requires the
2120     // appropriate header.
2121     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2122         << getHeaderName(Context.BuiltinInfo, ID, Error)
2123         << Context.BuiltinInfo.getName(ID);
2124     return nullptr;
2125   }
2126 
2127   if (!ForRedeclaration &&
2128       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2129        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2130     Diag(Loc, diag::ext_implicit_lib_function_decl)
2131         << Context.BuiltinInfo.getName(ID) << R;
2132     if (Context.BuiltinInfo.getHeaderName(ID) &&
2133         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2134       Diag(Loc, diag::note_include_header_or_declare)
2135           << Context.BuiltinInfo.getHeaderName(ID)
2136           << Context.BuiltinInfo.getName(ID);
2137   }
2138 
2139   if (R.isNull())
2140     return nullptr;
2141 
2142   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2143   RegisterLocallyScopedExternCDecl(New, S);
2144 
2145   // TUScope is the translation-unit scope to insert this function into.
2146   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2147   // relate Scopes to DeclContexts, and probably eliminate CurContext
2148   // entirely, but we're not there yet.
2149   DeclContext *SavedContext = CurContext;
2150   CurContext = New->getDeclContext();
2151   PushOnScopeChains(New, TUScope);
2152   CurContext = SavedContext;
2153   return New;
2154 }
2155 
2156 /// Typedef declarations don't have linkage, but they still denote the same
2157 /// entity if their types are the same.
2158 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2159 /// isSameEntity.
2160 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2161                                                      TypedefNameDecl *Decl,
2162                                                      LookupResult &Previous) {
2163   // This is only interesting when modules are enabled.
2164   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2165     return;
2166 
2167   // Empty sets are uninteresting.
2168   if (Previous.empty())
2169     return;
2170 
2171   LookupResult::Filter Filter = Previous.makeFilter();
2172   while (Filter.hasNext()) {
2173     NamedDecl *Old = Filter.next();
2174 
2175     // Non-hidden declarations are never ignored.
2176     if (S.isVisible(Old))
2177       continue;
2178 
2179     // Declarations of the same entity are not ignored, even if they have
2180     // different linkages.
2181     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2182       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2183                                 Decl->getUnderlyingType()))
2184         continue;
2185 
2186       // If both declarations give a tag declaration a typedef name for linkage
2187       // purposes, then they declare the same entity.
2188       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2189           Decl->getAnonDeclWithTypedefName())
2190         continue;
2191     }
2192 
2193     Filter.erase();
2194   }
2195 
2196   Filter.done();
2197 }
2198 
2199 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2200   QualType OldType;
2201   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2202     OldType = OldTypedef->getUnderlyingType();
2203   else
2204     OldType = Context.getTypeDeclType(Old);
2205   QualType NewType = New->getUnderlyingType();
2206 
2207   if (NewType->isVariablyModifiedType()) {
2208     // Must not redefine a typedef with a variably-modified type.
2209     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2210     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2211       << Kind << NewType;
2212     if (Old->getLocation().isValid())
2213       notePreviousDefinition(Old, New->getLocation());
2214     New->setInvalidDecl();
2215     return true;
2216   }
2217 
2218   if (OldType != NewType &&
2219       !OldType->isDependentType() &&
2220       !NewType->isDependentType() &&
2221       !Context.hasSameType(OldType, NewType)) {
2222     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2223     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2224       << Kind << NewType << OldType;
2225     if (Old->getLocation().isValid())
2226       notePreviousDefinition(Old, New->getLocation());
2227     New->setInvalidDecl();
2228     return true;
2229   }
2230   return false;
2231 }
2232 
2233 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2234 /// same name and scope as a previous declaration 'Old'.  Figure out
2235 /// how to resolve this situation, merging decls or emitting
2236 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2237 ///
2238 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2239                                 LookupResult &OldDecls) {
2240   // If the new decl is known invalid already, don't bother doing any
2241   // merging checks.
2242   if (New->isInvalidDecl()) return;
2243 
2244   // Allow multiple definitions for ObjC built-in typedefs.
2245   // FIXME: Verify the underlying types are equivalent!
2246   if (getLangOpts().ObjC) {
2247     const IdentifierInfo *TypeID = New->getIdentifier();
2248     switch (TypeID->getLength()) {
2249     default: break;
2250     case 2:
2251       {
2252         if (!TypeID->isStr("id"))
2253           break;
2254         QualType T = New->getUnderlyingType();
2255         if (!T->isPointerType())
2256           break;
2257         if (!T->isVoidPointerType()) {
2258           QualType PT = T->castAs<PointerType>()->getPointeeType();
2259           if (!PT->isStructureType())
2260             break;
2261         }
2262         Context.setObjCIdRedefinitionType(T);
2263         // Install the built-in type for 'id', ignoring the current definition.
2264         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2265         return;
2266       }
2267     case 5:
2268       if (!TypeID->isStr("Class"))
2269         break;
2270       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2271       // Install the built-in type for 'Class', ignoring the current definition.
2272       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2273       return;
2274     case 3:
2275       if (!TypeID->isStr("SEL"))
2276         break;
2277       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2278       // Install the built-in type for 'SEL', ignoring the current definition.
2279       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2280       return;
2281     }
2282     // Fall through - the typedef name was not a builtin type.
2283   }
2284 
2285   // Verify the old decl was also a type.
2286   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2287   if (!Old) {
2288     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2289       << New->getDeclName();
2290 
2291     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2292     if (OldD->getLocation().isValid())
2293       notePreviousDefinition(OldD, New->getLocation());
2294 
2295     return New->setInvalidDecl();
2296   }
2297 
2298   // If the old declaration is invalid, just give up here.
2299   if (Old->isInvalidDecl())
2300     return New->setInvalidDecl();
2301 
2302   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2303     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2304     auto *NewTag = New->getAnonDeclWithTypedefName();
2305     NamedDecl *Hidden = nullptr;
2306     if (OldTag && NewTag &&
2307         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2308         !hasVisibleDefinition(OldTag, &Hidden)) {
2309       // There is a definition of this tag, but it is not visible. Use it
2310       // instead of our tag.
2311       New->setTypeForDecl(OldTD->getTypeForDecl());
2312       if (OldTD->isModed())
2313         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2314                                     OldTD->getUnderlyingType());
2315       else
2316         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2317 
2318       // Make the old tag definition visible.
2319       makeMergedDefinitionVisible(Hidden);
2320 
2321       // If this was an unscoped enumeration, yank all of its enumerators
2322       // out of the scope.
2323       if (isa<EnumDecl>(NewTag)) {
2324         Scope *EnumScope = getNonFieldDeclScope(S);
2325         for (auto *D : NewTag->decls()) {
2326           auto *ED = cast<EnumConstantDecl>(D);
2327           assert(EnumScope->isDeclScope(ED));
2328           EnumScope->RemoveDecl(ED);
2329           IdResolver.RemoveDecl(ED);
2330           ED->getLexicalDeclContext()->removeDecl(ED);
2331         }
2332       }
2333     }
2334   }
2335 
2336   // If the typedef types are not identical, reject them in all languages and
2337   // with any extensions enabled.
2338   if (isIncompatibleTypedef(Old, New))
2339     return;
2340 
2341   // The types match.  Link up the redeclaration chain and merge attributes if
2342   // the old declaration was a typedef.
2343   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2344     New->setPreviousDecl(Typedef);
2345     mergeDeclAttributes(New, Old);
2346   }
2347 
2348   if (getLangOpts().MicrosoftExt)
2349     return;
2350 
2351   if (getLangOpts().CPlusPlus) {
2352     // C++ [dcl.typedef]p2:
2353     //   In a given non-class scope, a typedef specifier can be used to
2354     //   redefine the name of any type declared in that scope to refer
2355     //   to the type to which it already refers.
2356     if (!isa<CXXRecordDecl>(CurContext))
2357       return;
2358 
2359     // C++0x [dcl.typedef]p4:
2360     //   In a given class scope, a typedef specifier can be used to redefine
2361     //   any class-name declared in that scope that is not also a typedef-name
2362     //   to refer to the type to which it already refers.
2363     //
2364     // This wording came in via DR424, which was a correction to the
2365     // wording in DR56, which accidentally banned code like:
2366     //
2367     //   struct S {
2368     //     typedef struct A { } A;
2369     //   };
2370     //
2371     // in the C++03 standard. We implement the C++0x semantics, which
2372     // allow the above but disallow
2373     //
2374     //   struct S {
2375     //     typedef int I;
2376     //     typedef int I;
2377     //   };
2378     //
2379     // since that was the intent of DR56.
2380     if (!isa<TypedefNameDecl>(Old))
2381       return;
2382 
2383     Diag(New->getLocation(), diag::err_redefinition)
2384       << New->getDeclName();
2385     notePreviousDefinition(Old, New->getLocation());
2386     return New->setInvalidDecl();
2387   }
2388 
2389   // Modules always permit redefinition of typedefs, as does C11.
2390   if (getLangOpts().Modules || getLangOpts().C11)
2391     return;
2392 
2393   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2394   // is normally mapped to an error, but can be controlled with
2395   // -Wtypedef-redefinition.  If either the original or the redefinition is
2396   // in a system header, don't emit this for compatibility with GCC.
2397   if (getDiagnostics().getSuppressSystemWarnings() &&
2398       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2399       (Old->isImplicit() ||
2400        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2401        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2402     return;
2403 
2404   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2405     << New->getDeclName();
2406   notePreviousDefinition(Old, New->getLocation());
2407 }
2408 
2409 /// DeclhasAttr - returns true if decl Declaration already has the target
2410 /// attribute.
2411 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2412   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2413   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2414   for (const auto *i : D->attrs())
2415     if (i->getKind() == A->getKind()) {
2416       if (Ann) {
2417         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2418           return true;
2419         continue;
2420       }
2421       // FIXME: Don't hardcode this check
2422       if (OA && isa<OwnershipAttr>(i))
2423         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2424       return true;
2425     }
2426 
2427   return false;
2428 }
2429 
2430 static bool isAttributeTargetADefinition(Decl *D) {
2431   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2432     return VD->isThisDeclarationADefinition();
2433   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2434     return TD->isCompleteDefinition() || TD->isBeingDefined();
2435   return true;
2436 }
2437 
2438 /// Merge alignment attributes from \p Old to \p New, taking into account the
2439 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2440 ///
2441 /// \return \c true if any attributes were added to \p New.
2442 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2443   // Look for alignas attributes on Old, and pick out whichever attribute
2444   // specifies the strictest alignment requirement.
2445   AlignedAttr *OldAlignasAttr = nullptr;
2446   AlignedAttr *OldStrictestAlignAttr = nullptr;
2447   unsigned OldAlign = 0;
2448   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2449     // FIXME: We have no way of representing inherited dependent alignments
2450     // in a case like:
2451     //   template<int A, int B> struct alignas(A) X;
2452     //   template<int A, int B> struct alignas(B) X {};
2453     // For now, we just ignore any alignas attributes which are not on the
2454     // definition in such a case.
2455     if (I->isAlignmentDependent())
2456       return false;
2457 
2458     if (I->isAlignas())
2459       OldAlignasAttr = I;
2460 
2461     unsigned Align = I->getAlignment(S.Context);
2462     if (Align > OldAlign) {
2463       OldAlign = Align;
2464       OldStrictestAlignAttr = I;
2465     }
2466   }
2467 
2468   // Look for alignas attributes on New.
2469   AlignedAttr *NewAlignasAttr = nullptr;
2470   unsigned NewAlign = 0;
2471   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2472     if (I->isAlignmentDependent())
2473       return false;
2474 
2475     if (I->isAlignas())
2476       NewAlignasAttr = I;
2477 
2478     unsigned Align = I->getAlignment(S.Context);
2479     if (Align > NewAlign)
2480       NewAlign = Align;
2481   }
2482 
2483   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2484     // Both declarations have 'alignas' attributes. We require them to match.
2485     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2486     // fall short. (If two declarations both have alignas, they must both match
2487     // every definition, and so must match each other if there is a definition.)
2488 
2489     // If either declaration only contains 'alignas(0)' specifiers, then it
2490     // specifies the natural alignment for the type.
2491     if (OldAlign == 0 || NewAlign == 0) {
2492       QualType Ty;
2493       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2494         Ty = VD->getType();
2495       else
2496         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2497 
2498       if (OldAlign == 0)
2499         OldAlign = S.Context.getTypeAlign(Ty);
2500       if (NewAlign == 0)
2501         NewAlign = S.Context.getTypeAlign(Ty);
2502     }
2503 
2504     if (OldAlign != NewAlign) {
2505       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2506         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2507         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2508       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2509     }
2510   }
2511 
2512   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2513     // C++11 [dcl.align]p6:
2514     //   if any declaration of an entity has an alignment-specifier,
2515     //   every defining declaration of that entity shall specify an
2516     //   equivalent alignment.
2517     // C11 6.7.5/7:
2518     //   If the definition of an object does not have an alignment
2519     //   specifier, any other declaration of that object shall also
2520     //   have no alignment specifier.
2521     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2522       << OldAlignasAttr;
2523     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2524       << OldAlignasAttr;
2525   }
2526 
2527   bool AnyAdded = false;
2528 
2529   // Ensure we have an attribute representing the strictest alignment.
2530   if (OldAlign > NewAlign) {
2531     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2532     Clone->setInherited(true);
2533     New->addAttr(Clone);
2534     AnyAdded = true;
2535   }
2536 
2537   // Ensure we have an alignas attribute if the old declaration had one.
2538   if (OldAlignasAttr && !NewAlignasAttr &&
2539       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2540     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2541     Clone->setInherited(true);
2542     New->addAttr(Clone);
2543     AnyAdded = true;
2544   }
2545 
2546   return AnyAdded;
2547 }
2548 
2549 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2550                                const InheritableAttr *Attr,
2551                                Sema::AvailabilityMergeKind AMK) {
2552   // This function copies an attribute Attr from a previous declaration to the
2553   // new declaration D if the new declaration doesn't itself have that attribute
2554   // yet or if that attribute allows duplicates.
2555   // If you're adding a new attribute that requires logic different from
2556   // "use explicit attribute on decl if present, else use attribute from
2557   // previous decl", for example if the attribute needs to be consistent
2558   // between redeclarations, you need to call a custom merge function here.
2559   InheritableAttr *NewAttr = nullptr;
2560   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2561     NewAttr = S.mergeAvailabilityAttr(
2562         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2563         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2564         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2565         AA->getPriority());
2566   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2567     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2568   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2569     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2570   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2571     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2572   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2573     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2574   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2575     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2576                                 FA->getFirstArg());
2577   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2578     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2579   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2580     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2581   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2582     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2583                                        IA->getInheritanceModel());
2584   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2585     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2586                                       &S.Context.Idents.get(AA->getSpelling()));
2587   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2588            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2589             isa<CUDAGlobalAttr>(Attr))) {
2590     // CUDA target attributes are part of function signature for
2591     // overloading purposes and must not be merged.
2592     return false;
2593   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2594     NewAttr = S.mergeMinSizeAttr(D, *MA);
2595   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2596     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName(),
2597                                    AMK == Sema::AMK_Override);
2598   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2599     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2600   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2601     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2602   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2603     NewAttr = S.mergeCommonAttr(D, *CommonA);
2604   else if (isa<AlignedAttr>(Attr))
2605     // AlignedAttrs are handled separately, because we need to handle all
2606     // such attributes on a declaration at the same time.
2607     NewAttr = nullptr;
2608   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2609            (AMK == Sema::AMK_Override ||
2610             AMK == Sema::AMK_ProtocolImplementation))
2611     NewAttr = nullptr;
2612   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2613     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2614   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2615     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2616   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2617     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2618   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2619     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2620   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2621     NewAttr = S.mergeImportNameAttr(D, *INA);
2622   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2623     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2624 
2625   if (NewAttr) {
2626     NewAttr->setInherited(true);
2627     D->addAttr(NewAttr);
2628     if (isa<MSInheritanceAttr>(NewAttr))
2629       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2630     return true;
2631   }
2632 
2633   return false;
2634 }
2635 
2636 static const NamedDecl *getDefinition(const Decl *D) {
2637   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2638     return TD->getDefinition();
2639   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2640     const VarDecl *Def = VD->getDefinition();
2641     if (Def)
2642       return Def;
2643     return VD->getActingDefinition();
2644   }
2645   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2646     return FD->getDefinition();
2647   return nullptr;
2648 }
2649 
2650 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2651   for (const auto *Attribute : D->attrs())
2652     if (Attribute->getKind() == Kind)
2653       return true;
2654   return false;
2655 }
2656 
2657 /// checkNewAttributesAfterDef - If we already have a definition, check that
2658 /// there are no new attributes in this declaration.
2659 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2660   if (!New->hasAttrs())
2661     return;
2662 
2663   const NamedDecl *Def = getDefinition(Old);
2664   if (!Def || Def == New)
2665     return;
2666 
2667   AttrVec &NewAttributes = New->getAttrs();
2668   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2669     const Attr *NewAttribute = NewAttributes[I];
2670 
2671     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2672       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2673         Sema::SkipBodyInfo SkipBody;
2674         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2675 
2676         // If we're skipping this definition, drop the "alias" attribute.
2677         if (SkipBody.ShouldSkip) {
2678           NewAttributes.erase(NewAttributes.begin() + I);
2679           --E;
2680           continue;
2681         }
2682       } else {
2683         VarDecl *VD = cast<VarDecl>(New);
2684         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2685                                 VarDecl::TentativeDefinition
2686                             ? diag::err_alias_after_tentative
2687                             : diag::err_redefinition;
2688         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2689         if (Diag == diag::err_redefinition)
2690           S.notePreviousDefinition(Def, VD->getLocation());
2691         else
2692           S.Diag(Def->getLocation(), diag::note_previous_definition);
2693         VD->setInvalidDecl();
2694       }
2695       ++I;
2696       continue;
2697     }
2698 
2699     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2700       // Tentative definitions are only interesting for the alias check above.
2701       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2702         ++I;
2703         continue;
2704       }
2705     }
2706 
2707     if (hasAttribute(Def, NewAttribute->getKind())) {
2708       ++I;
2709       continue; // regular attr merging will take care of validating this.
2710     }
2711 
2712     if (isa<C11NoReturnAttr>(NewAttribute)) {
2713       // C's _Noreturn is allowed to be added to a function after it is defined.
2714       ++I;
2715       continue;
2716     } else if (isa<UuidAttr>(NewAttribute)) {
2717       // msvc will allow a subsequent definition to add an uuid to a class
2718       ++I;
2719       continue;
2720     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2721       if (AA->isAlignas()) {
2722         // C++11 [dcl.align]p6:
2723         //   if any declaration of an entity has an alignment-specifier,
2724         //   every defining declaration of that entity shall specify an
2725         //   equivalent alignment.
2726         // C11 6.7.5/7:
2727         //   If the definition of an object does not have an alignment
2728         //   specifier, any other declaration of that object shall also
2729         //   have no alignment specifier.
2730         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2731           << AA;
2732         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2733           << AA;
2734         NewAttributes.erase(NewAttributes.begin() + I);
2735         --E;
2736         continue;
2737       }
2738     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2739       // If there is a C definition followed by a redeclaration with this
2740       // attribute then there are two different definitions. In C++, prefer the
2741       // standard diagnostics.
2742       if (!S.getLangOpts().CPlusPlus) {
2743         S.Diag(NewAttribute->getLocation(),
2744                diag::err_loader_uninitialized_redeclaration);
2745         S.Diag(Def->getLocation(), diag::note_previous_definition);
2746         NewAttributes.erase(NewAttributes.begin() + I);
2747         --E;
2748         continue;
2749       }
2750     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2751                cast<VarDecl>(New)->isInline() &&
2752                !cast<VarDecl>(New)->isInlineSpecified()) {
2753       // Don't warn about applying selectany to implicitly inline variables.
2754       // Older compilers and language modes would require the use of selectany
2755       // to make such variables inline, and it would have no effect if we
2756       // honored it.
2757       ++I;
2758       continue;
2759     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2760       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2761       // declarations after defintions.
2762       ++I;
2763       continue;
2764     }
2765 
2766     S.Diag(NewAttribute->getLocation(),
2767            diag::warn_attribute_precede_definition);
2768     S.Diag(Def->getLocation(), diag::note_previous_definition);
2769     NewAttributes.erase(NewAttributes.begin() + I);
2770     --E;
2771   }
2772 }
2773 
2774 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2775                                      const ConstInitAttr *CIAttr,
2776                                      bool AttrBeforeInit) {
2777   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2778 
2779   // Figure out a good way to write this specifier on the old declaration.
2780   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2781   // enough of the attribute list spelling information to extract that without
2782   // heroics.
2783   std::string SuitableSpelling;
2784   if (S.getLangOpts().CPlusPlus20)
2785     SuitableSpelling = std::string(
2786         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2787   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2788     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2789         InsertLoc, {tok::l_square, tok::l_square,
2790                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2791                     S.PP.getIdentifierInfo("require_constant_initialization"),
2792                     tok::r_square, tok::r_square}));
2793   if (SuitableSpelling.empty())
2794     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2795         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2796                     S.PP.getIdentifierInfo("require_constant_initialization"),
2797                     tok::r_paren, tok::r_paren}));
2798   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2799     SuitableSpelling = "constinit";
2800   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2801     SuitableSpelling = "[[clang::require_constant_initialization]]";
2802   if (SuitableSpelling.empty())
2803     SuitableSpelling = "__attribute__((require_constant_initialization))";
2804   SuitableSpelling += " ";
2805 
2806   if (AttrBeforeInit) {
2807     // extern constinit int a;
2808     // int a = 0; // error (missing 'constinit'), accepted as extension
2809     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2810     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2811         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2812     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2813   } else {
2814     // int a = 0;
2815     // constinit extern int a; // error (missing 'constinit')
2816     S.Diag(CIAttr->getLocation(),
2817            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2818                                  : diag::warn_require_const_init_added_too_late)
2819         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2820     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2821         << CIAttr->isConstinit()
2822         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2823   }
2824 }
2825 
2826 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2827 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2828                                AvailabilityMergeKind AMK) {
2829   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2830     UsedAttr *NewAttr = OldAttr->clone(Context);
2831     NewAttr->setInherited(true);
2832     New->addAttr(NewAttr);
2833   }
2834 
2835   if (!Old->hasAttrs() && !New->hasAttrs())
2836     return;
2837 
2838   // [dcl.constinit]p1:
2839   //   If the [constinit] specifier is applied to any declaration of a
2840   //   variable, it shall be applied to the initializing declaration.
2841   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2842   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2843   if (bool(OldConstInit) != bool(NewConstInit)) {
2844     const auto *OldVD = cast<VarDecl>(Old);
2845     auto *NewVD = cast<VarDecl>(New);
2846 
2847     // Find the initializing declaration. Note that we might not have linked
2848     // the new declaration into the redeclaration chain yet.
2849     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2850     if (!InitDecl &&
2851         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2852       InitDecl = NewVD;
2853 
2854     if (InitDecl == NewVD) {
2855       // This is the initializing declaration. If it would inherit 'constinit',
2856       // that's ill-formed. (Note that we do not apply this to the attribute
2857       // form).
2858       if (OldConstInit && OldConstInit->isConstinit())
2859         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2860                                  /*AttrBeforeInit=*/true);
2861     } else if (NewConstInit) {
2862       // This is the first time we've been told that this declaration should
2863       // have a constant initializer. If we already saw the initializing
2864       // declaration, this is too late.
2865       if (InitDecl && InitDecl != NewVD) {
2866         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2867                                  /*AttrBeforeInit=*/false);
2868         NewVD->dropAttr<ConstInitAttr>();
2869       }
2870     }
2871   }
2872 
2873   // Attributes declared post-definition are currently ignored.
2874   checkNewAttributesAfterDef(*this, New, Old);
2875 
2876   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2877     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2878       if (!OldA->isEquivalent(NewA)) {
2879         // This redeclaration changes __asm__ label.
2880         Diag(New->getLocation(), diag::err_different_asm_label);
2881         Diag(OldA->getLocation(), diag::note_previous_declaration);
2882       }
2883     } else if (Old->isUsed()) {
2884       // This redeclaration adds an __asm__ label to a declaration that has
2885       // already been ODR-used.
2886       Diag(New->getLocation(), diag::err_late_asm_label_name)
2887         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2888     }
2889   }
2890 
2891   // Re-declaration cannot add abi_tag's.
2892   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2893     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2894       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2895         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2896                       NewTag) == OldAbiTagAttr->tags_end()) {
2897           Diag(NewAbiTagAttr->getLocation(),
2898                diag::err_new_abi_tag_on_redeclaration)
2899               << NewTag;
2900           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2901         }
2902       }
2903     } else {
2904       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2905       Diag(Old->getLocation(), diag::note_previous_declaration);
2906     }
2907   }
2908 
2909   // This redeclaration adds a section attribute.
2910   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2911     if (auto *VD = dyn_cast<VarDecl>(New)) {
2912       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2913         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2914         Diag(Old->getLocation(), diag::note_previous_declaration);
2915       }
2916     }
2917   }
2918 
2919   // Redeclaration adds code-seg attribute.
2920   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2921   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2922       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2923     Diag(New->getLocation(), diag::warn_mismatched_section)
2924          << 0 /*codeseg*/;
2925     Diag(Old->getLocation(), diag::note_previous_declaration);
2926   }
2927 
2928   if (!Old->hasAttrs())
2929     return;
2930 
2931   bool foundAny = New->hasAttrs();
2932 
2933   // Ensure that any moving of objects within the allocated map is done before
2934   // we process them.
2935   if (!foundAny) New->setAttrs(AttrVec());
2936 
2937   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2938     // Ignore deprecated/unavailable/availability attributes if requested.
2939     AvailabilityMergeKind LocalAMK = AMK_None;
2940     if (isa<DeprecatedAttr>(I) ||
2941         isa<UnavailableAttr>(I) ||
2942         isa<AvailabilityAttr>(I)) {
2943       switch (AMK) {
2944       case AMK_None:
2945         continue;
2946 
2947       case AMK_Redeclaration:
2948       case AMK_Override:
2949       case AMK_ProtocolImplementation:
2950         LocalAMK = AMK;
2951         break;
2952       }
2953     }
2954 
2955     // Already handled.
2956     if (isa<UsedAttr>(I))
2957       continue;
2958 
2959     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2960       foundAny = true;
2961   }
2962 
2963   if (mergeAlignedAttrs(*this, New, Old))
2964     foundAny = true;
2965 
2966   if (!foundAny) New->dropAttrs();
2967 }
2968 
2969 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2970 /// to the new one.
2971 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2972                                      const ParmVarDecl *oldDecl,
2973                                      Sema &S) {
2974   // C++11 [dcl.attr.depend]p2:
2975   //   The first declaration of a function shall specify the
2976   //   carries_dependency attribute for its declarator-id if any declaration
2977   //   of the function specifies the carries_dependency attribute.
2978   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2979   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2980     S.Diag(CDA->getLocation(),
2981            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2982     // Find the first declaration of the parameter.
2983     // FIXME: Should we build redeclaration chains for function parameters?
2984     const FunctionDecl *FirstFD =
2985       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2986     const ParmVarDecl *FirstVD =
2987       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2988     S.Diag(FirstVD->getLocation(),
2989            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2990   }
2991 
2992   if (!oldDecl->hasAttrs())
2993     return;
2994 
2995   bool foundAny = newDecl->hasAttrs();
2996 
2997   // Ensure that any moving of objects within the allocated map is
2998   // done before we process them.
2999   if (!foundAny) newDecl->setAttrs(AttrVec());
3000 
3001   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3002     if (!DeclHasAttr(newDecl, I)) {
3003       InheritableAttr *newAttr =
3004         cast<InheritableParamAttr>(I->clone(S.Context));
3005       newAttr->setInherited(true);
3006       newDecl->addAttr(newAttr);
3007       foundAny = true;
3008     }
3009   }
3010 
3011   if (!foundAny) newDecl->dropAttrs();
3012 }
3013 
3014 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3015                                 const ParmVarDecl *OldParam,
3016                                 Sema &S) {
3017   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3018     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3019       if (*Oldnullability != *Newnullability) {
3020         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3021           << DiagNullabilityKind(
3022                *Newnullability,
3023                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3024                 != 0))
3025           << DiagNullabilityKind(
3026                *Oldnullability,
3027                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3028                 != 0));
3029         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3030       }
3031     } else {
3032       QualType NewT = NewParam->getType();
3033       NewT = S.Context.getAttributedType(
3034                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3035                          NewT, NewT);
3036       NewParam->setType(NewT);
3037     }
3038   }
3039 }
3040 
3041 namespace {
3042 
3043 /// Used in MergeFunctionDecl to keep track of function parameters in
3044 /// C.
3045 struct GNUCompatibleParamWarning {
3046   ParmVarDecl *OldParm;
3047   ParmVarDecl *NewParm;
3048   QualType PromotedType;
3049 };
3050 
3051 } // end anonymous namespace
3052 
3053 // Determine whether the previous declaration was a definition, implicit
3054 // declaration, or a declaration.
3055 template <typename T>
3056 static std::pair<diag::kind, SourceLocation>
3057 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3058   diag::kind PrevDiag;
3059   SourceLocation OldLocation = Old->getLocation();
3060   if (Old->isThisDeclarationADefinition())
3061     PrevDiag = diag::note_previous_definition;
3062   else if (Old->isImplicit()) {
3063     PrevDiag = diag::note_previous_implicit_declaration;
3064     if (OldLocation.isInvalid())
3065       OldLocation = New->getLocation();
3066   } else
3067     PrevDiag = diag::note_previous_declaration;
3068   return std::make_pair(PrevDiag, OldLocation);
3069 }
3070 
3071 /// canRedefineFunction - checks if a function can be redefined. Currently,
3072 /// only extern inline functions can be redefined, and even then only in
3073 /// GNU89 mode.
3074 static bool canRedefineFunction(const FunctionDecl *FD,
3075                                 const LangOptions& LangOpts) {
3076   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3077           !LangOpts.CPlusPlus &&
3078           FD->isInlineSpecified() &&
3079           FD->getStorageClass() == SC_Extern);
3080 }
3081 
3082 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3083   const AttributedType *AT = T->getAs<AttributedType>();
3084   while (AT && !AT->isCallingConv())
3085     AT = AT->getModifiedType()->getAs<AttributedType>();
3086   return AT;
3087 }
3088 
3089 template <typename T>
3090 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3091   const DeclContext *DC = Old->getDeclContext();
3092   if (DC->isRecord())
3093     return false;
3094 
3095   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3096   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3097     return true;
3098   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3099     return true;
3100   return false;
3101 }
3102 
3103 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3104 static bool isExternC(VarTemplateDecl *) { return false; }
3105 
3106 /// Check whether a redeclaration of an entity introduced by a
3107 /// using-declaration is valid, given that we know it's not an overload
3108 /// (nor a hidden tag declaration).
3109 template<typename ExpectedDecl>
3110 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3111                                    ExpectedDecl *New) {
3112   // C++11 [basic.scope.declarative]p4:
3113   //   Given a set of declarations in a single declarative region, each of
3114   //   which specifies the same unqualified name,
3115   //   -- they shall all refer to the same entity, or all refer to functions
3116   //      and function templates; or
3117   //   -- exactly one declaration shall declare a class name or enumeration
3118   //      name that is not a typedef name and the other declarations shall all
3119   //      refer to the same variable or enumerator, or all refer to functions
3120   //      and function templates; in this case the class name or enumeration
3121   //      name is hidden (3.3.10).
3122 
3123   // C++11 [namespace.udecl]p14:
3124   //   If a function declaration in namespace scope or block scope has the
3125   //   same name and the same parameter-type-list as a function introduced
3126   //   by a using-declaration, and the declarations do not declare the same
3127   //   function, the program is ill-formed.
3128 
3129   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3130   if (Old &&
3131       !Old->getDeclContext()->getRedeclContext()->Equals(
3132           New->getDeclContext()->getRedeclContext()) &&
3133       !(isExternC(Old) && isExternC(New)))
3134     Old = nullptr;
3135 
3136   if (!Old) {
3137     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3138     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3139     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3140     return true;
3141   }
3142   return false;
3143 }
3144 
3145 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3146                                             const FunctionDecl *B) {
3147   assert(A->getNumParams() == B->getNumParams());
3148 
3149   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3150     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3151     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3152     if (AttrA == AttrB)
3153       return true;
3154     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3155            AttrA->isDynamic() == AttrB->isDynamic();
3156   };
3157 
3158   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3159 }
3160 
3161 /// If necessary, adjust the semantic declaration context for a qualified
3162 /// declaration to name the correct inline namespace within the qualifier.
3163 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3164                                                DeclaratorDecl *OldD) {
3165   // The only case where we need to update the DeclContext is when
3166   // redeclaration lookup for a qualified name finds a declaration
3167   // in an inline namespace within the context named by the qualifier:
3168   //
3169   //   inline namespace N { int f(); }
3170   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3171   //
3172   // For unqualified declarations, the semantic context *can* change
3173   // along the redeclaration chain (for local extern declarations,
3174   // extern "C" declarations, and friend declarations in particular).
3175   if (!NewD->getQualifier())
3176     return;
3177 
3178   // NewD is probably already in the right context.
3179   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3180   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3181   if (NamedDC->Equals(SemaDC))
3182     return;
3183 
3184   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3185           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3186          "unexpected context for redeclaration");
3187 
3188   auto *LexDC = NewD->getLexicalDeclContext();
3189   auto FixSemaDC = [=](NamedDecl *D) {
3190     if (!D)
3191       return;
3192     D->setDeclContext(SemaDC);
3193     D->setLexicalDeclContext(LexDC);
3194   };
3195 
3196   FixSemaDC(NewD);
3197   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3198     FixSemaDC(FD->getDescribedFunctionTemplate());
3199   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3200     FixSemaDC(VD->getDescribedVarTemplate());
3201 }
3202 
3203 /// MergeFunctionDecl - We just parsed a function 'New' from
3204 /// declarator D which has the same name and scope as a previous
3205 /// declaration 'Old'.  Figure out how to resolve this situation,
3206 /// merging decls or emitting diagnostics as appropriate.
3207 ///
3208 /// In C++, New and Old must be declarations that are not
3209 /// overloaded. Use IsOverload to determine whether New and Old are
3210 /// overloaded, and to select the Old declaration that New should be
3211 /// merged with.
3212 ///
3213 /// Returns true if there was an error, false otherwise.
3214 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3215                              Scope *S, bool MergeTypeWithOld) {
3216   // Verify the old decl was also a function.
3217   FunctionDecl *Old = OldD->getAsFunction();
3218   if (!Old) {
3219     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3220       if (New->getFriendObjectKind()) {
3221         Diag(New->getLocation(), diag::err_using_decl_friend);
3222         Diag(Shadow->getTargetDecl()->getLocation(),
3223              diag::note_using_decl_target);
3224         Diag(Shadow->getUsingDecl()->getLocation(),
3225              diag::note_using_decl) << 0;
3226         return true;
3227       }
3228 
3229       // Check whether the two declarations might declare the same function.
3230       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3231         return true;
3232       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3233     } else {
3234       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3235         << New->getDeclName();
3236       notePreviousDefinition(OldD, New->getLocation());
3237       return true;
3238     }
3239   }
3240 
3241   // If the old declaration is invalid, just give up here.
3242   if (Old->isInvalidDecl())
3243     return true;
3244 
3245   // Disallow redeclaration of some builtins.
3246   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3247     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3248     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3249         << Old << Old->getType();
3250     return true;
3251   }
3252 
3253   diag::kind PrevDiag;
3254   SourceLocation OldLocation;
3255   std::tie(PrevDiag, OldLocation) =
3256       getNoteDiagForInvalidRedeclaration(Old, New);
3257 
3258   // Don't complain about this if we're in GNU89 mode and the old function
3259   // is an extern inline function.
3260   // Don't complain about specializations. They are not supposed to have
3261   // storage classes.
3262   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3263       New->getStorageClass() == SC_Static &&
3264       Old->hasExternalFormalLinkage() &&
3265       !New->getTemplateSpecializationInfo() &&
3266       !canRedefineFunction(Old, getLangOpts())) {
3267     if (getLangOpts().MicrosoftExt) {
3268       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3269       Diag(OldLocation, PrevDiag);
3270     } else {
3271       Diag(New->getLocation(), diag::err_static_non_static) << New;
3272       Diag(OldLocation, PrevDiag);
3273       return true;
3274     }
3275   }
3276 
3277   if (New->hasAttr<InternalLinkageAttr>() &&
3278       !Old->hasAttr<InternalLinkageAttr>()) {
3279     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3280         << New->getDeclName();
3281     notePreviousDefinition(Old, New->getLocation());
3282     New->dropAttr<InternalLinkageAttr>();
3283   }
3284 
3285   if (CheckRedeclarationModuleOwnership(New, Old))
3286     return true;
3287 
3288   if (!getLangOpts().CPlusPlus) {
3289     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3290     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3291       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3292         << New << OldOvl;
3293 
3294       // Try our best to find a decl that actually has the overloadable
3295       // attribute for the note. In most cases (e.g. programs with only one
3296       // broken declaration/definition), this won't matter.
3297       //
3298       // FIXME: We could do this if we juggled some extra state in
3299       // OverloadableAttr, rather than just removing it.
3300       const Decl *DiagOld = Old;
3301       if (OldOvl) {
3302         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3303           const auto *A = D->getAttr<OverloadableAttr>();
3304           return A && !A->isImplicit();
3305         });
3306         // If we've implicitly added *all* of the overloadable attrs to this
3307         // chain, emitting a "previous redecl" note is pointless.
3308         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3309       }
3310 
3311       if (DiagOld)
3312         Diag(DiagOld->getLocation(),
3313              diag::note_attribute_overloadable_prev_overload)
3314           << OldOvl;
3315 
3316       if (OldOvl)
3317         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3318       else
3319         New->dropAttr<OverloadableAttr>();
3320     }
3321   }
3322 
3323   // If a function is first declared with a calling convention, but is later
3324   // declared or defined without one, all following decls assume the calling
3325   // convention of the first.
3326   //
3327   // It's OK if a function is first declared without a calling convention,
3328   // but is later declared or defined with the default calling convention.
3329   //
3330   // To test if either decl has an explicit calling convention, we look for
3331   // AttributedType sugar nodes on the type as written.  If they are missing or
3332   // were canonicalized away, we assume the calling convention was implicit.
3333   //
3334   // Note also that we DO NOT return at this point, because we still have
3335   // other tests to run.
3336   QualType OldQType = Context.getCanonicalType(Old->getType());
3337   QualType NewQType = Context.getCanonicalType(New->getType());
3338   const FunctionType *OldType = cast<FunctionType>(OldQType);
3339   const FunctionType *NewType = cast<FunctionType>(NewQType);
3340   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3341   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3342   bool RequiresAdjustment = false;
3343 
3344   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3345     FunctionDecl *First = Old->getFirstDecl();
3346     const FunctionType *FT =
3347         First->getType().getCanonicalType()->castAs<FunctionType>();
3348     FunctionType::ExtInfo FI = FT->getExtInfo();
3349     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3350     if (!NewCCExplicit) {
3351       // Inherit the CC from the previous declaration if it was specified
3352       // there but not here.
3353       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3354       RequiresAdjustment = true;
3355     } else if (Old->getBuiltinID()) {
3356       // Builtin attribute isn't propagated to the new one yet at this point,
3357       // so we check if the old one is a builtin.
3358 
3359       // Calling Conventions on a Builtin aren't really useful and setting a
3360       // default calling convention and cdecl'ing some builtin redeclarations is
3361       // common, so warn and ignore the calling convention on the redeclaration.
3362       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3363           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3364           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3365       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3366       RequiresAdjustment = true;
3367     } else {
3368       // Calling conventions aren't compatible, so complain.
3369       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3370       Diag(New->getLocation(), diag::err_cconv_change)
3371         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3372         << !FirstCCExplicit
3373         << (!FirstCCExplicit ? "" :
3374             FunctionType::getNameForCallConv(FI.getCC()));
3375 
3376       // Put the note on the first decl, since it is the one that matters.
3377       Diag(First->getLocation(), diag::note_previous_declaration);
3378       return true;
3379     }
3380   }
3381 
3382   // FIXME: diagnose the other way around?
3383   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3384     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3385     RequiresAdjustment = true;
3386   }
3387 
3388   // Merge regparm attribute.
3389   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3390       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3391     if (NewTypeInfo.getHasRegParm()) {
3392       Diag(New->getLocation(), diag::err_regparm_mismatch)
3393         << NewType->getRegParmType()
3394         << OldType->getRegParmType();
3395       Diag(OldLocation, diag::note_previous_declaration);
3396       return true;
3397     }
3398 
3399     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3400     RequiresAdjustment = true;
3401   }
3402 
3403   // Merge ns_returns_retained attribute.
3404   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3405     if (NewTypeInfo.getProducesResult()) {
3406       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3407           << "'ns_returns_retained'";
3408       Diag(OldLocation, diag::note_previous_declaration);
3409       return true;
3410     }
3411 
3412     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3413     RequiresAdjustment = true;
3414   }
3415 
3416   if (OldTypeInfo.getNoCallerSavedRegs() !=
3417       NewTypeInfo.getNoCallerSavedRegs()) {
3418     if (NewTypeInfo.getNoCallerSavedRegs()) {
3419       AnyX86NoCallerSavedRegistersAttr *Attr =
3420         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3421       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3422       Diag(OldLocation, diag::note_previous_declaration);
3423       return true;
3424     }
3425 
3426     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3427     RequiresAdjustment = true;
3428   }
3429 
3430   if (RequiresAdjustment) {
3431     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3432     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3433     New->setType(QualType(AdjustedType, 0));
3434     NewQType = Context.getCanonicalType(New->getType());
3435   }
3436 
3437   // If this redeclaration makes the function inline, we may need to add it to
3438   // UndefinedButUsed.
3439   if (!Old->isInlined() && New->isInlined() &&
3440       !New->hasAttr<GNUInlineAttr>() &&
3441       !getLangOpts().GNUInline &&
3442       Old->isUsed(false) &&
3443       !Old->isDefined() && !New->isThisDeclarationADefinition())
3444     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3445                                            SourceLocation()));
3446 
3447   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3448   // about it.
3449   if (New->hasAttr<GNUInlineAttr>() &&
3450       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3451     UndefinedButUsed.erase(Old->getCanonicalDecl());
3452   }
3453 
3454   // If pass_object_size params don't match up perfectly, this isn't a valid
3455   // redeclaration.
3456   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3457       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3458     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3459         << New->getDeclName();
3460     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3461     return true;
3462   }
3463 
3464   if (getLangOpts().CPlusPlus) {
3465     // C++1z [over.load]p2
3466     //   Certain function declarations cannot be overloaded:
3467     //     -- Function declarations that differ only in the return type,
3468     //        the exception specification, or both cannot be overloaded.
3469 
3470     // Check the exception specifications match. This may recompute the type of
3471     // both Old and New if it resolved exception specifications, so grab the
3472     // types again after this. Because this updates the type, we do this before
3473     // any of the other checks below, which may update the "de facto" NewQType
3474     // but do not necessarily update the type of New.
3475     if (CheckEquivalentExceptionSpec(Old, New))
3476       return true;
3477     OldQType = Context.getCanonicalType(Old->getType());
3478     NewQType = Context.getCanonicalType(New->getType());
3479 
3480     // Go back to the type source info to compare the declared return types,
3481     // per C++1y [dcl.type.auto]p13:
3482     //   Redeclarations or specializations of a function or function template
3483     //   with a declared return type that uses a placeholder type shall also
3484     //   use that placeholder, not a deduced type.
3485     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3486     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3487     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3488         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3489                                        OldDeclaredReturnType)) {
3490       QualType ResQT;
3491       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3492           OldDeclaredReturnType->isObjCObjectPointerType())
3493         // FIXME: This does the wrong thing for a deduced return type.
3494         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3495       if (ResQT.isNull()) {
3496         if (New->isCXXClassMember() && New->isOutOfLine())
3497           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3498               << New << New->getReturnTypeSourceRange();
3499         else
3500           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3501               << New->getReturnTypeSourceRange();
3502         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3503                                     << Old->getReturnTypeSourceRange();
3504         return true;
3505       }
3506       else
3507         NewQType = ResQT;
3508     }
3509 
3510     QualType OldReturnType = OldType->getReturnType();
3511     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3512     if (OldReturnType != NewReturnType) {
3513       // If this function has a deduced return type and has already been
3514       // defined, copy the deduced value from the old declaration.
3515       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3516       if (OldAT && OldAT->isDeduced()) {
3517         New->setType(
3518             SubstAutoType(New->getType(),
3519                           OldAT->isDependentType() ? Context.DependentTy
3520                                                    : OldAT->getDeducedType()));
3521         NewQType = Context.getCanonicalType(
3522             SubstAutoType(NewQType,
3523                           OldAT->isDependentType() ? Context.DependentTy
3524                                                    : OldAT->getDeducedType()));
3525       }
3526     }
3527 
3528     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3529     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3530     if (OldMethod && NewMethod) {
3531       // Preserve triviality.
3532       NewMethod->setTrivial(OldMethod->isTrivial());
3533 
3534       // MSVC allows explicit template specialization at class scope:
3535       // 2 CXXMethodDecls referring to the same function will be injected.
3536       // We don't want a redeclaration error.
3537       bool IsClassScopeExplicitSpecialization =
3538                               OldMethod->isFunctionTemplateSpecialization() &&
3539                               NewMethod->isFunctionTemplateSpecialization();
3540       bool isFriend = NewMethod->getFriendObjectKind();
3541 
3542       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3543           !IsClassScopeExplicitSpecialization) {
3544         //    -- Member function declarations with the same name and the
3545         //       same parameter types cannot be overloaded if any of them
3546         //       is a static member function declaration.
3547         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3548           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3549           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3550           return true;
3551         }
3552 
3553         // C++ [class.mem]p1:
3554         //   [...] A member shall not be declared twice in the
3555         //   member-specification, except that a nested class or member
3556         //   class template can be declared and then later defined.
3557         if (!inTemplateInstantiation()) {
3558           unsigned NewDiag;
3559           if (isa<CXXConstructorDecl>(OldMethod))
3560             NewDiag = diag::err_constructor_redeclared;
3561           else if (isa<CXXDestructorDecl>(NewMethod))
3562             NewDiag = diag::err_destructor_redeclared;
3563           else if (isa<CXXConversionDecl>(NewMethod))
3564             NewDiag = diag::err_conv_function_redeclared;
3565           else
3566             NewDiag = diag::err_member_redeclared;
3567 
3568           Diag(New->getLocation(), NewDiag);
3569         } else {
3570           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3571             << New << New->getType();
3572         }
3573         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3574         return true;
3575 
3576       // Complain if this is an explicit declaration of a special
3577       // member that was initially declared implicitly.
3578       //
3579       // As an exception, it's okay to befriend such methods in order
3580       // to permit the implicit constructor/destructor/operator calls.
3581       } else if (OldMethod->isImplicit()) {
3582         if (isFriend) {
3583           NewMethod->setImplicit();
3584         } else {
3585           Diag(NewMethod->getLocation(),
3586                diag::err_definition_of_implicitly_declared_member)
3587             << New << getSpecialMember(OldMethod);
3588           return true;
3589         }
3590       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3591         Diag(NewMethod->getLocation(),
3592              diag::err_definition_of_explicitly_defaulted_member)
3593           << getSpecialMember(OldMethod);
3594         return true;
3595       }
3596     }
3597 
3598     // C++11 [dcl.attr.noreturn]p1:
3599     //   The first declaration of a function shall specify the noreturn
3600     //   attribute if any declaration of that function specifies the noreturn
3601     //   attribute.
3602     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3603     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3604       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3605       Diag(Old->getFirstDecl()->getLocation(),
3606            diag::note_noreturn_missing_first_decl);
3607     }
3608 
3609     // C++11 [dcl.attr.depend]p2:
3610     //   The first declaration of a function shall specify the
3611     //   carries_dependency attribute for its declarator-id if any declaration
3612     //   of the function specifies the carries_dependency attribute.
3613     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3614     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3615       Diag(CDA->getLocation(),
3616            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3617       Diag(Old->getFirstDecl()->getLocation(),
3618            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3619     }
3620 
3621     // (C++98 8.3.5p3):
3622     //   All declarations for a function shall agree exactly in both the
3623     //   return type and the parameter-type-list.
3624     // We also want to respect all the extended bits except noreturn.
3625 
3626     // noreturn should now match unless the old type info didn't have it.
3627     QualType OldQTypeForComparison = OldQType;
3628     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3629       auto *OldType = OldQType->castAs<FunctionProtoType>();
3630       const FunctionType *OldTypeForComparison
3631         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3632       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3633       assert(OldQTypeForComparison.isCanonical());
3634     }
3635 
3636     if (haveIncompatibleLanguageLinkages(Old, New)) {
3637       // As a special case, retain the language linkage from previous
3638       // declarations of a friend function as an extension.
3639       //
3640       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3641       // and is useful because there's otherwise no way to specify language
3642       // linkage within class scope.
3643       //
3644       // Check cautiously as the friend object kind isn't yet complete.
3645       if (New->getFriendObjectKind() != Decl::FOK_None) {
3646         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3647         Diag(OldLocation, PrevDiag);
3648       } else {
3649         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3650         Diag(OldLocation, PrevDiag);
3651         return true;
3652       }
3653     }
3654 
3655     // If the function types are compatible, merge the declarations. Ignore the
3656     // exception specifier because it was already checked above in
3657     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3658     // about incompatible types under -fms-compatibility.
3659     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3660                                                          NewQType))
3661       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3662 
3663     // If the types are imprecise (due to dependent constructs in friends or
3664     // local extern declarations), it's OK if they differ. We'll check again
3665     // during instantiation.
3666     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3667       return false;
3668 
3669     // Fall through for conflicting redeclarations and redefinitions.
3670   }
3671 
3672   // C: Function types need to be compatible, not identical. This handles
3673   // duplicate function decls like "void f(int); void f(enum X);" properly.
3674   if (!getLangOpts().CPlusPlus &&
3675       Context.typesAreCompatible(OldQType, NewQType)) {
3676     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3677     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3678     const FunctionProtoType *OldProto = nullptr;
3679     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3680         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3681       // The old declaration provided a function prototype, but the
3682       // new declaration does not. Merge in the prototype.
3683       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3684       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3685       NewQType =
3686           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3687                                   OldProto->getExtProtoInfo());
3688       New->setType(NewQType);
3689       New->setHasInheritedPrototype();
3690 
3691       // Synthesize parameters with the same types.
3692       SmallVector<ParmVarDecl*, 16> Params;
3693       for (const auto &ParamType : OldProto->param_types()) {
3694         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3695                                                  SourceLocation(), nullptr,
3696                                                  ParamType, /*TInfo=*/nullptr,
3697                                                  SC_None, nullptr);
3698         Param->setScopeInfo(0, Params.size());
3699         Param->setImplicit();
3700         Params.push_back(Param);
3701       }
3702 
3703       New->setParams(Params);
3704     }
3705 
3706     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3707   }
3708 
3709   // Check if the function types are compatible when pointer size address
3710   // spaces are ignored.
3711   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3712     return false;
3713 
3714   // GNU C permits a K&R definition to follow a prototype declaration
3715   // if the declared types of the parameters in the K&R definition
3716   // match the types in the prototype declaration, even when the
3717   // promoted types of the parameters from the K&R definition differ
3718   // from the types in the prototype. GCC then keeps the types from
3719   // the prototype.
3720   //
3721   // If a variadic prototype is followed by a non-variadic K&R definition,
3722   // the K&R definition becomes variadic.  This is sort of an edge case, but
3723   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3724   // C99 6.9.1p8.
3725   if (!getLangOpts().CPlusPlus &&
3726       Old->hasPrototype() && !New->hasPrototype() &&
3727       New->getType()->getAs<FunctionProtoType>() &&
3728       Old->getNumParams() == New->getNumParams()) {
3729     SmallVector<QualType, 16> ArgTypes;
3730     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3731     const FunctionProtoType *OldProto
3732       = Old->getType()->getAs<FunctionProtoType>();
3733     const FunctionProtoType *NewProto
3734       = New->getType()->getAs<FunctionProtoType>();
3735 
3736     // Determine whether this is the GNU C extension.
3737     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3738                                                NewProto->getReturnType());
3739     bool LooseCompatible = !MergedReturn.isNull();
3740     for (unsigned Idx = 0, End = Old->getNumParams();
3741          LooseCompatible && Idx != End; ++Idx) {
3742       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3743       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3744       if (Context.typesAreCompatible(OldParm->getType(),
3745                                      NewProto->getParamType(Idx))) {
3746         ArgTypes.push_back(NewParm->getType());
3747       } else if (Context.typesAreCompatible(OldParm->getType(),
3748                                             NewParm->getType(),
3749                                             /*CompareUnqualified=*/true)) {
3750         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3751                                            NewProto->getParamType(Idx) };
3752         Warnings.push_back(Warn);
3753         ArgTypes.push_back(NewParm->getType());
3754       } else
3755         LooseCompatible = false;
3756     }
3757 
3758     if (LooseCompatible) {
3759       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3760         Diag(Warnings[Warn].NewParm->getLocation(),
3761              diag::ext_param_promoted_not_compatible_with_prototype)
3762           << Warnings[Warn].PromotedType
3763           << Warnings[Warn].OldParm->getType();
3764         if (Warnings[Warn].OldParm->getLocation().isValid())
3765           Diag(Warnings[Warn].OldParm->getLocation(),
3766                diag::note_previous_declaration);
3767       }
3768 
3769       if (MergeTypeWithOld)
3770         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3771                                              OldProto->getExtProtoInfo()));
3772       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3773     }
3774 
3775     // Fall through to diagnose conflicting types.
3776   }
3777 
3778   // A function that has already been declared has been redeclared or
3779   // defined with a different type; show an appropriate diagnostic.
3780 
3781   // If the previous declaration was an implicitly-generated builtin
3782   // declaration, then at the very least we should use a specialized note.
3783   unsigned BuiltinID;
3784   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3785     // If it's actually a library-defined builtin function like 'malloc'
3786     // or 'printf', just warn about the incompatible redeclaration.
3787     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3788       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3789       Diag(OldLocation, diag::note_previous_builtin_declaration)
3790         << Old << Old->getType();
3791       return false;
3792     }
3793 
3794     PrevDiag = diag::note_previous_builtin_declaration;
3795   }
3796 
3797   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3798   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3799   return true;
3800 }
3801 
3802 /// Completes the merge of two function declarations that are
3803 /// known to be compatible.
3804 ///
3805 /// This routine handles the merging of attributes and other
3806 /// properties of function declarations from the old declaration to
3807 /// the new declaration, once we know that New is in fact a
3808 /// redeclaration of Old.
3809 ///
3810 /// \returns false
3811 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3812                                         Scope *S, bool MergeTypeWithOld) {
3813   // Merge the attributes
3814   mergeDeclAttributes(New, Old);
3815 
3816   // Merge "pure" flag.
3817   if (Old->isPure())
3818     New->setPure();
3819 
3820   // Merge "used" flag.
3821   if (Old->getMostRecentDecl()->isUsed(false))
3822     New->setIsUsed();
3823 
3824   // Merge attributes from the parameters.  These can mismatch with K&R
3825   // declarations.
3826   if (New->getNumParams() == Old->getNumParams())
3827       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3828         ParmVarDecl *NewParam = New->getParamDecl(i);
3829         ParmVarDecl *OldParam = Old->getParamDecl(i);
3830         mergeParamDeclAttributes(NewParam, OldParam, *this);
3831         mergeParamDeclTypes(NewParam, OldParam, *this);
3832       }
3833 
3834   if (getLangOpts().CPlusPlus)
3835     return MergeCXXFunctionDecl(New, Old, S);
3836 
3837   // Merge the function types so the we get the composite types for the return
3838   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3839   // was visible.
3840   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3841   if (!Merged.isNull() && MergeTypeWithOld)
3842     New->setType(Merged);
3843 
3844   return false;
3845 }
3846 
3847 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3848                                 ObjCMethodDecl *oldMethod) {
3849   // Merge the attributes, including deprecated/unavailable
3850   AvailabilityMergeKind MergeKind =
3851     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3852       ? AMK_ProtocolImplementation
3853       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3854                                                        : AMK_Override;
3855 
3856   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3857 
3858   // Merge attributes from the parameters.
3859   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3860                                        oe = oldMethod->param_end();
3861   for (ObjCMethodDecl::param_iterator
3862          ni = newMethod->param_begin(), ne = newMethod->param_end();
3863        ni != ne && oi != oe; ++ni, ++oi)
3864     mergeParamDeclAttributes(*ni, *oi, *this);
3865 
3866   CheckObjCMethodOverride(newMethod, oldMethod);
3867 }
3868 
3869 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3870   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3871 
3872   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3873          ? diag::err_redefinition_different_type
3874          : diag::err_redeclaration_different_type)
3875     << New->getDeclName() << New->getType() << Old->getType();
3876 
3877   diag::kind PrevDiag;
3878   SourceLocation OldLocation;
3879   std::tie(PrevDiag, OldLocation)
3880     = getNoteDiagForInvalidRedeclaration(Old, New);
3881   S.Diag(OldLocation, PrevDiag);
3882   New->setInvalidDecl();
3883 }
3884 
3885 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3886 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3887 /// emitting diagnostics as appropriate.
3888 ///
3889 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3890 /// to here in AddInitializerToDecl. We can't check them before the initializer
3891 /// is attached.
3892 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3893                              bool MergeTypeWithOld) {
3894   if (New->isInvalidDecl() || Old->isInvalidDecl())
3895     return;
3896 
3897   QualType MergedT;
3898   if (getLangOpts().CPlusPlus) {
3899     if (New->getType()->isUndeducedType()) {
3900       // We don't know what the new type is until the initializer is attached.
3901       return;
3902     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3903       // These could still be something that needs exception specs checked.
3904       return MergeVarDeclExceptionSpecs(New, Old);
3905     }
3906     // C++ [basic.link]p10:
3907     //   [...] the types specified by all declarations referring to a given
3908     //   object or function shall be identical, except that declarations for an
3909     //   array object can specify array types that differ by the presence or
3910     //   absence of a major array bound (8.3.4).
3911     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3912       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3913       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3914 
3915       // We are merging a variable declaration New into Old. If it has an array
3916       // bound, and that bound differs from Old's bound, we should diagnose the
3917       // mismatch.
3918       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3919         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3920              PrevVD = PrevVD->getPreviousDecl()) {
3921           QualType PrevVDTy = PrevVD->getType();
3922           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3923             continue;
3924 
3925           if (!Context.hasSameType(New->getType(), PrevVDTy))
3926             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3927         }
3928       }
3929 
3930       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3931         if (Context.hasSameType(OldArray->getElementType(),
3932                                 NewArray->getElementType()))
3933           MergedT = New->getType();
3934       }
3935       // FIXME: Check visibility. New is hidden but has a complete type. If New
3936       // has no array bound, it should not inherit one from Old, if Old is not
3937       // visible.
3938       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3939         if (Context.hasSameType(OldArray->getElementType(),
3940                                 NewArray->getElementType()))
3941           MergedT = Old->getType();
3942       }
3943     }
3944     else if (New->getType()->isObjCObjectPointerType() &&
3945                Old->getType()->isObjCObjectPointerType()) {
3946       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3947                                               Old->getType());
3948     }
3949   } else {
3950     // C 6.2.7p2:
3951     //   All declarations that refer to the same object or function shall have
3952     //   compatible type.
3953     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3954   }
3955   if (MergedT.isNull()) {
3956     // It's OK if we couldn't merge types if either type is dependent, for a
3957     // block-scope variable. In other cases (static data members of class
3958     // templates, variable templates, ...), we require the types to be
3959     // equivalent.
3960     // FIXME: The C++ standard doesn't say anything about this.
3961     if ((New->getType()->isDependentType() ||
3962          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3963       // If the old type was dependent, we can't merge with it, so the new type
3964       // becomes dependent for now. We'll reproduce the original type when we
3965       // instantiate the TypeSourceInfo for the variable.
3966       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3967         New->setType(Context.DependentTy);
3968       return;
3969     }
3970     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3971   }
3972 
3973   // Don't actually update the type on the new declaration if the old
3974   // declaration was an extern declaration in a different scope.
3975   if (MergeTypeWithOld)
3976     New->setType(MergedT);
3977 }
3978 
3979 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3980                                   LookupResult &Previous) {
3981   // C11 6.2.7p4:
3982   //   For an identifier with internal or external linkage declared
3983   //   in a scope in which a prior declaration of that identifier is
3984   //   visible, if the prior declaration specifies internal or
3985   //   external linkage, the type of the identifier at the later
3986   //   declaration becomes the composite type.
3987   //
3988   // If the variable isn't visible, we do not merge with its type.
3989   if (Previous.isShadowed())
3990     return false;
3991 
3992   if (S.getLangOpts().CPlusPlus) {
3993     // C++11 [dcl.array]p3:
3994     //   If there is a preceding declaration of the entity in the same
3995     //   scope in which the bound was specified, an omitted array bound
3996     //   is taken to be the same as in that earlier declaration.
3997     return NewVD->isPreviousDeclInSameBlockScope() ||
3998            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3999             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4000   } else {
4001     // If the old declaration was function-local, don't merge with its
4002     // type unless we're in the same function.
4003     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4004            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4005   }
4006 }
4007 
4008 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4009 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4010 /// situation, merging decls or emitting diagnostics as appropriate.
4011 ///
4012 /// Tentative definition rules (C99 6.9.2p2) are checked by
4013 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4014 /// definitions here, since the initializer hasn't been attached.
4015 ///
4016 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4017   // If the new decl is already invalid, don't do any other checking.
4018   if (New->isInvalidDecl())
4019     return;
4020 
4021   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4022     return;
4023 
4024   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4025 
4026   // Verify the old decl was also a variable or variable template.
4027   VarDecl *Old = nullptr;
4028   VarTemplateDecl *OldTemplate = nullptr;
4029   if (Previous.isSingleResult()) {
4030     if (NewTemplate) {
4031       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4032       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4033 
4034       if (auto *Shadow =
4035               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4036         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4037           return New->setInvalidDecl();
4038     } else {
4039       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4040 
4041       if (auto *Shadow =
4042               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4043         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4044           return New->setInvalidDecl();
4045     }
4046   }
4047   if (!Old) {
4048     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4049         << New->getDeclName();
4050     notePreviousDefinition(Previous.getRepresentativeDecl(),
4051                            New->getLocation());
4052     return New->setInvalidDecl();
4053   }
4054 
4055   // Ensure the template parameters are compatible.
4056   if (NewTemplate &&
4057       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4058                                       OldTemplate->getTemplateParameters(),
4059                                       /*Complain=*/true, TPL_TemplateMatch))
4060     return New->setInvalidDecl();
4061 
4062   // C++ [class.mem]p1:
4063   //   A member shall not be declared twice in the member-specification [...]
4064   //
4065   // Here, we need only consider static data members.
4066   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4067     Diag(New->getLocation(), diag::err_duplicate_member)
4068       << New->getIdentifier();
4069     Diag(Old->getLocation(), diag::note_previous_declaration);
4070     New->setInvalidDecl();
4071   }
4072 
4073   mergeDeclAttributes(New, Old);
4074   // Warn if an already-declared variable is made a weak_import in a subsequent
4075   // declaration
4076   if (New->hasAttr<WeakImportAttr>() &&
4077       Old->getStorageClass() == SC_None &&
4078       !Old->hasAttr<WeakImportAttr>()) {
4079     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4080     notePreviousDefinition(Old, New->getLocation());
4081     // Remove weak_import attribute on new declaration.
4082     New->dropAttr<WeakImportAttr>();
4083   }
4084 
4085   if (New->hasAttr<InternalLinkageAttr>() &&
4086       !Old->hasAttr<InternalLinkageAttr>()) {
4087     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4088         << New->getDeclName();
4089     notePreviousDefinition(Old, New->getLocation());
4090     New->dropAttr<InternalLinkageAttr>();
4091   }
4092 
4093   // Merge the types.
4094   VarDecl *MostRecent = Old->getMostRecentDecl();
4095   if (MostRecent != Old) {
4096     MergeVarDeclTypes(New, MostRecent,
4097                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4098     if (New->isInvalidDecl())
4099       return;
4100   }
4101 
4102   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4103   if (New->isInvalidDecl())
4104     return;
4105 
4106   diag::kind PrevDiag;
4107   SourceLocation OldLocation;
4108   std::tie(PrevDiag, OldLocation) =
4109       getNoteDiagForInvalidRedeclaration(Old, New);
4110 
4111   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4112   if (New->getStorageClass() == SC_Static &&
4113       !New->isStaticDataMember() &&
4114       Old->hasExternalFormalLinkage()) {
4115     if (getLangOpts().MicrosoftExt) {
4116       Diag(New->getLocation(), diag::ext_static_non_static)
4117           << New->getDeclName();
4118       Diag(OldLocation, PrevDiag);
4119     } else {
4120       Diag(New->getLocation(), diag::err_static_non_static)
4121           << New->getDeclName();
4122       Diag(OldLocation, PrevDiag);
4123       return New->setInvalidDecl();
4124     }
4125   }
4126   // C99 6.2.2p4:
4127   //   For an identifier declared with the storage-class specifier
4128   //   extern in a scope in which a prior declaration of that
4129   //   identifier is visible,23) if the prior declaration specifies
4130   //   internal or external linkage, the linkage of the identifier at
4131   //   the later declaration is the same as the linkage specified at
4132   //   the prior declaration. If no prior declaration is visible, or
4133   //   if the prior declaration specifies no linkage, then the
4134   //   identifier has external linkage.
4135   if (New->hasExternalStorage() && Old->hasLinkage())
4136     /* Okay */;
4137   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4138            !New->isStaticDataMember() &&
4139            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4140     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4141     Diag(OldLocation, PrevDiag);
4142     return New->setInvalidDecl();
4143   }
4144 
4145   // Check if extern is followed by non-extern and vice-versa.
4146   if (New->hasExternalStorage() &&
4147       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4148     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4149     Diag(OldLocation, PrevDiag);
4150     return New->setInvalidDecl();
4151   }
4152   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4153       !New->hasExternalStorage()) {
4154     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4155     Diag(OldLocation, PrevDiag);
4156     return New->setInvalidDecl();
4157   }
4158 
4159   if (CheckRedeclarationModuleOwnership(New, Old))
4160     return;
4161 
4162   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4163 
4164   // FIXME: The test for external storage here seems wrong? We still
4165   // need to check for mismatches.
4166   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4167       // Don't complain about out-of-line definitions of static members.
4168       !(Old->getLexicalDeclContext()->isRecord() &&
4169         !New->getLexicalDeclContext()->isRecord())) {
4170     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4171     Diag(OldLocation, PrevDiag);
4172     return New->setInvalidDecl();
4173   }
4174 
4175   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4176     if (VarDecl *Def = Old->getDefinition()) {
4177       // C++1z [dcl.fcn.spec]p4:
4178       //   If the definition of a variable appears in a translation unit before
4179       //   its first declaration as inline, the program is ill-formed.
4180       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4181       Diag(Def->getLocation(), diag::note_previous_definition);
4182     }
4183   }
4184 
4185   // If this redeclaration makes the variable inline, we may need to add it to
4186   // UndefinedButUsed.
4187   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4188       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4189     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4190                                            SourceLocation()));
4191 
4192   if (New->getTLSKind() != Old->getTLSKind()) {
4193     if (!Old->getTLSKind()) {
4194       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4195       Diag(OldLocation, PrevDiag);
4196     } else if (!New->getTLSKind()) {
4197       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4198       Diag(OldLocation, PrevDiag);
4199     } else {
4200       // Do not allow redeclaration to change the variable between requiring
4201       // static and dynamic initialization.
4202       // FIXME: GCC allows this, but uses the TLS keyword on the first
4203       // declaration to determine the kind. Do we need to be compatible here?
4204       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4205         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4206       Diag(OldLocation, PrevDiag);
4207     }
4208   }
4209 
4210   // C++ doesn't have tentative definitions, so go right ahead and check here.
4211   if (getLangOpts().CPlusPlus &&
4212       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4213     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4214         Old->getCanonicalDecl()->isConstexpr()) {
4215       // This definition won't be a definition any more once it's been merged.
4216       Diag(New->getLocation(),
4217            diag::warn_deprecated_redundant_constexpr_static_def);
4218     } else if (VarDecl *Def = Old->getDefinition()) {
4219       if (checkVarDeclRedefinition(Def, New))
4220         return;
4221     }
4222   }
4223 
4224   if (haveIncompatibleLanguageLinkages(Old, New)) {
4225     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4226     Diag(OldLocation, PrevDiag);
4227     New->setInvalidDecl();
4228     return;
4229   }
4230 
4231   // Merge "used" flag.
4232   if (Old->getMostRecentDecl()->isUsed(false))
4233     New->setIsUsed();
4234 
4235   // Keep a chain of previous declarations.
4236   New->setPreviousDecl(Old);
4237   if (NewTemplate)
4238     NewTemplate->setPreviousDecl(OldTemplate);
4239   adjustDeclContextForDeclaratorDecl(New, Old);
4240 
4241   // Inherit access appropriately.
4242   New->setAccess(Old->getAccess());
4243   if (NewTemplate)
4244     NewTemplate->setAccess(New->getAccess());
4245 
4246   if (Old->isInline())
4247     New->setImplicitlyInline();
4248 }
4249 
4250 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4251   SourceManager &SrcMgr = getSourceManager();
4252   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4253   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4254   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4255   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4256   auto &HSI = PP.getHeaderSearchInfo();
4257   StringRef HdrFilename =
4258       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4259 
4260   auto noteFromModuleOrInclude = [&](Module *Mod,
4261                                      SourceLocation IncLoc) -> bool {
4262     // Redefinition errors with modules are common with non modular mapped
4263     // headers, example: a non-modular header H in module A that also gets
4264     // included directly in a TU. Pointing twice to the same header/definition
4265     // is confusing, try to get better diagnostics when modules is on.
4266     if (IncLoc.isValid()) {
4267       if (Mod) {
4268         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4269             << HdrFilename.str() << Mod->getFullModuleName();
4270         if (!Mod->DefinitionLoc.isInvalid())
4271           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4272               << Mod->getFullModuleName();
4273       } else {
4274         Diag(IncLoc, diag::note_redefinition_include_same_file)
4275             << HdrFilename.str();
4276       }
4277       return true;
4278     }
4279 
4280     return false;
4281   };
4282 
4283   // Is it the same file and same offset? Provide more information on why
4284   // this leads to a redefinition error.
4285   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4286     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4287     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4288     bool EmittedDiag =
4289         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4290     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4291 
4292     // If the header has no guards, emit a note suggesting one.
4293     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4294       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4295 
4296     if (EmittedDiag)
4297       return;
4298   }
4299 
4300   // Redefinition coming from different files or couldn't do better above.
4301   if (Old->getLocation().isValid())
4302     Diag(Old->getLocation(), diag::note_previous_definition);
4303 }
4304 
4305 /// We've just determined that \p Old and \p New both appear to be definitions
4306 /// of the same variable. Either diagnose or fix the problem.
4307 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4308   if (!hasVisibleDefinition(Old) &&
4309       (New->getFormalLinkage() == InternalLinkage ||
4310        New->isInline() ||
4311        New->getDescribedVarTemplate() ||
4312        New->getNumTemplateParameterLists() ||
4313        New->getDeclContext()->isDependentContext())) {
4314     // The previous definition is hidden, and multiple definitions are
4315     // permitted (in separate TUs). Demote this to a declaration.
4316     New->demoteThisDefinitionToDeclaration();
4317 
4318     // Make the canonical definition visible.
4319     if (auto *OldTD = Old->getDescribedVarTemplate())
4320       makeMergedDefinitionVisible(OldTD);
4321     makeMergedDefinitionVisible(Old);
4322     return false;
4323   } else {
4324     Diag(New->getLocation(), diag::err_redefinition) << New;
4325     notePreviousDefinition(Old, New->getLocation());
4326     New->setInvalidDecl();
4327     return true;
4328   }
4329 }
4330 
4331 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4332 /// no declarator (e.g. "struct foo;") is parsed.
4333 Decl *
4334 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4335                                  RecordDecl *&AnonRecord) {
4336   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4337                                     AnonRecord);
4338 }
4339 
4340 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4341 // disambiguate entities defined in different scopes.
4342 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4343 // compatibility.
4344 // We will pick our mangling number depending on which version of MSVC is being
4345 // targeted.
4346 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4347   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4348              ? S->getMSCurManglingNumber()
4349              : S->getMSLastManglingNumber();
4350 }
4351 
4352 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4353   if (!Context.getLangOpts().CPlusPlus)
4354     return;
4355 
4356   if (isa<CXXRecordDecl>(Tag->getParent())) {
4357     // If this tag is the direct child of a class, number it if
4358     // it is anonymous.
4359     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4360       return;
4361     MangleNumberingContext &MCtx =
4362         Context.getManglingNumberContext(Tag->getParent());
4363     Context.setManglingNumber(
4364         Tag, MCtx.getManglingNumber(
4365                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4366     return;
4367   }
4368 
4369   // If this tag isn't a direct child of a class, number it if it is local.
4370   MangleNumberingContext *MCtx;
4371   Decl *ManglingContextDecl;
4372   std::tie(MCtx, ManglingContextDecl) =
4373       getCurrentMangleNumberContext(Tag->getDeclContext());
4374   if (MCtx) {
4375     Context.setManglingNumber(
4376         Tag, MCtx->getManglingNumber(
4377                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4378   }
4379 }
4380 
4381 namespace {
4382 struct NonCLikeKind {
4383   enum {
4384     None,
4385     BaseClass,
4386     DefaultMemberInit,
4387     Lambda,
4388     Friend,
4389     OtherMember,
4390     Invalid,
4391   } Kind = None;
4392   SourceRange Range;
4393 
4394   explicit operator bool() { return Kind != None; }
4395 };
4396 }
4397 
4398 /// Determine whether a class is C-like, according to the rules of C++
4399 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4400 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4401   if (RD->isInvalidDecl())
4402     return {NonCLikeKind::Invalid, {}};
4403 
4404   // C++ [dcl.typedef]p9: [P1766R1]
4405   //   An unnamed class with a typedef name for linkage purposes shall not
4406   //
4407   //    -- have any base classes
4408   if (RD->getNumBases())
4409     return {NonCLikeKind::BaseClass,
4410             SourceRange(RD->bases_begin()->getBeginLoc(),
4411                         RD->bases_end()[-1].getEndLoc())};
4412   bool Invalid = false;
4413   for (Decl *D : RD->decls()) {
4414     // Don't complain about things we already diagnosed.
4415     if (D->isInvalidDecl()) {
4416       Invalid = true;
4417       continue;
4418     }
4419 
4420     //  -- have any [...] default member initializers
4421     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4422       if (FD->hasInClassInitializer()) {
4423         auto *Init = FD->getInClassInitializer();
4424         return {NonCLikeKind::DefaultMemberInit,
4425                 Init ? Init->getSourceRange() : D->getSourceRange()};
4426       }
4427       continue;
4428     }
4429 
4430     // FIXME: We don't allow friend declarations. This violates the wording of
4431     // P1766, but not the intent.
4432     if (isa<FriendDecl>(D))
4433       return {NonCLikeKind::Friend, D->getSourceRange()};
4434 
4435     //  -- declare any members other than non-static data members, member
4436     //     enumerations, or member classes,
4437     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4438         isa<EnumDecl>(D))
4439       continue;
4440     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4441     if (!MemberRD) {
4442       if (D->isImplicit())
4443         continue;
4444       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4445     }
4446 
4447     //  -- contain a lambda-expression,
4448     if (MemberRD->isLambda())
4449       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4450 
4451     //  and all member classes shall also satisfy these requirements
4452     //  (recursively).
4453     if (MemberRD->isThisDeclarationADefinition()) {
4454       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4455         return Kind;
4456     }
4457   }
4458 
4459   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4460 }
4461 
4462 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4463                                         TypedefNameDecl *NewTD) {
4464   if (TagFromDeclSpec->isInvalidDecl())
4465     return;
4466 
4467   // Do nothing if the tag already has a name for linkage purposes.
4468   if (TagFromDeclSpec->hasNameForLinkage())
4469     return;
4470 
4471   // A well-formed anonymous tag must always be a TUK_Definition.
4472   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4473 
4474   // The type must match the tag exactly;  no qualifiers allowed.
4475   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4476                            Context.getTagDeclType(TagFromDeclSpec))) {
4477     if (getLangOpts().CPlusPlus)
4478       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4479     return;
4480   }
4481 
4482   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4483   //   An unnamed class with a typedef name for linkage purposes shall [be
4484   //   C-like].
4485   //
4486   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4487   // shouldn't happen, but there are constructs that the language rule doesn't
4488   // disallow for which we can't reasonably avoid computing linkage early.
4489   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4490   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4491                              : NonCLikeKind();
4492   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4493   if (NonCLike || ChangesLinkage) {
4494     if (NonCLike.Kind == NonCLikeKind::Invalid)
4495       return;
4496 
4497     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4498     if (ChangesLinkage) {
4499       // If the linkage changes, we can't accept this as an extension.
4500       if (NonCLike.Kind == NonCLikeKind::None)
4501         DiagID = diag::err_typedef_changes_linkage;
4502       else
4503         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4504     }
4505 
4506     SourceLocation FixitLoc =
4507         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4508     llvm::SmallString<40> TextToInsert;
4509     TextToInsert += ' ';
4510     TextToInsert += NewTD->getIdentifier()->getName();
4511 
4512     Diag(FixitLoc, DiagID)
4513       << isa<TypeAliasDecl>(NewTD)
4514       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4515     if (NonCLike.Kind != NonCLikeKind::None) {
4516       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4517         << NonCLike.Kind - 1 << NonCLike.Range;
4518     }
4519     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4520       << NewTD << isa<TypeAliasDecl>(NewTD);
4521 
4522     if (ChangesLinkage)
4523       return;
4524   }
4525 
4526   // Otherwise, set this as the anon-decl typedef for the tag.
4527   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4528 }
4529 
4530 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4531   switch (T) {
4532   case DeclSpec::TST_class:
4533     return 0;
4534   case DeclSpec::TST_struct:
4535     return 1;
4536   case DeclSpec::TST_interface:
4537     return 2;
4538   case DeclSpec::TST_union:
4539     return 3;
4540   case DeclSpec::TST_enum:
4541     return 4;
4542   default:
4543     llvm_unreachable("unexpected type specifier");
4544   }
4545 }
4546 
4547 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4548 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4549 /// parameters to cope with template friend declarations.
4550 Decl *
4551 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4552                                  MultiTemplateParamsArg TemplateParams,
4553                                  bool IsExplicitInstantiation,
4554                                  RecordDecl *&AnonRecord) {
4555   Decl *TagD = nullptr;
4556   TagDecl *Tag = nullptr;
4557   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4558       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4559       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4560       DS.getTypeSpecType() == DeclSpec::TST_union ||
4561       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4562     TagD = DS.getRepAsDecl();
4563 
4564     if (!TagD) // We probably had an error
4565       return nullptr;
4566 
4567     // Note that the above type specs guarantee that the
4568     // type rep is a Decl, whereas in many of the others
4569     // it's a Type.
4570     if (isa<TagDecl>(TagD))
4571       Tag = cast<TagDecl>(TagD);
4572     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4573       Tag = CTD->getTemplatedDecl();
4574   }
4575 
4576   if (Tag) {
4577     handleTagNumbering(Tag, S);
4578     Tag->setFreeStanding();
4579     if (Tag->isInvalidDecl())
4580       return Tag;
4581   }
4582 
4583   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4584     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4585     // or incomplete types shall not be restrict-qualified."
4586     if (TypeQuals & DeclSpec::TQ_restrict)
4587       Diag(DS.getRestrictSpecLoc(),
4588            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4589            << DS.getSourceRange();
4590   }
4591 
4592   if (DS.isInlineSpecified())
4593     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4594         << getLangOpts().CPlusPlus17;
4595 
4596   if (DS.hasConstexprSpecifier()) {
4597     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4598     // and definitions of functions and variables.
4599     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4600     // the declaration of a function or function template
4601     if (Tag)
4602       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4603           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4604           << DS.getConstexprSpecifier();
4605     else
4606       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4607           << DS.getConstexprSpecifier();
4608     // Don't emit warnings after this error.
4609     return TagD;
4610   }
4611 
4612   DiagnoseFunctionSpecifiers(DS);
4613 
4614   if (DS.isFriendSpecified()) {
4615     // If we're dealing with a decl but not a TagDecl, assume that
4616     // whatever routines created it handled the friendship aspect.
4617     if (TagD && !Tag)
4618       return nullptr;
4619     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4620   }
4621 
4622   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4623   bool IsExplicitSpecialization =
4624     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4625   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4626       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4627       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4628     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4629     // nested-name-specifier unless it is an explicit instantiation
4630     // or an explicit specialization.
4631     //
4632     // FIXME: We allow class template partial specializations here too, per the
4633     // obvious intent of DR1819.
4634     //
4635     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4636     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4637         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4638     return nullptr;
4639   }
4640 
4641   // Track whether this decl-specifier declares anything.
4642   bool DeclaresAnything = true;
4643 
4644   // Handle anonymous struct definitions.
4645   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4646     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4647         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4648       if (getLangOpts().CPlusPlus ||
4649           Record->getDeclContext()->isRecord()) {
4650         // If CurContext is a DeclContext that can contain statements,
4651         // RecursiveASTVisitor won't visit the decls that
4652         // BuildAnonymousStructOrUnion() will put into CurContext.
4653         // Also store them here so that they can be part of the
4654         // DeclStmt that gets created in this case.
4655         // FIXME: Also return the IndirectFieldDecls created by
4656         // BuildAnonymousStructOr union, for the same reason?
4657         if (CurContext->isFunctionOrMethod())
4658           AnonRecord = Record;
4659         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4660                                            Context.getPrintingPolicy());
4661       }
4662 
4663       DeclaresAnything = false;
4664     }
4665   }
4666 
4667   // C11 6.7.2.1p2:
4668   //   A struct-declaration that does not declare an anonymous structure or
4669   //   anonymous union shall contain a struct-declarator-list.
4670   //
4671   // This rule also existed in C89 and C99; the grammar for struct-declaration
4672   // did not permit a struct-declaration without a struct-declarator-list.
4673   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4674       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4675     // Check for Microsoft C extension: anonymous struct/union member.
4676     // Handle 2 kinds of anonymous struct/union:
4677     //   struct STRUCT;
4678     //   union UNION;
4679     // and
4680     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4681     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4682     if ((Tag && Tag->getDeclName()) ||
4683         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4684       RecordDecl *Record = nullptr;
4685       if (Tag)
4686         Record = dyn_cast<RecordDecl>(Tag);
4687       else if (const RecordType *RT =
4688                    DS.getRepAsType().get()->getAsStructureType())
4689         Record = RT->getDecl();
4690       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4691         Record = UT->getDecl();
4692 
4693       if (Record && getLangOpts().MicrosoftExt) {
4694         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4695             << Record->isUnion() << DS.getSourceRange();
4696         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4697       }
4698 
4699       DeclaresAnything = false;
4700     }
4701   }
4702 
4703   // Skip all the checks below if we have a type error.
4704   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4705       (TagD && TagD->isInvalidDecl()))
4706     return TagD;
4707 
4708   if (getLangOpts().CPlusPlus &&
4709       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4710     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4711       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4712           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4713         DeclaresAnything = false;
4714 
4715   if (!DS.isMissingDeclaratorOk()) {
4716     // Customize diagnostic for a typedef missing a name.
4717     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4718       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4719           << DS.getSourceRange();
4720     else
4721       DeclaresAnything = false;
4722   }
4723 
4724   if (DS.isModulePrivateSpecified() &&
4725       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4726     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4727       << Tag->getTagKind()
4728       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4729 
4730   ActOnDocumentableDecl(TagD);
4731 
4732   // C 6.7/2:
4733   //   A declaration [...] shall declare at least a declarator [...], a tag,
4734   //   or the members of an enumeration.
4735   // C++ [dcl.dcl]p3:
4736   //   [If there are no declarators], and except for the declaration of an
4737   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4738   //   names into the program, or shall redeclare a name introduced by a
4739   //   previous declaration.
4740   if (!DeclaresAnything) {
4741     // In C, we allow this as a (popular) extension / bug. Don't bother
4742     // producing further diagnostics for redundant qualifiers after this.
4743     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4744                                ? diag::err_no_declarators
4745                                : diag::ext_no_declarators)
4746         << DS.getSourceRange();
4747     return TagD;
4748   }
4749 
4750   // C++ [dcl.stc]p1:
4751   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4752   //   init-declarator-list of the declaration shall not be empty.
4753   // C++ [dcl.fct.spec]p1:
4754   //   If a cv-qualifier appears in a decl-specifier-seq, the
4755   //   init-declarator-list of the declaration shall not be empty.
4756   //
4757   // Spurious qualifiers here appear to be valid in C.
4758   unsigned DiagID = diag::warn_standalone_specifier;
4759   if (getLangOpts().CPlusPlus)
4760     DiagID = diag::ext_standalone_specifier;
4761 
4762   // Note that a linkage-specification sets a storage class, but
4763   // 'extern "C" struct foo;' is actually valid and not theoretically
4764   // useless.
4765   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4766     if (SCS == DeclSpec::SCS_mutable)
4767       // Since mutable is not a viable storage class specifier in C, there is
4768       // no reason to treat it as an extension. Instead, diagnose as an error.
4769       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4770     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4771       Diag(DS.getStorageClassSpecLoc(), DiagID)
4772         << DeclSpec::getSpecifierName(SCS);
4773   }
4774 
4775   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4776     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4777       << DeclSpec::getSpecifierName(TSCS);
4778   if (DS.getTypeQualifiers()) {
4779     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4780       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4781     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4782       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4783     // Restrict is covered above.
4784     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4785       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4786     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4787       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4788   }
4789 
4790   // Warn about ignored type attributes, for example:
4791   // __attribute__((aligned)) struct A;
4792   // Attributes should be placed after tag to apply to type declaration.
4793   if (!DS.getAttributes().empty()) {
4794     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4795     if (TypeSpecType == DeclSpec::TST_class ||
4796         TypeSpecType == DeclSpec::TST_struct ||
4797         TypeSpecType == DeclSpec::TST_interface ||
4798         TypeSpecType == DeclSpec::TST_union ||
4799         TypeSpecType == DeclSpec::TST_enum) {
4800       for (const ParsedAttr &AL : DS.getAttributes())
4801         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4802             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4803     }
4804   }
4805 
4806   return TagD;
4807 }
4808 
4809 /// We are trying to inject an anonymous member into the given scope;
4810 /// check if there's an existing declaration that can't be overloaded.
4811 ///
4812 /// \return true if this is a forbidden redeclaration
4813 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4814                                          Scope *S,
4815                                          DeclContext *Owner,
4816                                          DeclarationName Name,
4817                                          SourceLocation NameLoc,
4818                                          bool IsUnion) {
4819   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4820                  Sema::ForVisibleRedeclaration);
4821   if (!SemaRef.LookupName(R, S)) return false;
4822 
4823   // Pick a representative declaration.
4824   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4825   assert(PrevDecl && "Expected a non-null Decl");
4826 
4827   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4828     return false;
4829 
4830   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4831     << IsUnion << Name;
4832   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4833 
4834   return true;
4835 }
4836 
4837 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4838 /// anonymous struct or union AnonRecord into the owning context Owner
4839 /// and scope S. This routine will be invoked just after we realize
4840 /// that an unnamed union or struct is actually an anonymous union or
4841 /// struct, e.g.,
4842 ///
4843 /// @code
4844 /// union {
4845 ///   int i;
4846 ///   float f;
4847 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4848 ///    // f into the surrounding scope.x
4849 /// @endcode
4850 ///
4851 /// This routine is recursive, injecting the names of nested anonymous
4852 /// structs/unions into the owning context and scope as well.
4853 static bool
4854 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4855                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4856                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4857   bool Invalid = false;
4858 
4859   // Look every FieldDecl and IndirectFieldDecl with a name.
4860   for (auto *D : AnonRecord->decls()) {
4861     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4862         cast<NamedDecl>(D)->getDeclName()) {
4863       ValueDecl *VD = cast<ValueDecl>(D);
4864       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4865                                        VD->getLocation(),
4866                                        AnonRecord->isUnion())) {
4867         // C++ [class.union]p2:
4868         //   The names of the members of an anonymous union shall be
4869         //   distinct from the names of any other entity in the
4870         //   scope in which the anonymous union is declared.
4871         Invalid = true;
4872       } else {
4873         // C++ [class.union]p2:
4874         //   For the purpose of name lookup, after the anonymous union
4875         //   definition, the members of the anonymous union are
4876         //   considered to have been defined in the scope in which the
4877         //   anonymous union is declared.
4878         unsigned OldChainingSize = Chaining.size();
4879         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4880           Chaining.append(IF->chain_begin(), IF->chain_end());
4881         else
4882           Chaining.push_back(VD);
4883 
4884         assert(Chaining.size() >= 2);
4885         NamedDecl **NamedChain =
4886           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4887         for (unsigned i = 0; i < Chaining.size(); i++)
4888           NamedChain[i] = Chaining[i];
4889 
4890         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4891             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4892             VD->getType(), {NamedChain, Chaining.size()});
4893 
4894         for (const auto *Attr : VD->attrs())
4895           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4896 
4897         IndirectField->setAccess(AS);
4898         IndirectField->setImplicit();
4899         SemaRef.PushOnScopeChains(IndirectField, S);
4900 
4901         // That includes picking up the appropriate access specifier.
4902         if (AS != AS_none) IndirectField->setAccess(AS);
4903 
4904         Chaining.resize(OldChainingSize);
4905       }
4906     }
4907   }
4908 
4909   return Invalid;
4910 }
4911 
4912 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4913 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4914 /// illegal input values are mapped to SC_None.
4915 static StorageClass
4916 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4917   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4918   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4919          "Parser allowed 'typedef' as storage class VarDecl.");
4920   switch (StorageClassSpec) {
4921   case DeclSpec::SCS_unspecified:    return SC_None;
4922   case DeclSpec::SCS_extern:
4923     if (DS.isExternInLinkageSpec())
4924       return SC_None;
4925     return SC_Extern;
4926   case DeclSpec::SCS_static:         return SC_Static;
4927   case DeclSpec::SCS_auto:           return SC_Auto;
4928   case DeclSpec::SCS_register:       return SC_Register;
4929   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4930     // Illegal SCSs map to None: error reporting is up to the caller.
4931   case DeclSpec::SCS_mutable:        // Fall through.
4932   case DeclSpec::SCS_typedef:        return SC_None;
4933   }
4934   llvm_unreachable("unknown storage class specifier");
4935 }
4936 
4937 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4938   assert(Record->hasInClassInitializer());
4939 
4940   for (const auto *I : Record->decls()) {
4941     const auto *FD = dyn_cast<FieldDecl>(I);
4942     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4943       FD = IFD->getAnonField();
4944     if (FD && FD->hasInClassInitializer())
4945       return FD->getLocation();
4946   }
4947 
4948   llvm_unreachable("couldn't find in-class initializer");
4949 }
4950 
4951 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4952                                       SourceLocation DefaultInitLoc) {
4953   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4954     return;
4955 
4956   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4957   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4958 }
4959 
4960 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4961                                       CXXRecordDecl *AnonUnion) {
4962   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4963     return;
4964 
4965   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4966 }
4967 
4968 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4969 /// anonymous structure or union. Anonymous unions are a C++ feature
4970 /// (C++ [class.union]) and a C11 feature; anonymous structures
4971 /// are a C11 feature and GNU C++ extension.
4972 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4973                                         AccessSpecifier AS,
4974                                         RecordDecl *Record,
4975                                         const PrintingPolicy &Policy) {
4976   DeclContext *Owner = Record->getDeclContext();
4977 
4978   // Diagnose whether this anonymous struct/union is an extension.
4979   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4980     Diag(Record->getLocation(), diag::ext_anonymous_union);
4981   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4982     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4983   else if (!Record->isUnion() && !getLangOpts().C11)
4984     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4985 
4986   // C and C++ require different kinds of checks for anonymous
4987   // structs/unions.
4988   bool Invalid = false;
4989   if (getLangOpts().CPlusPlus) {
4990     const char *PrevSpec = nullptr;
4991     if (Record->isUnion()) {
4992       // C++ [class.union]p6:
4993       // C++17 [class.union.anon]p2:
4994       //   Anonymous unions declared in a named namespace or in the
4995       //   global namespace shall be declared static.
4996       unsigned DiagID;
4997       DeclContext *OwnerScope = Owner->getRedeclContext();
4998       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4999           (OwnerScope->isTranslationUnit() ||
5000            (OwnerScope->isNamespace() &&
5001             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5002         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5003           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5004 
5005         // Recover by adding 'static'.
5006         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5007                                PrevSpec, DiagID, Policy);
5008       }
5009       // C++ [class.union]p6:
5010       //   A storage class is not allowed in a declaration of an
5011       //   anonymous union in a class scope.
5012       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5013                isa<RecordDecl>(Owner)) {
5014         Diag(DS.getStorageClassSpecLoc(),
5015              diag::err_anonymous_union_with_storage_spec)
5016           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5017 
5018         // Recover by removing the storage specifier.
5019         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5020                                SourceLocation(),
5021                                PrevSpec, DiagID, Context.getPrintingPolicy());
5022       }
5023     }
5024 
5025     // Ignore const/volatile/restrict qualifiers.
5026     if (DS.getTypeQualifiers()) {
5027       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5028         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5029           << Record->isUnion() << "const"
5030           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5031       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5032         Diag(DS.getVolatileSpecLoc(),
5033              diag::ext_anonymous_struct_union_qualified)
5034           << Record->isUnion() << "volatile"
5035           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5036       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5037         Diag(DS.getRestrictSpecLoc(),
5038              diag::ext_anonymous_struct_union_qualified)
5039           << Record->isUnion() << "restrict"
5040           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5041       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5042         Diag(DS.getAtomicSpecLoc(),
5043              diag::ext_anonymous_struct_union_qualified)
5044           << Record->isUnion() << "_Atomic"
5045           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5046       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5047         Diag(DS.getUnalignedSpecLoc(),
5048              diag::ext_anonymous_struct_union_qualified)
5049           << Record->isUnion() << "__unaligned"
5050           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5051 
5052       DS.ClearTypeQualifiers();
5053     }
5054 
5055     // C++ [class.union]p2:
5056     //   The member-specification of an anonymous union shall only
5057     //   define non-static data members. [Note: nested types and
5058     //   functions cannot be declared within an anonymous union. ]
5059     for (auto *Mem : Record->decls()) {
5060       // Ignore invalid declarations; we already diagnosed them.
5061       if (Mem->isInvalidDecl())
5062         continue;
5063 
5064       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5065         // C++ [class.union]p3:
5066         //   An anonymous union shall not have private or protected
5067         //   members (clause 11).
5068         assert(FD->getAccess() != AS_none);
5069         if (FD->getAccess() != AS_public) {
5070           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5071             << Record->isUnion() << (FD->getAccess() == AS_protected);
5072           Invalid = true;
5073         }
5074 
5075         // C++ [class.union]p1
5076         //   An object of a class with a non-trivial constructor, a non-trivial
5077         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5078         //   assignment operator cannot be a member of a union, nor can an
5079         //   array of such objects.
5080         if (CheckNontrivialField(FD))
5081           Invalid = true;
5082       } else if (Mem->isImplicit()) {
5083         // Any implicit members are fine.
5084       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5085         // This is a type that showed up in an
5086         // elaborated-type-specifier inside the anonymous struct or
5087         // union, but which actually declares a type outside of the
5088         // anonymous struct or union. It's okay.
5089       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5090         if (!MemRecord->isAnonymousStructOrUnion() &&
5091             MemRecord->getDeclName()) {
5092           // Visual C++ allows type definition in anonymous struct or union.
5093           if (getLangOpts().MicrosoftExt)
5094             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5095               << Record->isUnion();
5096           else {
5097             // This is a nested type declaration.
5098             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5099               << Record->isUnion();
5100             Invalid = true;
5101           }
5102         } else {
5103           // This is an anonymous type definition within another anonymous type.
5104           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5105           // not part of standard C++.
5106           Diag(MemRecord->getLocation(),
5107                diag::ext_anonymous_record_with_anonymous_type)
5108             << Record->isUnion();
5109         }
5110       } else if (isa<AccessSpecDecl>(Mem)) {
5111         // Any access specifier is fine.
5112       } else if (isa<StaticAssertDecl>(Mem)) {
5113         // In C++1z, static_assert declarations are also fine.
5114       } else {
5115         // We have something that isn't a non-static data
5116         // member. Complain about it.
5117         unsigned DK = diag::err_anonymous_record_bad_member;
5118         if (isa<TypeDecl>(Mem))
5119           DK = diag::err_anonymous_record_with_type;
5120         else if (isa<FunctionDecl>(Mem))
5121           DK = diag::err_anonymous_record_with_function;
5122         else if (isa<VarDecl>(Mem))
5123           DK = diag::err_anonymous_record_with_static;
5124 
5125         // Visual C++ allows type definition in anonymous struct or union.
5126         if (getLangOpts().MicrosoftExt &&
5127             DK == diag::err_anonymous_record_with_type)
5128           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5129             << Record->isUnion();
5130         else {
5131           Diag(Mem->getLocation(), DK) << Record->isUnion();
5132           Invalid = true;
5133         }
5134       }
5135     }
5136 
5137     // C++11 [class.union]p8 (DR1460):
5138     //   At most one variant member of a union may have a
5139     //   brace-or-equal-initializer.
5140     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5141         Owner->isRecord())
5142       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5143                                 cast<CXXRecordDecl>(Record));
5144   }
5145 
5146   if (!Record->isUnion() && !Owner->isRecord()) {
5147     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5148       << getLangOpts().CPlusPlus;
5149     Invalid = true;
5150   }
5151 
5152   // C++ [dcl.dcl]p3:
5153   //   [If there are no declarators], and except for the declaration of an
5154   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5155   //   names into the program
5156   // C++ [class.mem]p2:
5157   //   each such member-declaration shall either declare at least one member
5158   //   name of the class or declare at least one unnamed bit-field
5159   //
5160   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5161   if (getLangOpts().CPlusPlus && Record->field_empty())
5162     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5163 
5164   // Mock up a declarator.
5165   Declarator Dc(DS, DeclaratorContext::MemberContext);
5166   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5167   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5168 
5169   // Create a declaration for this anonymous struct/union.
5170   NamedDecl *Anon = nullptr;
5171   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5172     Anon = FieldDecl::Create(
5173         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5174         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5175         /*BitWidth=*/nullptr, /*Mutable=*/false,
5176         /*InitStyle=*/ICIS_NoInit);
5177     Anon->setAccess(AS);
5178     ProcessDeclAttributes(S, Anon, Dc);
5179 
5180     if (getLangOpts().CPlusPlus)
5181       FieldCollector->Add(cast<FieldDecl>(Anon));
5182   } else {
5183     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5184     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5185     if (SCSpec == DeclSpec::SCS_mutable) {
5186       // mutable can only appear on non-static class members, so it's always
5187       // an error here
5188       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5189       Invalid = true;
5190       SC = SC_None;
5191     }
5192 
5193     assert(DS.getAttributes().empty() && "No attribute expected");
5194     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5195                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5196                            Context.getTypeDeclType(Record), TInfo, SC);
5197 
5198     // Default-initialize the implicit variable. This initialization will be
5199     // trivial in almost all cases, except if a union member has an in-class
5200     // initializer:
5201     //   union { int n = 0; };
5202     ActOnUninitializedDecl(Anon);
5203   }
5204   Anon->setImplicit();
5205 
5206   // Mark this as an anonymous struct/union type.
5207   Record->setAnonymousStructOrUnion(true);
5208 
5209   // Add the anonymous struct/union object to the current
5210   // context. We'll be referencing this object when we refer to one of
5211   // its members.
5212   Owner->addDecl(Anon);
5213 
5214   // Inject the members of the anonymous struct/union into the owning
5215   // context and into the identifier resolver chain for name lookup
5216   // purposes.
5217   SmallVector<NamedDecl*, 2> Chain;
5218   Chain.push_back(Anon);
5219 
5220   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5221     Invalid = true;
5222 
5223   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5224     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5225       MangleNumberingContext *MCtx;
5226       Decl *ManglingContextDecl;
5227       std::tie(MCtx, ManglingContextDecl) =
5228           getCurrentMangleNumberContext(NewVD->getDeclContext());
5229       if (MCtx) {
5230         Context.setManglingNumber(
5231             NewVD, MCtx->getManglingNumber(
5232                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5233         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5234       }
5235     }
5236   }
5237 
5238   if (Invalid)
5239     Anon->setInvalidDecl();
5240 
5241   return Anon;
5242 }
5243 
5244 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5245 /// Microsoft C anonymous structure.
5246 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5247 /// Example:
5248 ///
5249 /// struct A { int a; };
5250 /// struct B { struct A; int b; };
5251 ///
5252 /// void foo() {
5253 ///   B var;
5254 ///   var.a = 3;
5255 /// }
5256 ///
5257 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5258                                            RecordDecl *Record) {
5259   assert(Record && "expected a record!");
5260 
5261   // Mock up a declarator.
5262   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5263   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5264   assert(TInfo && "couldn't build declarator info for anonymous struct");
5265 
5266   auto *ParentDecl = cast<RecordDecl>(CurContext);
5267   QualType RecTy = Context.getTypeDeclType(Record);
5268 
5269   // Create a declaration for this anonymous struct.
5270   NamedDecl *Anon =
5271       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5272                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5273                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5274                         /*InitStyle=*/ICIS_NoInit);
5275   Anon->setImplicit();
5276 
5277   // Add the anonymous struct object to the current context.
5278   CurContext->addDecl(Anon);
5279 
5280   // Inject the members of the anonymous struct into the current
5281   // context and into the identifier resolver chain for name lookup
5282   // purposes.
5283   SmallVector<NamedDecl*, 2> Chain;
5284   Chain.push_back(Anon);
5285 
5286   RecordDecl *RecordDef = Record->getDefinition();
5287   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5288                                diag::err_field_incomplete_or_sizeless) ||
5289       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5290                                           AS_none, Chain)) {
5291     Anon->setInvalidDecl();
5292     ParentDecl->setInvalidDecl();
5293   }
5294 
5295   return Anon;
5296 }
5297 
5298 /// GetNameForDeclarator - Determine the full declaration name for the
5299 /// given Declarator.
5300 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5301   return GetNameFromUnqualifiedId(D.getName());
5302 }
5303 
5304 /// Retrieves the declaration name from a parsed unqualified-id.
5305 DeclarationNameInfo
5306 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5307   DeclarationNameInfo NameInfo;
5308   NameInfo.setLoc(Name.StartLocation);
5309 
5310   switch (Name.getKind()) {
5311 
5312   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5313   case UnqualifiedIdKind::IK_Identifier:
5314     NameInfo.setName(Name.Identifier);
5315     return NameInfo;
5316 
5317   case UnqualifiedIdKind::IK_DeductionGuideName: {
5318     // C++ [temp.deduct.guide]p3:
5319     //   The simple-template-id shall name a class template specialization.
5320     //   The template-name shall be the same identifier as the template-name
5321     //   of the simple-template-id.
5322     // These together intend to imply that the template-name shall name a
5323     // class template.
5324     // FIXME: template<typename T> struct X {};
5325     //        template<typename T> using Y = X<T>;
5326     //        Y(int) -> Y<int>;
5327     //   satisfies these rules but does not name a class template.
5328     TemplateName TN = Name.TemplateName.get().get();
5329     auto *Template = TN.getAsTemplateDecl();
5330     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5331       Diag(Name.StartLocation,
5332            diag::err_deduction_guide_name_not_class_template)
5333         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5334       if (Template)
5335         Diag(Template->getLocation(), diag::note_template_decl_here);
5336       return DeclarationNameInfo();
5337     }
5338 
5339     NameInfo.setName(
5340         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5341     return NameInfo;
5342   }
5343 
5344   case UnqualifiedIdKind::IK_OperatorFunctionId:
5345     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5346                                            Name.OperatorFunctionId.Operator));
5347     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5348       = Name.OperatorFunctionId.SymbolLocations[0];
5349     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5350       = Name.EndLocation.getRawEncoding();
5351     return NameInfo;
5352 
5353   case UnqualifiedIdKind::IK_LiteralOperatorId:
5354     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5355                                                            Name.Identifier));
5356     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5357     return NameInfo;
5358 
5359   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5360     TypeSourceInfo *TInfo;
5361     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5362     if (Ty.isNull())
5363       return DeclarationNameInfo();
5364     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5365                                                Context.getCanonicalType(Ty)));
5366     NameInfo.setNamedTypeInfo(TInfo);
5367     return NameInfo;
5368   }
5369 
5370   case UnqualifiedIdKind::IK_ConstructorName: {
5371     TypeSourceInfo *TInfo;
5372     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5373     if (Ty.isNull())
5374       return DeclarationNameInfo();
5375     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5376                                               Context.getCanonicalType(Ty)));
5377     NameInfo.setNamedTypeInfo(TInfo);
5378     return NameInfo;
5379   }
5380 
5381   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5382     // In well-formed code, we can only have a constructor
5383     // template-id that refers to the current context, so go there
5384     // to find the actual type being constructed.
5385     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5386     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5387       return DeclarationNameInfo();
5388 
5389     // Determine the type of the class being constructed.
5390     QualType CurClassType = Context.getTypeDeclType(CurClass);
5391 
5392     // FIXME: Check two things: that the template-id names the same type as
5393     // CurClassType, and that the template-id does not occur when the name
5394     // was qualified.
5395 
5396     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5397                                     Context.getCanonicalType(CurClassType)));
5398     // FIXME: should we retrieve TypeSourceInfo?
5399     NameInfo.setNamedTypeInfo(nullptr);
5400     return NameInfo;
5401   }
5402 
5403   case UnqualifiedIdKind::IK_DestructorName: {
5404     TypeSourceInfo *TInfo;
5405     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5406     if (Ty.isNull())
5407       return DeclarationNameInfo();
5408     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5409                                               Context.getCanonicalType(Ty)));
5410     NameInfo.setNamedTypeInfo(TInfo);
5411     return NameInfo;
5412   }
5413 
5414   case UnqualifiedIdKind::IK_TemplateId: {
5415     TemplateName TName = Name.TemplateId->Template.get();
5416     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5417     return Context.getNameForTemplate(TName, TNameLoc);
5418   }
5419 
5420   } // switch (Name.getKind())
5421 
5422   llvm_unreachable("Unknown name kind");
5423 }
5424 
5425 static QualType getCoreType(QualType Ty) {
5426   do {
5427     if (Ty->isPointerType() || Ty->isReferenceType())
5428       Ty = Ty->getPointeeType();
5429     else if (Ty->isArrayType())
5430       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5431     else
5432       return Ty.withoutLocalFastQualifiers();
5433   } while (true);
5434 }
5435 
5436 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5437 /// and Definition have "nearly" matching parameters. This heuristic is
5438 /// used to improve diagnostics in the case where an out-of-line function
5439 /// definition doesn't match any declaration within the class or namespace.
5440 /// Also sets Params to the list of indices to the parameters that differ
5441 /// between the declaration and the definition. If hasSimilarParameters
5442 /// returns true and Params is empty, then all of the parameters match.
5443 static bool hasSimilarParameters(ASTContext &Context,
5444                                      FunctionDecl *Declaration,
5445                                      FunctionDecl *Definition,
5446                                      SmallVectorImpl<unsigned> &Params) {
5447   Params.clear();
5448   if (Declaration->param_size() != Definition->param_size())
5449     return false;
5450   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5451     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5452     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5453 
5454     // The parameter types are identical
5455     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5456       continue;
5457 
5458     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5459     QualType DefParamBaseTy = getCoreType(DefParamTy);
5460     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5461     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5462 
5463     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5464         (DeclTyName && DeclTyName == DefTyName))
5465       Params.push_back(Idx);
5466     else  // The two parameters aren't even close
5467       return false;
5468   }
5469 
5470   return true;
5471 }
5472 
5473 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5474 /// declarator needs to be rebuilt in the current instantiation.
5475 /// Any bits of declarator which appear before the name are valid for
5476 /// consideration here.  That's specifically the type in the decl spec
5477 /// and the base type in any member-pointer chunks.
5478 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5479                                                     DeclarationName Name) {
5480   // The types we specifically need to rebuild are:
5481   //   - typenames, typeofs, and decltypes
5482   //   - types which will become injected class names
5483   // Of course, we also need to rebuild any type referencing such a
5484   // type.  It's safest to just say "dependent", but we call out a
5485   // few cases here.
5486 
5487   DeclSpec &DS = D.getMutableDeclSpec();
5488   switch (DS.getTypeSpecType()) {
5489   case DeclSpec::TST_typename:
5490   case DeclSpec::TST_typeofType:
5491   case DeclSpec::TST_underlyingType:
5492   case DeclSpec::TST_atomic: {
5493     // Grab the type from the parser.
5494     TypeSourceInfo *TSI = nullptr;
5495     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5496     if (T.isNull() || !T->isDependentType()) break;
5497 
5498     // Make sure there's a type source info.  This isn't really much
5499     // of a waste; most dependent types should have type source info
5500     // attached already.
5501     if (!TSI)
5502       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5503 
5504     // Rebuild the type in the current instantiation.
5505     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5506     if (!TSI) return true;
5507 
5508     // Store the new type back in the decl spec.
5509     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5510     DS.UpdateTypeRep(LocType);
5511     break;
5512   }
5513 
5514   case DeclSpec::TST_decltype:
5515   case DeclSpec::TST_typeofExpr: {
5516     Expr *E = DS.getRepAsExpr();
5517     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5518     if (Result.isInvalid()) return true;
5519     DS.UpdateExprRep(Result.get());
5520     break;
5521   }
5522 
5523   default:
5524     // Nothing to do for these decl specs.
5525     break;
5526   }
5527 
5528   // It doesn't matter what order we do this in.
5529   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5530     DeclaratorChunk &Chunk = D.getTypeObject(I);
5531 
5532     // The only type information in the declarator which can come
5533     // before the declaration name is the base type of a member
5534     // pointer.
5535     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5536       continue;
5537 
5538     // Rebuild the scope specifier in-place.
5539     CXXScopeSpec &SS = Chunk.Mem.Scope();
5540     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5541       return true;
5542   }
5543 
5544   return false;
5545 }
5546 
5547 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5548   D.setFunctionDefinitionKind(FDK_Declaration);
5549   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5550 
5551   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5552       Dcl && Dcl->getDeclContext()->isFileContext())
5553     Dcl->setTopLevelDeclInObjCContainer();
5554 
5555   if (getLangOpts().OpenCL)
5556     setCurrentOpenCLExtensionForDecl(Dcl);
5557 
5558   return Dcl;
5559 }
5560 
5561 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5562 ///   If T is the name of a class, then each of the following shall have a
5563 ///   name different from T:
5564 ///     - every static data member of class T;
5565 ///     - every member function of class T
5566 ///     - every member of class T that is itself a type;
5567 /// \returns true if the declaration name violates these rules.
5568 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5569                                    DeclarationNameInfo NameInfo) {
5570   DeclarationName Name = NameInfo.getName();
5571 
5572   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5573   while (Record && Record->isAnonymousStructOrUnion())
5574     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5575   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5576     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5577     return true;
5578   }
5579 
5580   return false;
5581 }
5582 
5583 /// Diagnose a declaration whose declarator-id has the given
5584 /// nested-name-specifier.
5585 ///
5586 /// \param SS The nested-name-specifier of the declarator-id.
5587 ///
5588 /// \param DC The declaration context to which the nested-name-specifier
5589 /// resolves.
5590 ///
5591 /// \param Name The name of the entity being declared.
5592 ///
5593 /// \param Loc The location of the name of the entity being declared.
5594 ///
5595 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5596 /// we're declaring an explicit / partial specialization / instantiation.
5597 ///
5598 /// \returns true if we cannot safely recover from this error, false otherwise.
5599 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5600                                         DeclarationName Name,
5601                                         SourceLocation Loc, bool IsTemplateId) {
5602   DeclContext *Cur = CurContext;
5603   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5604     Cur = Cur->getParent();
5605 
5606   // If the user provided a superfluous scope specifier that refers back to the
5607   // class in which the entity is already declared, diagnose and ignore it.
5608   //
5609   // class X {
5610   //   void X::f();
5611   // };
5612   //
5613   // Note, it was once ill-formed to give redundant qualification in all
5614   // contexts, but that rule was removed by DR482.
5615   if (Cur->Equals(DC)) {
5616     if (Cur->isRecord()) {
5617       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5618                                       : diag::err_member_extra_qualification)
5619         << Name << FixItHint::CreateRemoval(SS.getRange());
5620       SS.clear();
5621     } else {
5622       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5623     }
5624     return false;
5625   }
5626 
5627   // Check whether the qualifying scope encloses the scope of the original
5628   // declaration. For a template-id, we perform the checks in
5629   // CheckTemplateSpecializationScope.
5630   if (!Cur->Encloses(DC) && !IsTemplateId) {
5631     if (Cur->isRecord())
5632       Diag(Loc, diag::err_member_qualification)
5633         << Name << SS.getRange();
5634     else if (isa<TranslationUnitDecl>(DC))
5635       Diag(Loc, diag::err_invalid_declarator_global_scope)
5636         << Name << SS.getRange();
5637     else if (isa<FunctionDecl>(Cur))
5638       Diag(Loc, diag::err_invalid_declarator_in_function)
5639         << Name << SS.getRange();
5640     else if (isa<BlockDecl>(Cur))
5641       Diag(Loc, diag::err_invalid_declarator_in_block)
5642         << Name << SS.getRange();
5643     else
5644       Diag(Loc, diag::err_invalid_declarator_scope)
5645       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5646 
5647     return true;
5648   }
5649 
5650   if (Cur->isRecord()) {
5651     // Cannot qualify members within a class.
5652     Diag(Loc, diag::err_member_qualification)
5653       << Name << SS.getRange();
5654     SS.clear();
5655 
5656     // C++ constructors and destructors with incorrect scopes can break
5657     // our AST invariants by having the wrong underlying types. If
5658     // that's the case, then drop this declaration entirely.
5659     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5660          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5661         !Context.hasSameType(Name.getCXXNameType(),
5662                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5663       return true;
5664 
5665     return false;
5666   }
5667 
5668   // C++11 [dcl.meaning]p1:
5669   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5670   //   not begin with a decltype-specifer"
5671   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5672   while (SpecLoc.getPrefix())
5673     SpecLoc = SpecLoc.getPrefix();
5674   if (dyn_cast_or_null<DecltypeType>(
5675         SpecLoc.getNestedNameSpecifier()->getAsType()))
5676     Diag(Loc, diag::err_decltype_in_declarator)
5677       << SpecLoc.getTypeLoc().getSourceRange();
5678 
5679   return false;
5680 }
5681 
5682 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5683                                   MultiTemplateParamsArg TemplateParamLists) {
5684   // TODO: consider using NameInfo for diagnostic.
5685   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5686   DeclarationName Name = NameInfo.getName();
5687 
5688   // All of these full declarators require an identifier.  If it doesn't have
5689   // one, the ParsedFreeStandingDeclSpec action should be used.
5690   if (D.isDecompositionDeclarator()) {
5691     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5692   } else if (!Name) {
5693     if (!D.isInvalidType())  // Reject this if we think it is valid.
5694       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5695           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5696     return nullptr;
5697   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5698     return nullptr;
5699 
5700   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5701   // we find one that is.
5702   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5703          (S->getFlags() & Scope::TemplateParamScope) != 0)
5704     S = S->getParent();
5705 
5706   DeclContext *DC = CurContext;
5707   if (D.getCXXScopeSpec().isInvalid())
5708     D.setInvalidType();
5709   else if (D.getCXXScopeSpec().isSet()) {
5710     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5711                                         UPPC_DeclarationQualifier))
5712       return nullptr;
5713 
5714     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5715     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5716     if (!DC || isa<EnumDecl>(DC)) {
5717       // If we could not compute the declaration context, it's because the
5718       // declaration context is dependent but does not refer to a class,
5719       // class template, or class template partial specialization. Complain
5720       // and return early, to avoid the coming semantic disaster.
5721       Diag(D.getIdentifierLoc(),
5722            diag::err_template_qualified_declarator_no_match)
5723         << D.getCXXScopeSpec().getScopeRep()
5724         << D.getCXXScopeSpec().getRange();
5725       return nullptr;
5726     }
5727     bool IsDependentContext = DC->isDependentContext();
5728 
5729     if (!IsDependentContext &&
5730         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5731       return nullptr;
5732 
5733     // If a class is incomplete, do not parse entities inside it.
5734     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5735       Diag(D.getIdentifierLoc(),
5736            diag::err_member_def_undefined_record)
5737         << Name << DC << D.getCXXScopeSpec().getRange();
5738       return nullptr;
5739     }
5740     if (!D.getDeclSpec().isFriendSpecified()) {
5741       if (diagnoseQualifiedDeclaration(
5742               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5743               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5744         if (DC->isRecord())
5745           return nullptr;
5746 
5747         D.setInvalidType();
5748       }
5749     }
5750 
5751     // Check whether we need to rebuild the type of the given
5752     // declaration in the current instantiation.
5753     if (EnteringContext && IsDependentContext &&
5754         TemplateParamLists.size() != 0) {
5755       ContextRAII SavedContext(*this, DC);
5756       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5757         D.setInvalidType();
5758     }
5759   }
5760 
5761   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5762   QualType R = TInfo->getType();
5763 
5764   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5765                                       UPPC_DeclarationType))
5766     D.setInvalidType();
5767 
5768   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5769                         forRedeclarationInCurContext());
5770 
5771   // See if this is a redefinition of a variable in the same scope.
5772   if (!D.getCXXScopeSpec().isSet()) {
5773     bool IsLinkageLookup = false;
5774     bool CreateBuiltins = false;
5775 
5776     // If the declaration we're planning to build will be a function
5777     // or object with linkage, then look for another declaration with
5778     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5779     //
5780     // If the declaration we're planning to build will be declared with
5781     // external linkage in the translation unit, create any builtin with
5782     // the same name.
5783     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5784       /* Do nothing*/;
5785     else if (CurContext->isFunctionOrMethod() &&
5786              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5787               R->isFunctionType())) {
5788       IsLinkageLookup = true;
5789       CreateBuiltins =
5790           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5791     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5792                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5793       CreateBuiltins = true;
5794 
5795     if (IsLinkageLookup) {
5796       Previous.clear(LookupRedeclarationWithLinkage);
5797       Previous.setRedeclarationKind(ForExternalRedeclaration);
5798     }
5799 
5800     LookupName(Previous, S, CreateBuiltins);
5801   } else { // Something like "int foo::x;"
5802     LookupQualifiedName(Previous, DC);
5803 
5804     // C++ [dcl.meaning]p1:
5805     //   When the declarator-id is qualified, the declaration shall refer to a
5806     //  previously declared member of the class or namespace to which the
5807     //  qualifier refers (or, in the case of a namespace, of an element of the
5808     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5809     //  thereof; [...]
5810     //
5811     // Note that we already checked the context above, and that we do not have
5812     // enough information to make sure that Previous contains the declaration
5813     // we want to match. For example, given:
5814     //
5815     //   class X {
5816     //     void f();
5817     //     void f(float);
5818     //   };
5819     //
5820     //   void X::f(int) { } // ill-formed
5821     //
5822     // In this case, Previous will point to the overload set
5823     // containing the two f's declared in X, but neither of them
5824     // matches.
5825 
5826     // C++ [dcl.meaning]p1:
5827     //   [...] the member shall not merely have been introduced by a
5828     //   using-declaration in the scope of the class or namespace nominated by
5829     //   the nested-name-specifier of the declarator-id.
5830     RemoveUsingDecls(Previous);
5831   }
5832 
5833   if (Previous.isSingleResult() &&
5834       Previous.getFoundDecl()->isTemplateParameter()) {
5835     // Maybe we will complain about the shadowed template parameter.
5836     if (!D.isInvalidType())
5837       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5838                                       Previous.getFoundDecl());
5839 
5840     // Just pretend that we didn't see the previous declaration.
5841     Previous.clear();
5842   }
5843 
5844   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5845     // Forget that the previous declaration is the injected-class-name.
5846     Previous.clear();
5847 
5848   // In C++, the previous declaration we find might be a tag type
5849   // (class or enum). In this case, the new declaration will hide the
5850   // tag type. Note that this applies to functions, function templates, and
5851   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5852   if (Previous.isSingleTagDecl() &&
5853       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5854       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5855     Previous.clear();
5856 
5857   // Check that there are no default arguments other than in the parameters
5858   // of a function declaration (C++ only).
5859   if (getLangOpts().CPlusPlus)
5860     CheckExtraCXXDefaultArguments(D);
5861 
5862   NamedDecl *New;
5863 
5864   bool AddToScope = true;
5865   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5866     if (TemplateParamLists.size()) {
5867       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5868       return nullptr;
5869     }
5870 
5871     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5872   } else if (R->isFunctionType()) {
5873     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5874                                   TemplateParamLists,
5875                                   AddToScope);
5876   } else {
5877     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5878                                   AddToScope);
5879   }
5880 
5881   if (!New)
5882     return nullptr;
5883 
5884   // If this has an identifier and is not a function template specialization,
5885   // add it to the scope stack.
5886   if (New->getDeclName() && AddToScope)
5887     PushOnScopeChains(New, S);
5888 
5889   if (isInOpenMPDeclareTargetContext())
5890     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5891 
5892   return New;
5893 }
5894 
5895 /// Helper method to turn variable array types into constant array
5896 /// types in certain situations which would otherwise be errors (for
5897 /// GCC compatibility).
5898 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5899                                                     ASTContext &Context,
5900                                                     bool &SizeIsNegative,
5901                                                     llvm::APSInt &Oversized) {
5902   // This method tries to turn a variable array into a constant
5903   // array even when the size isn't an ICE.  This is necessary
5904   // for compatibility with code that depends on gcc's buggy
5905   // constant expression folding, like struct {char x[(int)(char*)2];}
5906   SizeIsNegative = false;
5907   Oversized = 0;
5908 
5909   if (T->isDependentType())
5910     return QualType();
5911 
5912   QualifierCollector Qs;
5913   const Type *Ty = Qs.strip(T);
5914 
5915   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5916     QualType Pointee = PTy->getPointeeType();
5917     QualType FixedType =
5918         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5919                                             Oversized);
5920     if (FixedType.isNull()) return FixedType;
5921     FixedType = Context.getPointerType(FixedType);
5922     return Qs.apply(Context, FixedType);
5923   }
5924   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5925     QualType Inner = PTy->getInnerType();
5926     QualType FixedType =
5927         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5928                                             Oversized);
5929     if (FixedType.isNull()) return FixedType;
5930     FixedType = Context.getParenType(FixedType);
5931     return Qs.apply(Context, FixedType);
5932   }
5933 
5934   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5935   if (!VLATy)
5936     return QualType();
5937   // FIXME: We should probably handle this case
5938   if (VLATy->getElementType()->isVariablyModifiedType())
5939     return QualType();
5940 
5941   Expr::EvalResult Result;
5942   if (!VLATy->getSizeExpr() ||
5943       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5944     return QualType();
5945 
5946   llvm::APSInt Res = Result.Val.getInt();
5947 
5948   // Check whether the array size is negative.
5949   if (Res.isSigned() && Res.isNegative()) {
5950     SizeIsNegative = true;
5951     return QualType();
5952   }
5953 
5954   // Check whether the array is too large to be addressed.
5955   unsigned ActiveSizeBits
5956     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5957                                               Res);
5958   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5959     Oversized = Res;
5960     return QualType();
5961   }
5962 
5963   return Context.getConstantArrayType(
5964       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5965 }
5966 
5967 static void
5968 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5969   SrcTL = SrcTL.getUnqualifiedLoc();
5970   DstTL = DstTL.getUnqualifiedLoc();
5971   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5972     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5973     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5974                                       DstPTL.getPointeeLoc());
5975     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5976     return;
5977   }
5978   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5979     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5980     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5981                                       DstPTL.getInnerLoc());
5982     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5983     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5984     return;
5985   }
5986   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5987   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5988   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5989   TypeLoc DstElemTL = DstATL.getElementLoc();
5990   DstElemTL.initializeFullCopy(SrcElemTL);
5991   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5992   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5993   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5994 }
5995 
5996 /// Helper method to turn variable array types into constant array
5997 /// types in certain situations which would otherwise be errors (for
5998 /// GCC compatibility).
5999 static TypeSourceInfo*
6000 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6001                                               ASTContext &Context,
6002                                               bool &SizeIsNegative,
6003                                               llvm::APSInt &Oversized) {
6004   QualType FixedTy
6005     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6006                                           SizeIsNegative, Oversized);
6007   if (FixedTy.isNull())
6008     return nullptr;
6009   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6010   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6011                                     FixedTInfo->getTypeLoc());
6012   return FixedTInfo;
6013 }
6014 
6015 /// Register the given locally-scoped extern "C" declaration so
6016 /// that it can be found later for redeclarations. We include any extern "C"
6017 /// declaration that is not visible in the translation unit here, not just
6018 /// function-scope declarations.
6019 void
6020 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6021   if (!getLangOpts().CPlusPlus &&
6022       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6023     // Don't need to track declarations in the TU in C.
6024     return;
6025 
6026   // Note that we have a locally-scoped external with this name.
6027   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6028 }
6029 
6030 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6031   // FIXME: We can have multiple results via __attribute__((overloadable)).
6032   auto Result = Context.getExternCContextDecl()->lookup(Name);
6033   return Result.empty() ? nullptr : *Result.begin();
6034 }
6035 
6036 /// Diagnose function specifiers on a declaration of an identifier that
6037 /// does not identify a function.
6038 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6039   // FIXME: We should probably indicate the identifier in question to avoid
6040   // confusion for constructs like "virtual int a(), b;"
6041   if (DS.isVirtualSpecified())
6042     Diag(DS.getVirtualSpecLoc(),
6043          diag::err_virtual_non_function);
6044 
6045   if (DS.hasExplicitSpecifier())
6046     Diag(DS.getExplicitSpecLoc(),
6047          diag::err_explicit_non_function);
6048 
6049   if (DS.isNoreturnSpecified())
6050     Diag(DS.getNoreturnSpecLoc(),
6051          diag::err_noreturn_non_function);
6052 }
6053 
6054 NamedDecl*
6055 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6056                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6057   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6058   if (D.getCXXScopeSpec().isSet()) {
6059     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6060       << D.getCXXScopeSpec().getRange();
6061     D.setInvalidType();
6062     // Pretend we didn't see the scope specifier.
6063     DC = CurContext;
6064     Previous.clear();
6065   }
6066 
6067   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6068 
6069   if (D.getDeclSpec().isInlineSpecified())
6070     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6071         << getLangOpts().CPlusPlus17;
6072   if (D.getDeclSpec().hasConstexprSpecifier())
6073     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6074         << 1 << D.getDeclSpec().getConstexprSpecifier();
6075 
6076   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6077     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6078       Diag(D.getName().StartLocation,
6079            diag::err_deduction_guide_invalid_specifier)
6080           << "typedef";
6081     else
6082       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6083           << D.getName().getSourceRange();
6084     return nullptr;
6085   }
6086 
6087   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6088   if (!NewTD) return nullptr;
6089 
6090   // Handle attributes prior to checking for duplicates in MergeVarDecl
6091   ProcessDeclAttributes(S, NewTD, D);
6092 
6093   CheckTypedefForVariablyModifiedType(S, NewTD);
6094 
6095   bool Redeclaration = D.isRedeclaration();
6096   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6097   D.setRedeclaration(Redeclaration);
6098   return ND;
6099 }
6100 
6101 void
6102 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6103   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6104   // then it shall have block scope.
6105   // Note that variably modified types must be fixed before merging the decl so
6106   // that redeclarations will match.
6107   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6108   QualType T = TInfo->getType();
6109   if (T->isVariablyModifiedType()) {
6110     setFunctionHasBranchProtectedScope();
6111 
6112     if (S->getFnParent() == nullptr) {
6113       bool SizeIsNegative;
6114       llvm::APSInt Oversized;
6115       TypeSourceInfo *FixedTInfo =
6116         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6117                                                       SizeIsNegative,
6118                                                       Oversized);
6119       if (FixedTInfo) {
6120         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6121         NewTD->setTypeSourceInfo(FixedTInfo);
6122       } else {
6123         if (SizeIsNegative)
6124           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6125         else if (T->isVariableArrayType())
6126           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6127         else if (Oversized.getBoolValue())
6128           Diag(NewTD->getLocation(), diag::err_array_too_large)
6129             << Oversized.toString(10);
6130         else
6131           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6132         NewTD->setInvalidDecl();
6133       }
6134     }
6135   }
6136 }
6137 
6138 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6139 /// declares a typedef-name, either using the 'typedef' type specifier or via
6140 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6141 NamedDecl*
6142 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6143                            LookupResult &Previous, bool &Redeclaration) {
6144 
6145   // Find the shadowed declaration before filtering for scope.
6146   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6147 
6148   // Merge the decl with the existing one if appropriate. If the decl is
6149   // in an outer scope, it isn't the same thing.
6150   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6151                        /*AllowInlineNamespace*/false);
6152   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6153   if (!Previous.empty()) {
6154     Redeclaration = true;
6155     MergeTypedefNameDecl(S, NewTD, Previous);
6156   } else {
6157     inferGslPointerAttribute(NewTD);
6158   }
6159 
6160   if (ShadowedDecl && !Redeclaration)
6161     CheckShadow(NewTD, ShadowedDecl, Previous);
6162 
6163   // If this is the C FILE type, notify the AST context.
6164   if (IdentifierInfo *II = NewTD->getIdentifier())
6165     if (!NewTD->isInvalidDecl() &&
6166         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6167       if (II->isStr("FILE"))
6168         Context.setFILEDecl(NewTD);
6169       else if (II->isStr("jmp_buf"))
6170         Context.setjmp_bufDecl(NewTD);
6171       else if (II->isStr("sigjmp_buf"))
6172         Context.setsigjmp_bufDecl(NewTD);
6173       else if (II->isStr("ucontext_t"))
6174         Context.setucontext_tDecl(NewTD);
6175     }
6176 
6177   return NewTD;
6178 }
6179 
6180 /// Determines whether the given declaration is an out-of-scope
6181 /// previous declaration.
6182 ///
6183 /// This routine should be invoked when name lookup has found a
6184 /// previous declaration (PrevDecl) that is not in the scope where a
6185 /// new declaration by the same name is being introduced. If the new
6186 /// declaration occurs in a local scope, previous declarations with
6187 /// linkage may still be considered previous declarations (C99
6188 /// 6.2.2p4-5, C++ [basic.link]p6).
6189 ///
6190 /// \param PrevDecl the previous declaration found by name
6191 /// lookup
6192 ///
6193 /// \param DC the context in which the new declaration is being
6194 /// declared.
6195 ///
6196 /// \returns true if PrevDecl is an out-of-scope previous declaration
6197 /// for a new delcaration with the same name.
6198 static bool
6199 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6200                                 ASTContext &Context) {
6201   if (!PrevDecl)
6202     return false;
6203 
6204   if (!PrevDecl->hasLinkage())
6205     return false;
6206 
6207   if (Context.getLangOpts().CPlusPlus) {
6208     // C++ [basic.link]p6:
6209     //   If there is a visible declaration of an entity with linkage
6210     //   having the same name and type, ignoring entities declared
6211     //   outside the innermost enclosing namespace scope, the block
6212     //   scope declaration declares that same entity and receives the
6213     //   linkage of the previous declaration.
6214     DeclContext *OuterContext = DC->getRedeclContext();
6215     if (!OuterContext->isFunctionOrMethod())
6216       // This rule only applies to block-scope declarations.
6217       return false;
6218 
6219     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6220     if (PrevOuterContext->isRecord())
6221       // We found a member function: ignore it.
6222       return false;
6223 
6224     // Find the innermost enclosing namespace for the new and
6225     // previous declarations.
6226     OuterContext = OuterContext->getEnclosingNamespaceContext();
6227     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6228 
6229     // The previous declaration is in a different namespace, so it
6230     // isn't the same function.
6231     if (!OuterContext->Equals(PrevOuterContext))
6232       return false;
6233   }
6234 
6235   return true;
6236 }
6237 
6238 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6239   CXXScopeSpec &SS = D.getCXXScopeSpec();
6240   if (!SS.isSet()) return;
6241   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6242 }
6243 
6244 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6245   QualType type = decl->getType();
6246   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6247   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6248     // Various kinds of declaration aren't allowed to be __autoreleasing.
6249     unsigned kind = -1U;
6250     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6251       if (var->hasAttr<BlocksAttr>())
6252         kind = 0; // __block
6253       else if (!var->hasLocalStorage())
6254         kind = 1; // global
6255     } else if (isa<ObjCIvarDecl>(decl)) {
6256       kind = 3; // ivar
6257     } else if (isa<FieldDecl>(decl)) {
6258       kind = 2; // field
6259     }
6260 
6261     if (kind != -1U) {
6262       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6263         << kind;
6264     }
6265   } else if (lifetime == Qualifiers::OCL_None) {
6266     // Try to infer lifetime.
6267     if (!type->isObjCLifetimeType())
6268       return false;
6269 
6270     lifetime = type->getObjCARCImplicitLifetime();
6271     type = Context.getLifetimeQualifiedType(type, lifetime);
6272     decl->setType(type);
6273   }
6274 
6275   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6276     // Thread-local variables cannot have lifetime.
6277     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6278         var->getTLSKind()) {
6279       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6280         << var->getType();
6281       return true;
6282     }
6283   }
6284 
6285   return false;
6286 }
6287 
6288 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6289   if (Decl->getType().hasAddressSpace())
6290     return;
6291   if (Decl->getType()->isDependentType())
6292     return;
6293   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6294     QualType Type = Var->getType();
6295     if (Type->isSamplerT() || Type->isVoidType())
6296       return;
6297     LangAS ImplAS = LangAS::opencl_private;
6298     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6299         Var->hasGlobalStorage())
6300       ImplAS = LangAS::opencl_global;
6301     // If the original type from a decayed type is an array type and that array
6302     // type has no address space yet, deduce it now.
6303     if (auto DT = dyn_cast<DecayedType>(Type)) {
6304       auto OrigTy = DT->getOriginalType();
6305       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6306         // Add the address space to the original array type and then propagate
6307         // that to the element type through `getAsArrayType`.
6308         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6309         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6310         // Re-generate the decayed type.
6311         Type = Context.getDecayedType(OrigTy);
6312       }
6313     }
6314     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6315     // Apply any qualifiers (including address space) from the array type to
6316     // the element type. This implements C99 6.7.3p8: "If the specification of
6317     // an array type includes any type qualifiers, the element type is so
6318     // qualified, not the array type."
6319     if (Type->isArrayType())
6320       Type = QualType(Context.getAsArrayType(Type), 0);
6321     Decl->setType(Type);
6322   }
6323 }
6324 
6325 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6326   // Ensure that an auto decl is deduced otherwise the checks below might cache
6327   // the wrong linkage.
6328   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6329 
6330   // 'weak' only applies to declarations with external linkage.
6331   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6332     if (!ND.isExternallyVisible()) {
6333       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6334       ND.dropAttr<WeakAttr>();
6335     }
6336   }
6337   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6338     if (ND.isExternallyVisible()) {
6339       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6340       ND.dropAttr<WeakRefAttr>();
6341       ND.dropAttr<AliasAttr>();
6342     }
6343   }
6344 
6345   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6346     if (VD->hasInit()) {
6347       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6348         assert(VD->isThisDeclarationADefinition() &&
6349                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6350         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6351         VD->dropAttr<AliasAttr>();
6352       }
6353     }
6354   }
6355 
6356   // 'selectany' only applies to externally visible variable declarations.
6357   // It does not apply to functions.
6358   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6359     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6360       S.Diag(Attr->getLocation(),
6361              diag::err_attribute_selectany_non_extern_data);
6362       ND.dropAttr<SelectAnyAttr>();
6363     }
6364   }
6365 
6366   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6367     auto *VD = dyn_cast<VarDecl>(&ND);
6368     bool IsAnonymousNS = false;
6369     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6370     if (VD) {
6371       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6372       while (NS && !IsAnonymousNS) {
6373         IsAnonymousNS = NS->isAnonymousNamespace();
6374         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6375       }
6376     }
6377     // dll attributes require external linkage. Static locals may have external
6378     // linkage but still cannot be explicitly imported or exported.
6379     // In Microsoft mode, a variable defined in anonymous namespace must have
6380     // external linkage in order to be exported.
6381     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6382     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6383         (!AnonNSInMicrosoftMode &&
6384          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6385       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6386         << &ND << Attr;
6387       ND.setInvalidDecl();
6388     }
6389   }
6390 
6391   // Virtual functions cannot be marked as 'notail'.
6392   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6393     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6394       if (MD->isVirtual()) {
6395         S.Diag(ND.getLocation(),
6396                diag::err_invalid_attribute_on_virtual_function)
6397             << Attr;
6398         ND.dropAttr<NotTailCalledAttr>();
6399       }
6400 
6401   // Check the attributes on the function type, if any.
6402   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6403     // Don't declare this variable in the second operand of the for-statement;
6404     // GCC miscompiles that by ending its lifetime before evaluating the
6405     // third operand. See gcc.gnu.org/PR86769.
6406     AttributedTypeLoc ATL;
6407     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6408          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6409          TL = ATL.getModifiedLoc()) {
6410       // The [[lifetimebound]] attribute can be applied to the implicit object
6411       // parameter of a non-static member function (other than a ctor or dtor)
6412       // by applying it to the function type.
6413       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6414         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6415         if (!MD || MD->isStatic()) {
6416           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6417               << !MD << A->getRange();
6418         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6419           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6420               << isa<CXXDestructorDecl>(MD) << A->getRange();
6421         }
6422       }
6423     }
6424   }
6425 }
6426 
6427 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6428                                            NamedDecl *NewDecl,
6429                                            bool IsSpecialization,
6430                                            bool IsDefinition) {
6431   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6432     return;
6433 
6434   bool IsTemplate = false;
6435   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6436     OldDecl = OldTD->getTemplatedDecl();
6437     IsTemplate = true;
6438     if (!IsSpecialization)
6439       IsDefinition = false;
6440   }
6441   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6442     NewDecl = NewTD->getTemplatedDecl();
6443     IsTemplate = true;
6444   }
6445 
6446   if (!OldDecl || !NewDecl)
6447     return;
6448 
6449   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6450   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6451   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6452   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6453 
6454   // dllimport and dllexport are inheritable attributes so we have to exclude
6455   // inherited attribute instances.
6456   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6457                     (NewExportAttr && !NewExportAttr->isInherited());
6458 
6459   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6460   // the only exception being explicit specializations.
6461   // Implicitly generated declarations are also excluded for now because there
6462   // is no other way to switch these to use dllimport or dllexport.
6463   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6464 
6465   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6466     // Allow with a warning for free functions and global variables.
6467     bool JustWarn = false;
6468     if (!OldDecl->isCXXClassMember()) {
6469       auto *VD = dyn_cast<VarDecl>(OldDecl);
6470       if (VD && !VD->getDescribedVarTemplate())
6471         JustWarn = true;
6472       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6473       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6474         JustWarn = true;
6475     }
6476 
6477     // We cannot change a declaration that's been used because IR has already
6478     // been emitted. Dllimported functions will still work though (modulo
6479     // address equality) as they can use the thunk.
6480     if (OldDecl->isUsed())
6481       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6482         JustWarn = false;
6483 
6484     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6485                                : diag::err_attribute_dll_redeclaration;
6486     S.Diag(NewDecl->getLocation(), DiagID)
6487         << NewDecl
6488         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6489     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6490     if (!JustWarn) {
6491       NewDecl->setInvalidDecl();
6492       return;
6493     }
6494   }
6495 
6496   // A redeclaration is not allowed to drop a dllimport attribute, the only
6497   // exceptions being inline function definitions (except for function
6498   // templates), local extern declarations, qualified friend declarations or
6499   // special MSVC extension: in the last case, the declaration is treated as if
6500   // it were marked dllexport.
6501   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6502   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6503   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6504     // Ignore static data because out-of-line definitions are diagnosed
6505     // separately.
6506     IsStaticDataMember = VD->isStaticDataMember();
6507     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6508                    VarDecl::DeclarationOnly;
6509   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6510     IsInline = FD->isInlined();
6511     IsQualifiedFriend = FD->getQualifier() &&
6512                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6513   }
6514 
6515   if (OldImportAttr && !HasNewAttr &&
6516       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6517       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6518     if (IsMicrosoft && IsDefinition) {
6519       S.Diag(NewDecl->getLocation(),
6520              diag::warn_redeclaration_without_import_attribute)
6521           << NewDecl;
6522       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6523       NewDecl->dropAttr<DLLImportAttr>();
6524       NewDecl->addAttr(
6525           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6526     } else {
6527       S.Diag(NewDecl->getLocation(),
6528              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6529           << NewDecl << OldImportAttr;
6530       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6531       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6532       OldDecl->dropAttr<DLLImportAttr>();
6533       NewDecl->dropAttr<DLLImportAttr>();
6534     }
6535   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6536     // In MinGW, seeing a function declared inline drops the dllimport
6537     // attribute.
6538     OldDecl->dropAttr<DLLImportAttr>();
6539     NewDecl->dropAttr<DLLImportAttr>();
6540     S.Diag(NewDecl->getLocation(),
6541            diag::warn_dllimport_dropped_from_inline_function)
6542         << NewDecl << OldImportAttr;
6543   }
6544 
6545   // A specialization of a class template member function is processed here
6546   // since it's a redeclaration. If the parent class is dllexport, the
6547   // specialization inherits that attribute. This doesn't happen automatically
6548   // since the parent class isn't instantiated until later.
6549   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6550     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6551         !NewImportAttr && !NewExportAttr) {
6552       if (const DLLExportAttr *ParentExportAttr =
6553               MD->getParent()->getAttr<DLLExportAttr>()) {
6554         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6555         NewAttr->setInherited(true);
6556         NewDecl->addAttr(NewAttr);
6557       }
6558     }
6559   }
6560 }
6561 
6562 /// Given that we are within the definition of the given function,
6563 /// will that definition behave like C99's 'inline', where the
6564 /// definition is discarded except for optimization purposes?
6565 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6566   // Try to avoid calling GetGVALinkageForFunction.
6567 
6568   // All cases of this require the 'inline' keyword.
6569   if (!FD->isInlined()) return false;
6570 
6571   // This is only possible in C++ with the gnu_inline attribute.
6572   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6573     return false;
6574 
6575   // Okay, go ahead and call the relatively-more-expensive function.
6576   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6577 }
6578 
6579 /// Determine whether a variable is extern "C" prior to attaching
6580 /// an initializer. We can't just call isExternC() here, because that
6581 /// will also compute and cache whether the declaration is externally
6582 /// visible, which might change when we attach the initializer.
6583 ///
6584 /// This can only be used if the declaration is known to not be a
6585 /// redeclaration of an internal linkage declaration.
6586 ///
6587 /// For instance:
6588 ///
6589 ///   auto x = []{};
6590 ///
6591 /// Attaching the initializer here makes this declaration not externally
6592 /// visible, because its type has internal linkage.
6593 ///
6594 /// FIXME: This is a hack.
6595 template<typename T>
6596 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6597   if (S.getLangOpts().CPlusPlus) {
6598     // In C++, the overloadable attribute negates the effects of extern "C".
6599     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6600       return false;
6601 
6602     // So do CUDA's host/device attributes.
6603     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6604                                  D->template hasAttr<CUDAHostAttr>()))
6605       return false;
6606   }
6607   return D->isExternC();
6608 }
6609 
6610 static bool shouldConsiderLinkage(const VarDecl *VD) {
6611   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6612   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6613       isa<OMPDeclareMapperDecl>(DC))
6614     return VD->hasExternalStorage();
6615   if (DC->isFileContext())
6616     return true;
6617   if (DC->isRecord())
6618     return false;
6619   if (isa<RequiresExprBodyDecl>(DC))
6620     return false;
6621   llvm_unreachable("Unexpected context");
6622 }
6623 
6624 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6625   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6626   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6627       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6628     return true;
6629   if (DC->isRecord())
6630     return false;
6631   llvm_unreachable("Unexpected context");
6632 }
6633 
6634 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6635                           ParsedAttr::Kind Kind) {
6636   // Check decl attributes on the DeclSpec.
6637   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6638     return true;
6639 
6640   // Walk the declarator structure, checking decl attributes that were in a type
6641   // position to the decl itself.
6642   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6643     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6644       return true;
6645   }
6646 
6647   // Finally, check attributes on the decl itself.
6648   return PD.getAttributes().hasAttribute(Kind);
6649 }
6650 
6651 /// Adjust the \c DeclContext for a function or variable that might be a
6652 /// function-local external declaration.
6653 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6654   if (!DC->isFunctionOrMethod())
6655     return false;
6656 
6657   // If this is a local extern function or variable declared within a function
6658   // template, don't add it into the enclosing namespace scope until it is
6659   // instantiated; it might have a dependent type right now.
6660   if (DC->isDependentContext())
6661     return true;
6662 
6663   // C++11 [basic.link]p7:
6664   //   When a block scope declaration of an entity with linkage is not found to
6665   //   refer to some other declaration, then that entity is a member of the
6666   //   innermost enclosing namespace.
6667   //
6668   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6669   // semantically-enclosing namespace, not a lexically-enclosing one.
6670   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6671     DC = DC->getParent();
6672   return true;
6673 }
6674 
6675 /// Returns true if given declaration has external C language linkage.
6676 static bool isDeclExternC(const Decl *D) {
6677   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6678     return FD->isExternC();
6679   if (const auto *VD = dyn_cast<VarDecl>(D))
6680     return VD->isExternC();
6681 
6682   llvm_unreachable("Unknown type of decl!");
6683 }
6684 /// Returns true if there hasn't been any invalid type diagnosed.
6685 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6686                                 DeclContext *DC, QualType R) {
6687   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6688   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6689   // argument.
6690   if (R->isImageType() || R->isPipeType()) {
6691     Se.Diag(D.getIdentifierLoc(),
6692             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6693         << R;
6694     D.setInvalidType();
6695     return false;
6696   }
6697 
6698   // OpenCL v1.2 s6.9.r:
6699   // The event type cannot be used to declare a program scope variable.
6700   // OpenCL v2.0 s6.9.q:
6701   // The clk_event_t and reserve_id_t types cannot be declared in program
6702   // scope.
6703   if (NULL == S->getParent()) {
6704     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6705       Se.Diag(D.getIdentifierLoc(),
6706               diag::err_invalid_type_for_program_scope_var)
6707           << R;
6708       D.setInvalidType();
6709       return false;
6710     }
6711   }
6712 
6713   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6714   QualType NR = R;
6715   while (NR->isPointerType()) {
6716     if (NR->isFunctionPointerType()) {
6717       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6718       D.setInvalidType();
6719       return false;
6720     }
6721     NR = NR->getPointeeType();
6722   }
6723 
6724   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6725     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6726     // half array type (unless the cl_khr_fp16 extension is enabled).
6727     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6728       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6729       D.setInvalidType();
6730       return false;
6731     }
6732   }
6733 
6734   // OpenCL v1.2 s6.9.r:
6735   // The event type cannot be used with the __local, __constant and __global
6736   // address space qualifiers.
6737   if (R->isEventT()) {
6738     if (R.getAddressSpace() != LangAS::opencl_private) {
6739       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6740       D.setInvalidType();
6741       return false;
6742     }
6743   }
6744 
6745   // C++ for OpenCL does not allow the thread_local storage qualifier.
6746   // OpenCL C does not support thread_local either, and
6747   // also reject all other thread storage class specifiers.
6748   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6749   if (TSC != TSCS_unspecified) {
6750     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6751     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6752             diag::err_opencl_unknown_type_specifier)
6753         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6754         << DeclSpec::getSpecifierName(TSC) << 1;
6755     D.setInvalidType();
6756     return false;
6757   }
6758 
6759   if (R->isSamplerT()) {
6760     // OpenCL v1.2 s6.9.b p4:
6761     // The sampler type cannot be used with the __local and __global address
6762     // space qualifiers.
6763     if (R.getAddressSpace() == LangAS::opencl_local ||
6764         R.getAddressSpace() == LangAS::opencl_global) {
6765       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6766       D.setInvalidType();
6767     }
6768 
6769     // OpenCL v1.2 s6.12.14.1:
6770     // A global sampler must be declared with either the constant address
6771     // space qualifier or with the const qualifier.
6772     if (DC->isTranslationUnit() &&
6773         !(R.getAddressSpace() == LangAS::opencl_constant ||
6774           R.isConstQualified())) {
6775       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6776       D.setInvalidType();
6777     }
6778     if (D.isInvalidType())
6779       return false;
6780   }
6781   return true;
6782 }
6783 
6784 NamedDecl *Sema::ActOnVariableDeclarator(
6785     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6786     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6787     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6788   QualType R = TInfo->getType();
6789   DeclarationName Name = GetNameForDeclarator(D).getName();
6790 
6791   IdentifierInfo *II = Name.getAsIdentifierInfo();
6792 
6793   if (D.isDecompositionDeclarator()) {
6794     // Take the name of the first declarator as our name for diagnostic
6795     // purposes.
6796     auto &Decomp = D.getDecompositionDeclarator();
6797     if (!Decomp.bindings().empty()) {
6798       II = Decomp.bindings()[0].Name;
6799       Name = II;
6800     }
6801   } else if (!II) {
6802     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6803     return nullptr;
6804   }
6805 
6806 
6807   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6808   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6809 
6810   // dllimport globals without explicit storage class are treated as extern. We
6811   // have to change the storage class this early to get the right DeclContext.
6812   if (SC == SC_None && !DC->isRecord() &&
6813       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6814       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6815     SC = SC_Extern;
6816 
6817   DeclContext *OriginalDC = DC;
6818   bool IsLocalExternDecl = SC == SC_Extern &&
6819                            adjustContextForLocalExternDecl(DC);
6820 
6821   if (SCSpec == DeclSpec::SCS_mutable) {
6822     // mutable can only appear on non-static class members, so it's always
6823     // an error here
6824     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6825     D.setInvalidType();
6826     SC = SC_None;
6827   }
6828 
6829   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6830       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6831                               D.getDeclSpec().getStorageClassSpecLoc())) {
6832     // In C++11, the 'register' storage class specifier is deprecated.
6833     // Suppress the warning in system macros, it's used in macros in some
6834     // popular C system headers, such as in glibc's htonl() macro.
6835     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6836          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6837                                    : diag::warn_deprecated_register)
6838       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6839   }
6840 
6841   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6842 
6843   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6844     // C99 6.9p2: The storage-class specifiers auto and register shall not
6845     // appear in the declaration specifiers in an external declaration.
6846     // Global Register+Asm is a GNU extension we support.
6847     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6848       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6849       D.setInvalidType();
6850     }
6851   }
6852 
6853   bool IsMemberSpecialization = false;
6854   bool IsVariableTemplateSpecialization = false;
6855   bool IsPartialSpecialization = false;
6856   bool IsVariableTemplate = false;
6857   VarDecl *NewVD = nullptr;
6858   VarTemplateDecl *NewTemplate = nullptr;
6859   TemplateParameterList *TemplateParams = nullptr;
6860   if (!getLangOpts().CPlusPlus) {
6861     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6862                             II, R, TInfo, SC);
6863 
6864     if (R->getContainedDeducedType())
6865       ParsingInitForAutoVars.insert(NewVD);
6866 
6867     if (D.isInvalidType())
6868       NewVD->setInvalidDecl();
6869 
6870     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6871         NewVD->hasLocalStorage())
6872       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6873                             NTCUC_AutoVar, NTCUK_Destruct);
6874   } else {
6875     bool Invalid = false;
6876 
6877     if (DC->isRecord() && !CurContext->isRecord()) {
6878       // This is an out-of-line definition of a static data member.
6879       switch (SC) {
6880       case SC_None:
6881         break;
6882       case SC_Static:
6883         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6884              diag::err_static_out_of_line)
6885           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6886         break;
6887       case SC_Auto:
6888       case SC_Register:
6889       case SC_Extern:
6890         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6891         // to names of variables declared in a block or to function parameters.
6892         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6893         // of class members
6894 
6895         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6896              diag::err_storage_class_for_static_member)
6897           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6898         break;
6899       case SC_PrivateExtern:
6900         llvm_unreachable("C storage class in c++!");
6901       }
6902     }
6903 
6904     if (SC == SC_Static && CurContext->isRecord()) {
6905       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6906         // Walk up the enclosing DeclContexts to check for any that are
6907         // incompatible with static data members.
6908         const DeclContext *FunctionOrMethod = nullptr;
6909         const CXXRecordDecl *AnonStruct = nullptr;
6910         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6911           if (Ctxt->isFunctionOrMethod()) {
6912             FunctionOrMethod = Ctxt;
6913             break;
6914           }
6915           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6916           if (ParentDecl && !ParentDecl->getDeclName()) {
6917             AnonStruct = ParentDecl;
6918             break;
6919           }
6920         }
6921         if (FunctionOrMethod) {
6922           // C++ [class.static.data]p5: A local class shall not have static data
6923           // members.
6924           Diag(D.getIdentifierLoc(),
6925                diag::err_static_data_member_not_allowed_in_local_class)
6926             << Name << RD->getDeclName() << RD->getTagKind();
6927         } else if (AnonStruct) {
6928           // C++ [class.static.data]p4: Unnamed classes and classes contained
6929           // directly or indirectly within unnamed classes shall not contain
6930           // static data members.
6931           Diag(D.getIdentifierLoc(),
6932                diag::err_static_data_member_not_allowed_in_anon_struct)
6933             << Name << AnonStruct->getTagKind();
6934           Invalid = true;
6935         } else if (RD->isUnion()) {
6936           // C++98 [class.union]p1: If a union contains a static data member,
6937           // the program is ill-formed. C++11 drops this restriction.
6938           Diag(D.getIdentifierLoc(),
6939                getLangOpts().CPlusPlus11
6940                  ? diag::warn_cxx98_compat_static_data_member_in_union
6941                  : diag::ext_static_data_member_in_union) << Name;
6942         }
6943       }
6944     }
6945 
6946     // Match up the template parameter lists with the scope specifier, then
6947     // determine whether we have a template or a template specialization.
6948     bool InvalidScope = false;
6949     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6950         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6951         D.getCXXScopeSpec(),
6952         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6953             ? D.getName().TemplateId
6954             : nullptr,
6955         TemplateParamLists,
6956         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6957     Invalid |= InvalidScope;
6958 
6959     if (TemplateParams) {
6960       if (!TemplateParams->size() &&
6961           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6962         // There is an extraneous 'template<>' for this variable. Complain
6963         // about it, but allow the declaration of the variable.
6964         Diag(TemplateParams->getTemplateLoc(),
6965              diag::err_template_variable_noparams)
6966           << II
6967           << SourceRange(TemplateParams->getTemplateLoc(),
6968                          TemplateParams->getRAngleLoc());
6969         TemplateParams = nullptr;
6970       } else {
6971         // Check that we can declare a template here.
6972         if (CheckTemplateDeclScope(S, TemplateParams))
6973           return nullptr;
6974 
6975         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6976           // This is an explicit specialization or a partial specialization.
6977           IsVariableTemplateSpecialization = true;
6978           IsPartialSpecialization = TemplateParams->size() > 0;
6979         } else { // if (TemplateParams->size() > 0)
6980           // This is a template declaration.
6981           IsVariableTemplate = true;
6982 
6983           // Only C++1y supports variable templates (N3651).
6984           Diag(D.getIdentifierLoc(),
6985                getLangOpts().CPlusPlus14
6986                    ? diag::warn_cxx11_compat_variable_template
6987                    : diag::ext_variable_template);
6988         }
6989       }
6990     } else {
6991       // Check that we can declare a member specialization here.
6992       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
6993           CheckTemplateDeclScope(S, TemplateParamLists.back()))
6994         return nullptr;
6995       assert((Invalid ||
6996               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6997              "should have a 'template<>' for this decl");
6998     }
6999 
7000     if (IsVariableTemplateSpecialization) {
7001       SourceLocation TemplateKWLoc =
7002           TemplateParamLists.size() > 0
7003               ? TemplateParamLists[0]->getTemplateLoc()
7004               : SourceLocation();
7005       DeclResult Res = ActOnVarTemplateSpecialization(
7006           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7007           IsPartialSpecialization);
7008       if (Res.isInvalid())
7009         return nullptr;
7010       NewVD = cast<VarDecl>(Res.get());
7011       AddToScope = false;
7012     } else if (D.isDecompositionDeclarator()) {
7013       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7014                                         D.getIdentifierLoc(), R, TInfo, SC,
7015                                         Bindings);
7016     } else
7017       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7018                               D.getIdentifierLoc(), II, R, TInfo, SC);
7019 
7020     // If this is supposed to be a variable template, create it as such.
7021     if (IsVariableTemplate) {
7022       NewTemplate =
7023           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7024                                   TemplateParams, NewVD);
7025       NewVD->setDescribedVarTemplate(NewTemplate);
7026     }
7027 
7028     // If this decl has an auto type in need of deduction, make a note of the
7029     // Decl so we can diagnose uses of it in its own initializer.
7030     if (R->getContainedDeducedType())
7031       ParsingInitForAutoVars.insert(NewVD);
7032 
7033     if (D.isInvalidType() || Invalid) {
7034       NewVD->setInvalidDecl();
7035       if (NewTemplate)
7036         NewTemplate->setInvalidDecl();
7037     }
7038 
7039     SetNestedNameSpecifier(*this, NewVD, D);
7040 
7041     // If we have any template parameter lists that don't directly belong to
7042     // the variable (matching the scope specifier), store them.
7043     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7044     if (TemplateParamLists.size() > VDTemplateParamLists)
7045       NewVD->setTemplateParameterListsInfo(
7046           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7047   }
7048 
7049   if (D.getDeclSpec().isInlineSpecified()) {
7050     if (!getLangOpts().CPlusPlus) {
7051       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7052           << 0;
7053     } else if (CurContext->isFunctionOrMethod()) {
7054       // 'inline' is not allowed on block scope variable declaration.
7055       Diag(D.getDeclSpec().getInlineSpecLoc(),
7056            diag::err_inline_declaration_block_scope) << Name
7057         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7058     } else {
7059       Diag(D.getDeclSpec().getInlineSpecLoc(),
7060            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7061                                      : diag::ext_inline_variable);
7062       NewVD->setInlineSpecified();
7063     }
7064   }
7065 
7066   // Set the lexical context. If the declarator has a C++ scope specifier, the
7067   // lexical context will be different from the semantic context.
7068   NewVD->setLexicalDeclContext(CurContext);
7069   if (NewTemplate)
7070     NewTemplate->setLexicalDeclContext(CurContext);
7071 
7072   if (IsLocalExternDecl) {
7073     if (D.isDecompositionDeclarator())
7074       for (auto *B : Bindings)
7075         B->setLocalExternDecl();
7076     else
7077       NewVD->setLocalExternDecl();
7078   }
7079 
7080   bool EmitTLSUnsupportedError = false;
7081   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7082     // C++11 [dcl.stc]p4:
7083     //   When thread_local is applied to a variable of block scope the
7084     //   storage-class-specifier static is implied if it does not appear
7085     //   explicitly.
7086     // Core issue: 'static' is not implied if the variable is declared
7087     //   'extern'.
7088     if (NewVD->hasLocalStorage() &&
7089         (SCSpec != DeclSpec::SCS_unspecified ||
7090          TSCS != DeclSpec::TSCS_thread_local ||
7091          !DC->isFunctionOrMethod()))
7092       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7093            diag::err_thread_non_global)
7094         << DeclSpec::getSpecifierName(TSCS);
7095     else if (!Context.getTargetInfo().isTLSSupported()) {
7096       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7097           getLangOpts().SYCLIsDevice) {
7098         // Postpone error emission until we've collected attributes required to
7099         // figure out whether it's a host or device variable and whether the
7100         // error should be ignored.
7101         EmitTLSUnsupportedError = true;
7102         // We still need to mark the variable as TLS so it shows up in AST with
7103         // proper storage class for other tools to use even if we're not going
7104         // to emit any code for it.
7105         NewVD->setTSCSpec(TSCS);
7106       } else
7107         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7108              diag::err_thread_unsupported);
7109     } else
7110       NewVD->setTSCSpec(TSCS);
7111   }
7112 
7113   switch (D.getDeclSpec().getConstexprSpecifier()) {
7114   case CSK_unspecified:
7115     break;
7116 
7117   case CSK_consteval:
7118     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7119         diag::err_constexpr_wrong_decl_kind)
7120       << D.getDeclSpec().getConstexprSpecifier();
7121     LLVM_FALLTHROUGH;
7122 
7123   case CSK_constexpr:
7124     NewVD->setConstexpr(true);
7125     MaybeAddCUDAConstantAttr(NewVD);
7126     // C++1z [dcl.spec.constexpr]p1:
7127     //   A static data member declared with the constexpr specifier is
7128     //   implicitly an inline variable.
7129     if (NewVD->isStaticDataMember() &&
7130         (getLangOpts().CPlusPlus17 ||
7131          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7132       NewVD->setImplicitlyInline();
7133     break;
7134 
7135   case CSK_constinit:
7136     if (!NewVD->hasGlobalStorage())
7137       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7138            diag::err_constinit_local_variable);
7139     else
7140       NewVD->addAttr(ConstInitAttr::Create(
7141           Context, D.getDeclSpec().getConstexprSpecLoc(),
7142           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7143     break;
7144   }
7145 
7146   // C99 6.7.4p3
7147   //   An inline definition of a function with external linkage shall
7148   //   not contain a definition of a modifiable object with static or
7149   //   thread storage duration...
7150   // We only apply this when the function is required to be defined
7151   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7152   // that a local variable with thread storage duration still has to
7153   // be marked 'static'.  Also note that it's possible to get these
7154   // semantics in C++ using __attribute__((gnu_inline)).
7155   if (SC == SC_Static && S->getFnParent() != nullptr &&
7156       !NewVD->getType().isConstQualified()) {
7157     FunctionDecl *CurFD = getCurFunctionDecl();
7158     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7159       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7160            diag::warn_static_local_in_extern_inline);
7161       MaybeSuggestAddingStaticToDecl(CurFD);
7162     }
7163   }
7164 
7165   if (D.getDeclSpec().isModulePrivateSpecified()) {
7166     if (IsVariableTemplateSpecialization)
7167       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7168           << (IsPartialSpecialization ? 1 : 0)
7169           << FixItHint::CreateRemoval(
7170                  D.getDeclSpec().getModulePrivateSpecLoc());
7171     else if (IsMemberSpecialization)
7172       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7173         << 2
7174         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7175     else if (NewVD->hasLocalStorage())
7176       Diag(NewVD->getLocation(), diag::err_module_private_local)
7177           << 0 << NewVD
7178           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7179           << FixItHint::CreateRemoval(
7180                  D.getDeclSpec().getModulePrivateSpecLoc());
7181     else {
7182       NewVD->setModulePrivate();
7183       if (NewTemplate)
7184         NewTemplate->setModulePrivate();
7185       for (auto *B : Bindings)
7186         B->setModulePrivate();
7187     }
7188   }
7189 
7190   if (getLangOpts().OpenCL) {
7191 
7192     deduceOpenCLAddressSpace(NewVD);
7193 
7194     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7195   }
7196 
7197   // Handle attributes prior to checking for duplicates in MergeVarDecl
7198   ProcessDeclAttributes(S, NewVD, D);
7199 
7200   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7201       getLangOpts().SYCLIsDevice) {
7202     if (EmitTLSUnsupportedError &&
7203         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7204          (getLangOpts().OpenMPIsDevice &&
7205           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7206       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7207            diag::err_thread_unsupported);
7208 
7209     if (EmitTLSUnsupportedError &&
7210         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7211       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7212     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7213     // storage [duration]."
7214     if (SC == SC_None && S->getFnParent() != nullptr &&
7215         (NewVD->hasAttr<CUDASharedAttr>() ||
7216          NewVD->hasAttr<CUDAConstantAttr>())) {
7217       NewVD->setStorageClass(SC_Static);
7218     }
7219   }
7220 
7221   // Ensure that dllimport globals without explicit storage class are treated as
7222   // extern. The storage class is set above using parsed attributes. Now we can
7223   // check the VarDecl itself.
7224   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7225          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7226          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7227 
7228   // In auto-retain/release, infer strong retension for variables of
7229   // retainable type.
7230   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7231     NewVD->setInvalidDecl();
7232 
7233   // Handle GNU asm-label extension (encoded as an attribute).
7234   if (Expr *E = (Expr*)D.getAsmLabel()) {
7235     // The parser guarantees this is a string.
7236     StringLiteral *SE = cast<StringLiteral>(E);
7237     StringRef Label = SE->getString();
7238     if (S->getFnParent() != nullptr) {
7239       switch (SC) {
7240       case SC_None:
7241       case SC_Auto:
7242         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7243         break;
7244       case SC_Register:
7245         // Local Named register
7246         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7247             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7248           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7249         break;
7250       case SC_Static:
7251       case SC_Extern:
7252       case SC_PrivateExtern:
7253         break;
7254       }
7255     } else if (SC == SC_Register) {
7256       // Global Named register
7257       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7258         const auto &TI = Context.getTargetInfo();
7259         bool HasSizeMismatch;
7260 
7261         if (!TI.isValidGCCRegisterName(Label))
7262           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7263         else if (!TI.validateGlobalRegisterVariable(Label,
7264                                                     Context.getTypeSize(R),
7265                                                     HasSizeMismatch))
7266           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7267         else if (HasSizeMismatch)
7268           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7269       }
7270 
7271       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7272         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7273         NewVD->setInvalidDecl(true);
7274       }
7275     }
7276 
7277     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7278                                         /*IsLiteralLabel=*/true,
7279                                         SE->getStrTokenLoc(0)));
7280   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7281     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7282       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7283     if (I != ExtnameUndeclaredIdentifiers.end()) {
7284       if (isDeclExternC(NewVD)) {
7285         NewVD->addAttr(I->second);
7286         ExtnameUndeclaredIdentifiers.erase(I);
7287       } else
7288         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7289             << /*Variable*/1 << NewVD;
7290     }
7291   }
7292 
7293   // Find the shadowed declaration before filtering for scope.
7294   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7295                                 ? getShadowedDeclaration(NewVD, Previous)
7296                                 : nullptr;
7297 
7298   // Don't consider existing declarations that are in a different
7299   // scope and are out-of-semantic-context declarations (if the new
7300   // declaration has linkage).
7301   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7302                        D.getCXXScopeSpec().isNotEmpty() ||
7303                        IsMemberSpecialization ||
7304                        IsVariableTemplateSpecialization);
7305 
7306   // Check whether the previous declaration is in the same block scope. This
7307   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7308   if (getLangOpts().CPlusPlus &&
7309       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7310     NewVD->setPreviousDeclInSameBlockScope(
7311         Previous.isSingleResult() && !Previous.isShadowed() &&
7312         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7313 
7314   if (!getLangOpts().CPlusPlus) {
7315     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7316   } else {
7317     // If this is an explicit specialization of a static data member, check it.
7318     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7319         CheckMemberSpecialization(NewVD, Previous))
7320       NewVD->setInvalidDecl();
7321 
7322     // Merge the decl with the existing one if appropriate.
7323     if (!Previous.empty()) {
7324       if (Previous.isSingleResult() &&
7325           isa<FieldDecl>(Previous.getFoundDecl()) &&
7326           D.getCXXScopeSpec().isSet()) {
7327         // The user tried to define a non-static data member
7328         // out-of-line (C++ [dcl.meaning]p1).
7329         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7330           << D.getCXXScopeSpec().getRange();
7331         Previous.clear();
7332         NewVD->setInvalidDecl();
7333       }
7334     } else if (D.getCXXScopeSpec().isSet()) {
7335       // No previous declaration in the qualifying scope.
7336       Diag(D.getIdentifierLoc(), diag::err_no_member)
7337         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7338         << D.getCXXScopeSpec().getRange();
7339       NewVD->setInvalidDecl();
7340     }
7341 
7342     if (!IsVariableTemplateSpecialization)
7343       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7344 
7345     if (NewTemplate) {
7346       VarTemplateDecl *PrevVarTemplate =
7347           NewVD->getPreviousDecl()
7348               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7349               : nullptr;
7350 
7351       // Check the template parameter list of this declaration, possibly
7352       // merging in the template parameter list from the previous variable
7353       // template declaration.
7354       if (CheckTemplateParameterList(
7355               TemplateParams,
7356               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7357                               : nullptr,
7358               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7359                DC->isDependentContext())
7360                   ? TPC_ClassTemplateMember
7361                   : TPC_VarTemplate))
7362         NewVD->setInvalidDecl();
7363 
7364       // If we are providing an explicit specialization of a static variable
7365       // template, make a note of that.
7366       if (PrevVarTemplate &&
7367           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7368         PrevVarTemplate->setMemberSpecialization();
7369     }
7370   }
7371 
7372   // Diagnose shadowed variables iff this isn't a redeclaration.
7373   if (ShadowedDecl && !D.isRedeclaration())
7374     CheckShadow(NewVD, ShadowedDecl, Previous);
7375 
7376   ProcessPragmaWeak(S, NewVD);
7377 
7378   // If this is the first declaration of an extern C variable, update
7379   // the map of such variables.
7380   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7381       isIncompleteDeclExternC(*this, NewVD))
7382     RegisterLocallyScopedExternCDecl(NewVD, S);
7383 
7384   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7385     MangleNumberingContext *MCtx;
7386     Decl *ManglingContextDecl;
7387     std::tie(MCtx, ManglingContextDecl) =
7388         getCurrentMangleNumberContext(NewVD->getDeclContext());
7389     if (MCtx) {
7390       Context.setManglingNumber(
7391           NewVD, MCtx->getManglingNumber(
7392                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7393       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7394     }
7395   }
7396 
7397   // Special handling of variable named 'main'.
7398   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7399       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7400       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7401 
7402     // C++ [basic.start.main]p3
7403     // A program that declares a variable main at global scope is ill-formed.
7404     if (getLangOpts().CPlusPlus)
7405       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7406 
7407     // In C, and external-linkage variable named main results in undefined
7408     // behavior.
7409     else if (NewVD->hasExternalFormalLinkage())
7410       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7411   }
7412 
7413   if (D.isRedeclaration() && !Previous.empty()) {
7414     NamedDecl *Prev = Previous.getRepresentativeDecl();
7415     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7416                                    D.isFunctionDefinition());
7417   }
7418 
7419   if (NewTemplate) {
7420     if (NewVD->isInvalidDecl())
7421       NewTemplate->setInvalidDecl();
7422     ActOnDocumentableDecl(NewTemplate);
7423     return NewTemplate;
7424   }
7425 
7426   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7427     CompleteMemberSpecialization(NewVD, Previous);
7428 
7429   return NewVD;
7430 }
7431 
7432 /// Enum describing the %select options in diag::warn_decl_shadow.
7433 enum ShadowedDeclKind {
7434   SDK_Local,
7435   SDK_Global,
7436   SDK_StaticMember,
7437   SDK_Field,
7438   SDK_Typedef,
7439   SDK_Using
7440 };
7441 
7442 /// Determine what kind of declaration we're shadowing.
7443 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7444                                                 const DeclContext *OldDC) {
7445   if (isa<TypeAliasDecl>(ShadowedDecl))
7446     return SDK_Using;
7447   else if (isa<TypedefDecl>(ShadowedDecl))
7448     return SDK_Typedef;
7449   else if (isa<RecordDecl>(OldDC))
7450     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7451 
7452   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7453 }
7454 
7455 /// Return the location of the capture if the given lambda captures the given
7456 /// variable \p VD, or an invalid source location otherwise.
7457 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7458                                          const VarDecl *VD) {
7459   for (const Capture &Capture : LSI->Captures) {
7460     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7461       return Capture.getLocation();
7462   }
7463   return SourceLocation();
7464 }
7465 
7466 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7467                                      const LookupResult &R) {
7468   // Only diagnose if we're shadowing an unambiguous field or variable.
7469   if (R.getResultKind() != LookupResult::Found)
7470     return false;
7471 
7472   // Return false if warning is ignored.
7473   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7474 }
7475 
7476 /// Return the declaration shadowed by the given variable \p D, or null
7477 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7478 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7479                                         const LookupResult &R) {
7480   if (!shouldWarnIfShadowedDecl(Diags, R))
7481     return nullptr;
7482 
7483   // Don't diagnose declarations at file scope.
7484   if (D->hasGlobalStorage())
7485     return nullptr;
7486 
7487   NamedDecl *ShadowedDecl = R.getFoundDecl();
7488   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7489              ? ShadowedDecl
7490              : nullptr;
7491 }
7492 
7493 /// Return the declaration shadowed by the given typedef \p D, or null
7494 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7495 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7496                                         const LookupResult &R) {
7497   // Don't warn if typedef declaration is part of a class
7498   if (D->getDeclContext()->isRecord())
7499     return nullptr;
7500 
7501   if (!shouldWarnIfShadowedDecl(Diags, R))
7502     return nullptr;
7503 
7504   NamedDecl *ShadowedDecl = R.getFoundDecl();
7505   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7506 }
7507 
7508 /// Diagnose variable or built-in function shadowing.  Implements
7509 /// -Wshadow.
7510 ///
7511 /// This method is called whenever a VarDecl is added to a "useful"
7512 /// scope.
7513 ///
7514 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7515 /// \param R the lookup of the name
7516 ///
7517 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7518                        const LookupResult &R) {
7519   DeclContext *NewDC = D->getDeclContext();
7520 
7521   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7522     // Fields are not shadowed by variables in C++ static methods.
7523     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7524       if (MD->isStatic())
7525         return;
7526 
7527     // Fields shadowed by constructor parameters are a special case. Usually
7528     // the constructor initializes the field with the parameter.
7529     if (isa<CXXConstructorDecl>(NewDC))
7530       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7531         // Remember that this was shadowed so we can either warn about its
7532         // modification or its existence depending on warning settings.
7533         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7534         return;
7535       }
7536   }
7537 
7538   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7539     if (shadowedVar->isExternC()) {
7540       // For shadowing external vars, make sure that we point to the global
7541       // declaration, not a locally scoped extern declaration.
7542       for (auto I : shadowedVar->redecls())
7543         if (I->isFileVarDecl()) {
7544           ShadowedDecl = I;
7545           break;
7546         }
7547     }
7548 
7549   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7550 
7551   unsigned WarningDiag = diag::warn_decl_shadow;
7552   SourceLocation CaptureLoc;
7553   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7554       isa<CXXMethodDecl>(NewDC)) {
7555     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7556       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7557         if (RD->getLambdaCaptureDefault() == LCD_None) {
7558           // Try to avoid warnings for lambdas with an explicit capture list.
7559           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7560           // Warn only when the lambda captures the shadowed decl explicitly.
7561           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7562           if (CaptureLoc.isInvalid())
7563             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7564         } else {
7565           // Remember that this was shadowed so we can avoid the warning if the
7566           // shadowed decl isn't captured and the warning settings allow it.
7567           cast<LambdaScopeInfo>(getCurFunction())
7568               ->ShadowingDecls.push_back(
7569                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7570           return;
7571         }
7572       }
7573 
7574       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7575         // A variable can't shadow a local variable in an enclosing scope, if
7576         // they are separated by a non-capturing declaration context.
7577         for (DeclContext *ParentDC = NewDC;
7578              ParentDC && !ParentDC->Equals(OldDC);
7579              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7580           // Only block literals, captured statements, and lambda expressions
7581           // can capture; other scopes don't.
7582           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7583               !isLambdaCallOperator(ParentDC)) {
7584             return;
7585           }
7586         }
7587       }
7588     }
7589   }
7590 
7591   // Only warn about certain kinds of shadowing for class members.
7592   if (NewDC && NewDC->isRecord()) {
7593     // In particular, don't warn about shadowing non-class members.
7594     if (!OldDC->isRecord())
7595       return;
7596 
7597     // TODO: should we warn about static data members shadowing
7598     // static data members from base classes?
7599 
7600     // TODO: don't diagnose for inaccessible shadowed members.
7601     // This is hard to do perfectly because we might friend the
7602     // shadowing context, but that's just a false negative.
7603   }
7604 
7605 
7606   DeclarationName Name = R.getLookupName();
7607 
7608   // Emit warning and note.
7609   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7610     return;
7611   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7612   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7613   if (!CaptureLoc.isInvalid())
7614     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7615         << Name << /*explicitly*/ 1;
7616   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7617 }
7618 
7619 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7620 /// when these variables are captured by the lambda.
7621 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7622   for (const auto &Shadow : LSI->ShadowingDecls) {
7623     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7624     // Try to avoid the warning when the shadowed decl isn't captured.
7625     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7626     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7627     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7628                                        ? diag::warn_decl_shadow_uncaptured_local
7629                                        : diag::warn_decl_shadow)
7630         << Shadow.VD->getDeclName()
7631         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7632     if (!CaptureLoc.isInvalid())
7633       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7634           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7635     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7636   }
7637 }
7638 
7639 /// Check -Wshadow without the advantage of a previous lookup.
7640 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7641   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7642     return;
7643 
7644   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7645                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7646   LookupName(R, S);
7647   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7648     CheckShadow(D, ShadowedDecl, R);
7649 }
7650 
7651 /// Check if 'E', which is an expression that is about to be modified, refers
7652 /// to a constructor parameter that shadows a field.
7653 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7654   // Quickly ignore expressions that can't be shadowing ctor parameters.
7655   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7656     return;
7657   E = E->IgnoreParenImpCasts();
7658   auto *DRE = dyn_cast<DeclRefExpr>(E);
7659   if (!DRE)
7660     return;
7661   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7662   auto I = ShadowingDecls.find(D);
7663   if (I == ShadowingDecls.end())
7664     return;
7665   const NamedDecl *ShadowedDecl = I->second;
7666   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7667   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7668   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7669   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7670 
7671   // Avoid issuing multiple warnings about the same decl.
7672   ShadowingDecls.erase(I);
7673 }
7674 
7675 /// Check for conflict between this global or extern "C" declaration and
7676 /// previous global or extern "C" declarations. This is only used in C++.
7677 template<typename T>
7678 static bool checkGlobalOrExternCConflict(
7679     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7680   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7681   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7682 
7683   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7684     // The common case: this global doesn't conflict with any extern "C"
7685     // declaration.
7686     return false;
7687   }
7688 
7689   if (Prev) {
7690     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7691       // Both the old and new declarations have C language linkage. This is a
7692       // redeclaration.
7693       Previous.clear();
7694       Previous.addDecl(Prev);
7695       return true;
7696     }
7697 
7698     // This is a global, non-extern "C" declaration, and there is a previous
7699     // non-global extern "C" declaration. Diagnose if this is a variable
7700     // declaration.
7701     if (!isa<VarDecl>(ND))
7702       return false;
7703   } else {
7704     // The declaration is extern "C". Check for any declaration in the
7705     // translation unit which might conflict.
7706     if (IsGlobal) {
7707       // We have already performed the lookup into the translation unit.
7708       IsGlobal = false;
7709       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7710            I != E; ++I) {
7711         if (isa<VarDecl>(*I)) {
7712           Prev = *I;
7713           break;
7714         }
7715       }
7716     } else {
7717       DeclContext::lookup_result R =
7718           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7719       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7720            I != E; ++I) {
7721         if (isa<VarDecl>(*I)) {
7722           Prev = *I;
7723           break;
7724         }
7725         // FIXME: If we have any other entity with this name in global scope,
7726         // the declaration is ill-formed, but that is a defect: it breaks the
7727         // 'stat' hack, for instance. Only variables can have mangled name
7728         // clashes with extern "C" declarations, so only they deserve a
7729         // diagnostic.
7730       }
7731     }
7732 
7733     if (!Prev)
7734       return false;
7735   }
7736 
7737   // Use the first declaration's location to ensure we point at something which
7738   // is lexically inside an extern "C" linkage-spec.
7739   assert(Prev && "should have found a previous declaration to diagnose");
7740   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7741     Prev = FD->getFirstDecl();
7742   else
7743     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7744 
7745   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7746     << IsGlobal << ND;
7747   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7748     << IsGlobal;
7749   return false;
7750 }
7751 
7752 /// Apply special rules for handling extern "C" declarations. Returns \c true
7753 /// if we have found that this is a redeclaration of some prior entity.
7754 ///
7755 /// Per C++ [dcl.link]p6:
7756 ///   Two declarations [for a function or variable] with C language linkage
7757 ///   with the same name that appear in different scopes refer to the same
7758 ///   [entity]. An entity with C language linkage shall not be declared with
7759 ///   the same name as an entity in global scope.
7760 template<typename T>
7761 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7762                                                   LookupResult &Previous) {
7763   if (!S.getLangOpts().CPlusPlus) {
7764     // In C, when declaring a global variable, look for a corresponding 'extern'
7765     // variable declared in function scope. We don't need this in C++, because
7766     // we find local extern decls in the surrounding file-scope DeclContext.
7767     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7768       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7769         Previous.clear();
7770         Previous.addDecl(Prev);
7771         return true;
7772       }
7773     }
7774     return false;
7775   }
7776 
7777   // A declaration in the translation unit can conflict with an extern "C"
7778   // declaration.
7779   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7780     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7781 
7782   // An extern "C" declaration can conflict with a declaration in the
7783   // translation unit or can be a redeclaration of an extern "C" declaration
7784   // in another scope.
7785   if (isIncompleteDeclExternC(S,ND))
7786     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7787 
7788   // Neither global nor extern "C": nothing to do.
7789   return false;
7790 }
7791 
7792 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7793   // If the decl is already known invalid, don't check it.
7794   if (NewVD->isInvalidDecl())
7795     return;
7796 
7797   QualType T = NewVD->getType();
7798 
7799   // Defer checking an 'auto' type until its initializer is attached.
7800   if (T->isUndeducedType())
7801     return;
7802 
7803   if (NewVD->hasAttrs())
7804     CheckAlignasUnderalignment(NewVD);
7805 
7806   if (T->isObjCObjectType()) {
7807     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7808       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7809     T = Context.getObjCObjectPointerType(T);
7810     NewVD->setType(T);
7811   }
7812 
7813   // Emit an error if an address space was applied to decl with local storage.
7814   // This includes arrays of objects with address space qualifiers, but not
7815   // automatic variables that point to other address spaces.
7816   // ISO/IEC TR 18037 S5.1.2
7817   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7818       T.getAddressSpace() != LangAS::Default) {
7819     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7820     NewVD->setInvalidDecl();
7821     return;
7822   }
7823 
7824   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7825   // scope.
7826   if (getLangOpts().OpenCLVersion == 120 &&
7827       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7828       NewVD->isStaticLocal()) {
7829     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7830     NewVD->setInvalidDecl();
7831     return;
7832   }
7833 
7834   if (getLangOpts().OpenCL) {
7835     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7836     if (NewVD->hasAttr<BlocksAttr>()) {
7837       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7838       return;
7839     }
7840 
7841     if (T->isBlockPointerType()) {
7842       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7843       // can't use 'extern' storage class.
7844       if (!T.isConstQualified()) {
7845         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7846             << 0 /*const*/;
7847         NewVD->setInvalidDecl();
7848         return;
7849       }
7850       if (NewVD->hasExternalStorage()) {
7851         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7852         NewVD->setInvalidDecl();
7853         return;
7854       }
7855     }
7856     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7857     // __constant address space.
7858     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7859     // variables inside a function can also be declared in the global
7860     // address space.
7861     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7862     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7863     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7864         NewVD->hasExternalStorage()) {
7865       if (!T->isSamplerT() &&
7866           !T->isDependentType() &&
7867           !(T.getAddressSpace() == LangAS::opencl_constant ||
7868             (T.getAddressSpace() == LangAS::opencl_global &&
7869              (getLangOpts().OpenCLVersion == 200 ||
7870               getLangOpts().OpenCLCPlusPlus)))) {
7871         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7872         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7873           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7874               << Scope << "global or constant";
7875         else
7876           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7877               << Scope << "constant";
7878         NewVD->setInvalidDecl();
7879         return;
7880       }
7881     } else {
7882       if (T.getAddressSpace() == LangAS::opencl_global) {
7883         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7884             << 1 /*is any function*/ << "global";
7885         NewVD->setInvalidDecl();
7886         return;
7887       }
7888       if (T.getAddressSpace() == LangAS::opencl_constant ||
7889           T.getAddressSpace() == LangAS::opencl_local) {
7890         FunctionDecl *FD = getCurFunctionDecl();
7891         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7892         // in functions.
7893         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7894           if (T.getAddressSpace() == LangAS::opencl_constant)
7895             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7896                 << 0 /*non-kernel only*/ << "constant";
7897           else
7898             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7899                 << 0 /*non-kernel only*/ << "local";
7900           NewVD->setInvalidDecl();
7901           return;
7902         }
7903         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7904         // in the outermost scope of a kernel function.
7905         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7906           if (!getCurScope()->isFunctionScope()) {
7907             if (T.getAddressSpace() == LangAS::opencl_constant)
7908               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7909                   << "constant";
7910             else
7911               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7912                   << "local";
7913             NewVD->setInvalidDecl();
7914             return;
7915           }
7916         }
7917       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7918                  // If we are parsing a template we didn't deduce an addr
7919                  // space yet.
7920                  T.getAddressSpace() != LangAS::Default) {
7921         // Do not allow other address spaces on automatic variable.
7922         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7923         NewVD->setInvalidDecl();
7924         return;
7925       }
7926     }
7927   }
7928 
7929   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7930       && !NewVD->hasAttr<BlocksAttr>()) {
7931     if (getLangOpts().getGC() != LangOptions::NonGC)
7932       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7933     else {
7934       assert(!getLangOpts().ObjCAutoRefCount);
7935       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7936     }
7937   }
7938 
7939   bool isVM = T->isVariablyModifiedType();
7940   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7941       NewVD->hasAttr<BlocksAttr>())
7942     setFunctionHasBranchProtectedScope();
7943 
7944   if ((isVM && NewVD->hasLinkage()) ||
7945       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7946     bool SizeIsNegative;
7947     llvm::APSInt Oversized;
7948     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7949         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7950     QualType FixedT;
7951     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7952       FixedT = FixedTInfo->getType();
7953     else if (FixedTInfo) {
7954       // Type and type-as-written are canonically different. We need to fix up
7955       // both types separately.
7956       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7957                                                    Oversized);
7958     }
7959     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7960       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7961       // FIXME: This won't give the correct result for
7962       // int a[10][n];
7963       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7964 
7965       if (NewVD->isFileVarDecl())
7966         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7967         << SizeRange;
7968       else if (NewVD->isStaticLocal())
7969         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7970         << SizeRange;
7971       else
7972         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7973         << SizeRange;
7974       NewVD->setInvalidDecl();
7975       return;
7976     }
7977 
7978     if (!FixedTInfo) {
7979       if (NewVD->isFileVarDecl())
7980         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7981       else
7982         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7983       NewVD->setInvalidDecl();
7984       return;
7985     }
7986 
7987     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7988     NewVD->setType(FixedT);
7989     NewVD->setTypeSourceInfo(FixedTInfo);
7990   }
7991 
7992   if (T->isVoidType()) {
7993     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7994     //                    of objects and functions.
7995     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7996       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7997         << T;
7998       NewVD->setInvalidDecl();
7999       return;
8000     }
8001   }
8002 
8003   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8004     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8005     NewVD->setInvalidDecl();
8006     return;
8007   }
8008 
8009   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8010     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8011     NewVD->setInvalidDecl();
8012     return;
8013   }
8014 
8015   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8016     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8017     NewVD->setInvalidDecl();
8018     return;
8019   }
8020 
8021   if (NewVD->isConstexpr() && !T->isDependentType() &&
8022       RequireLiteralType(NewVD->getLocation(), T,
8023                          diag::err_constexpr_var_non_literal)) {
8024     NewVD->setInvalidDecl();
8025     return;
8026   }
8027 }
8028 
8029 /// Perform semantic checking on a newly-created variable
8030 /// declaration.
8031 ///
8032 /// This routine performs all of the type-checking required for a
8033 /// variable declaration once it has been built. It is used both to
8034 /// check variables after they have been parsed and their declarators
8035 /// have been translated into a declaration, and to check variables
8036 /// that have been instantiated from a template.
8037 ///
8038 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8039 ///
8040 /// Returns true if the variable declaration is a redeclaration.
8041 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8042   CheckVariableDeclarationType(NewVD);
8043 
8044   // If the decl is already known invalid, don't check it.
8045   if (NewVD->isInvalidDecl())
8046     return false;
8047 
8048   // If we did not find anything by this name, look for a non-visible
8049   // extern "C" declaration with the same name.
8050   if (Previous.empty() &&
8051       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8052     Previous.setShadowed();
8053 
8054   if (!Previous.empty()) {
8055     MergeVarDecl(NewVD, Previous);
8056     return true;
8057   }
8058   return false;
8059 }
8060 
8061 namespace {
8062 struct FindOverriddenMethod {
8063   Sema *S;
8064   CXXMethodDecl *Method;
8065 
8066   /// Member lookup function that determines whether a given C++
8067   /// method overrides a method in a base class, to be used with
8068   /// CXXRecordDecl::lookupInBases().
8069   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8070     RecordDecl *BaseRecord =
8071         Specifier->getType()->castAs<RecordType>()->getDecl();
8072 
8073     DeclarationName Name = Method->getDeclName();
8074 
8075     // FIXME: Do we care about other names here too?
8076     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8077       // We really want to find the base class destructor here.
8078       QualType T = S->Context.getTypeDeclType(BaseRecord);
8079       CanQualType CT = S->Context.getCanonicalType(T);
8080 
8081       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8082     }
8083 
8084     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8085          Path.Decls = Path.Decls.slice(1)) {
8086       NamedDecl *D = Path.Decls.front();
8087       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8088         if (MD->isVirtual() &&
8089             !S->IsOverload(
8090                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8091                 /*ConsiderCudaAttrs=*/true,
8092                 // C++2a [class.virtual]p2 does not consider requires clauses
8093                 // when overriding.
8094                 /*ConsiderRequiresClauses=*/false))
8095           return true;
8096       }
8097     }
8098 
8099     return false;
8100   }
8101 };
8102 } // end anonymous namespace
8103 
8104 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8105 /// and if so, check that it's a valid override and remember it.
8106 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8107   // Look for methods in base classes that this method might override.
8108   CXXBasePaths Paths;
8109   FindOverriddenMethod FOM;
8110   FOM.Method = MD;
8111   FOM.S = this;
8112   bool AddedAny = false;
8113   if (DC->lookupInBases(FOM, Paths)) {
8114     for (auto *I : Paths.found_decls()) {
8115       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8116         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8117         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8118             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8119             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8120             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8121           AddedAny = true;
8122         }
8123       }
8124     }
8125   }
8126 
8127   return AddedAny;
8128 }
8129 
8130 namespace {
8131   // Struct for holding all of the extra arguments needed by
8132   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8133   struct ActOnFDArgs {
8134     Scope *S;
8135     Declarator &D;
8136     MultiTemplateParamsArg TemplateParamLists;
8137     bool AddToScope;
8138   };
8139 } // end anonymous namespace
8140 
8141 namespace {
8142 
8143 // Callback to only accept typo corrections that have a non-zero edit distance.
8144 // Also only accept corrections that have the same parent decl.
8145 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8146  public:
8147   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8148                             CXXRecordDecl *Parent)
8149       : Context(Context), OriginalFD(TypoFD),
8150         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8151 
8152   bool ValidateCandidate(const TypoCorrection &candidate) override {
8153     if (candidate.getEditDistance() == 0)
8154       return false;
8155 
8156     SmallVector<unsigned, 1> MismatchedParams;
8157     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8158                                           CDeclEnd = candidate.end();
8159          CDecl != CDeclEnd; ++CDecl) {
8160       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8161 
8162       if (FD && !FD->hasBody() &&
8163           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8164         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8165           CXXRecordDecl *Parent = MD->getParent();
8166           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8167             return true;
8168         } else if (!ExpectedParent) {
8169           return true;
8170         }
8171       }
8172     }
8173 
8174     return false;
8175   }
8176 
8177   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8178     return std::make_unique<DifferentNameValidatorCCC>(*this);
8179   }
8180 
8181  private:
8182   ASTContext &Context;
8183   FunctionDecl *OriginalFD;
8184   CXXRecordDecl *ExpectedParent;
8185 };
8186 
8187 } // end anonymous namespace
8188 
8189 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8190   TypoCorrectedFunctionDefinitions.insert(F);
8191 }
8192 
8193 /// Generate diagnostics for an invalid function redeclaration.
8194 ///
8195 /// This routine handles generating the diagnostic messages for an invalid
8196 /// function redeclaration, including finding possible similar declarations
8197 /// or performing typo correction if there are no previous declarations with
8198 /// the same name.
8199 ///
8200 /// Returns a NamedDecl iff typo correction was performed and substituting in
8201 /// the new declaration name does not cause new errors.
8202 static NamedDecl *DiagnoseInvalidRedeclaration(
8203     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8204     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8205   DeclarationName Name = NewFD->getDeclName();
8206   DeclContext *NewDC = NewFD->getDeclContext();
8207   SmallVector<unsigned, 1> MismatchedParams;
8208   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8209   TypoCorrection Correction;
8210   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8211   unsigned DiagMsg =
8212     IsLocalFriend ? diag::err_no_matching_local_friend :
8213     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8214     diag::err_member_decl_does_not_match;
8215   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8216                     IsLocalFriend ? Sema::LookupLocalFriendName
8217                                   : Sema::LookupOrdinaryName,
8218                     Sema::ForVisibleRedeclaration);
8219 
8220   NewFD->setInvalidDecl();
8221   if (IsLocalFriend)
8222     SemaRef.LookupName(Prev, S);
8223   else
8224     SemaRef.LookupQualifiedName(Prev, NewDC);
8225   assert(!Prev.isAmbiguous() &&
8226          "Cannot have an ambiguity in previous-declaration lookup");
8227   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8228   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8229                                 MD ? MD->getParent() : nullptr);
8230   if (!Prev.empty()) {
8231     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8232          Func != FuncEnd; ++Func) {
8233       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8234       if (FD &&
8235           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8236         // Add 1 to the index so that 0 can mean the mismatch didn't
8237         // involve a parameter
8238         unsigned ParamNum =
8239             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8240         NearMatches.push_back(std::make_pair(FD, ParamNum));
8241       }
8242     }
8243   // If the qualified name lookup yielded nothing, try typo correction
8244   } else if ((Correction = SemaRef.CorrectTypo(
8245                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8246                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8247                   IsLocalFriend ? nullptr : NewDC))) {
8248     // Set up everything for the call to ActOnFunctionDeclarator
8249     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8250                               ExtraArgs.D.getIdentifierLoc());
8251     Previous.clear();
8252     Previous.setLookupName(Correction.getCorrection());
8253     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8254                                     CDeclEnd = Correction.end();
8255          CDecl != CDeclEnd; ++CDecl) {
8256       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8257       if (FD && !FD->hasBody() &&
8258           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8259         Previous.addDecl(FD);
8260       }
8261     }
8262     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8263 
8264     NamedDecl *Result;
8265     // Retry building the function declaration with the new previous
8266     // declarations, and with errors suppressed.
8267     {
8268       // Trap errors.
8269       Sema::SFINAETrap Trap(SemaRef);
8270 
8271       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8272       // pieces need to verify the typo-corrected C++ declaration and hopefully
8273       // eliminate the need for the parameter pack ExtraArgs.
8274       Result = SemaRef.ActOnFunctionDeclarator(
8275           ExtraArgs.S, ExtraArgs.D,
8276           Correction.getCorrectionDecl()->getDeclContext(),
8277           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8278           ExtraArgs.AddToScope);
8279 
8280       if (Trap.hasErrorOccurred())
8281         Result = nullptr;
8282     }
8283 
8284     if (Result) {
8285       // Determine which correction we picked.
8286       Decl *Canonical = Result->getCanonicalDecl();
8287       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8288            I != E; ++I)
8289         if ((*I)->getCanonicalDecl() == Canonical)
8290           Correction.setCorrectionDecl(*I);
8291 
8292       // Let Sema know about the correction.
8293       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8294       SemaRef.diagnoseTypo(
8295           Correction,
8296           SemaRef.PDiag(IsLocalFriend
8297                           ? diag::err_no_matching_local_friend_suggest
8298                           : diag::err_member_decl_does_not_match_suggest)
8299             << Name << NewDC << IsDefinition);
8300       return Result;
8301     }
8302 
8303     // Pretend the typo correction never occurred
8304     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8305                               ExtraArgs.D.getIdentifierLoc());
8306     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8307     Previous.clear();
8308     Previous.setLookupName(Name);
8309   }
8310 
8311   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8312       << Name << NewDC << IsDefinition << NewFD->getLocation();
8313 
8314   bool NewFDisConst = false;
8315   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8316     NewFDisConst = NewMD->isConst();
8317 
8318   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8319        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8320        NearMatch != NearMatchEnd; ++NearMatch) {
8321     FunctionDecl *FD = NearMatch->first;
8322     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8323     bool FDisConst = MD && MD->isConst();
8324     bool IsMember = MD || !IsLocalFriend;
8325 
8326     // FIXME: These notes are poorly worded for the local friend case.
8327     if (unsigned Idx = NearMatch->second) {
8328       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8329       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8330       if (Loc.isInvalid()) Loc = FD->getLocation();
8331       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8332                                  : diag::note_local_decl_close_param_match)
8333         << Idx << FDParam->getType()
8334         << NewFD->getParamDecl(Idx - 1)->getType();
8335     } else if (FDisConst != NewFDisConst) {
8336       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8337           << NewFDisConst << FD->getSourceRange().getEnd();
8338     } else
8339       SemaRef.Diag(FD->getLocation(),
8340                    IsMember ? diag::note_member_def_close_match
8341                             : diag::note_local_decl_close_match);
8342   }
8343   return nullptr;
8344 }
8345 
8346 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8347   switch (D.getDeclSpec().getStorageClassSpec()) {
8348   default: llvm_unreachable("Unknown storage class!");
8349   case DeclSpec::SCS_auto:
8350   case DeclSpec::SCS_register:
8351   case DeclSpec::SCS_mutable:
8352     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8353                  diag::err_typecheck_sclass_func);
8354     D.getMutableDeclSpec().ClearStorageClassSpecs();
8355     D.setInvalidType();
8356     break;
8357   case DeclSpec::SCS_unspecified: break;
8358   case DeclSpec::SCS_extern:
8359     if (D.getDeclSpec().isExternInLinkageSpec())
8360       return SC_None;
8361     return SC_Extern;
8362   case DeclSpec::SCS_static: {
8363     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8364       // C99 6.7.1p5:
8365       //   The declaration of an identifier for a function that has
8366       //   block scope shall have no explicit storage-class specifier
8367       //   other than extern
8368       // See also (C++ [dcl.stc]p4).
8369       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8370                    diag::err_static_block_func);
8371       break;
8372     } else
8373       return SC_Static;
8374   }
8375   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8376   }
8377 
8378   // No explicit storage class has already been returned
8379   return SC_None;
8380 }
8381 
8382 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8383                                            DeclContext *DC, QualType &R,
8384                                            TypeSourceInfo *TInfo,
8385                                            StorageClass SC,
8386                                            bool &IsVirtualOkay) {
8387   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8388   DeclarationName Name = NameInfo.getName();
8389 
8390   FunctionDecl *NewFD = nullptr;
8391   bool isInline = D.getDeclSpec().isInlineSpecified();
8392 
8393   if (!SemaRef.getLangOpts().CPlusPlus) {
8394     // Determine whether the function was written with a
8395     // prototype. This true when:
8396     //   - there is a prototype in the declarator, or
8397     //   - the type R of the function is some kind of typedef or other non-
8398     //     attributed reference to a type name (which eventually refers to a
8399     //     function type).
8400     bool HasPrototype =
8401       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8402       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8403 
8404     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8405                                  R, TInfo, SC, isInline, HasPrototype,
8406                                  CSK_unspecified,
8407                                  /*TrailingRequiresClause=*/nullptr);
8408     if (D.isInvalidType())
8409       NewFD->setInvalidDecl();
8410 
8411     return NewFD;
8412   }
8413 
8414   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8415 
8416   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8417   if (ConstexprKind == CSK_constinit) {
8418     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8419                  diag::err_constexpr_wrong_decl_kind)
8420         << ConstexprKind;
8421     ConstexprKind = CSK_unspecified;
8422     D.getMutableDeclSpec().ClearConstexprSpec();
8423   }
8424   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8425 
8426   // Check that the return type is not an abstract class type.
8427   // For record types, this is done by the AbstractClassUsageDiagnoser once
8428   // the class has been completely parsed.
8429   if (!DC->isRecord() &&
8430       SemaRef.RequireNonAbstractType(
8431           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8432           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8433     D.setInvalidType();
8434 
8435   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8436     // This is a C++ constructor declaration.
8437     assert(DC->isRecord() &&
8438            "Constructors can only be declared in a member context");
8439 
8440     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8441     return CXXConstructorDecl::Create(
8442         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8443         TInfo, ExplicitSpecifier, isInline,
8444         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8445         TrailingRequiresClause);
8446 
8447   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8448     // This is a C++ destructor declaration.
8449     if (DC->isRecord()) {
8450       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8451       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8452       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8453           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8454           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8455           TrailingRequiresClause);
8456 
8457       // If the destructor needs an implicit exception specification, set it
8458       // now. FIXME: It'd be nice to be able to create the right type to start
8459       // with, but the type needs to reference the destructor declaration.
8460       if (SemaRef.getLangOpts().CPlusPlus11)
8461         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8462 
8463       IsVirtualOkay = true;
8464       return NewDD;
8465 
8466     } else {
8467       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8468       D.setInvalidType();
8469 
8470       // Create a FunctionDecl to satisfy the function definition parsing
8471       // code path.
8472       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8473                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8474                                   isInline,
8475                                   /*hasPrototype=*/true, ConstexprKind,
8476                                   TrailingRequiresClause);
8477     }
8478 
8479   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8480     if (!DC->isRecord()) {
8481       SemaRef.Diag(D.getIdentifierLoc(),
8482            diag::err_conv_function_not_member);
8483       return nullptr;
8484     }
8485 
8486     SemaRef.CheckConversionDeclarator(D, R, SC);
8487     if (D.isInvalidType())
8488       return nullptr;
8489 
8490     IsVirtualOkay = true;
8491     return CXXConversionDecl::Create(
8492         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8493         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8494         TrailingRequiresClause);
8495 
8496   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8497     if (TrailingRequiresClause)
8498       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8499                    diag::err_trailing_requires_clause_on_deduction_guide)
8500           << TrailingRequiresClause->getSourceRange();
8501     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8502 
8503     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8504                                          ExplicitSpecifier, NameInfo, R, TInfo,
8505                                          D.getEndLoc());
8506   } else if (DC->isRecord()) {
8507     // If the name of the function is the same as the name of the record,
8508     // then this must be an invalid constructor that has a return type.
8509     // (The parser checks for a return type and makes the declarator a
8510     // constructor if it has no return type).
8511     if (Name.getAsIdentifierInfo() &&
8512         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8513       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8514         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8515         << SourceRange(D.getIdentifierLoc());
8516       return nullptr;
8517     }
8518 
8519     // This is a C++ method declaration.
8520     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8521         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8522         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8523         TrailingRequiresClause);
8524     IsVirtualOkay = !Ret->isStatic();
8525     return Ret;
8526   } else {
8527     bool isFriend =
8528         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8529     if (!isFriend && SemaRef.CurContext->isRecord())
8530       return nullptr;
8531 
8532     // Determine whether the function was written with a
8533     // prototype. This true when:
8534     //   - we're in C++ (where every function has a prototype),
8535     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8536                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8537                                 ConstexprKind, TrailingRequiresClause);
8538   }
8539 }
8540 
8541 enum OpenCLParamType {
8542   ValidKernelParam,
8543   PtrPtrKernelParam,
8544   PtrKernelParam,
8545   InvalidAddrSpacePtrKernelParam,
8546   InvalidKernelParam,
8547   RecordKernelParam
8548 };
8549 
8550 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8551   // Size dependent types are just typedefs to normal integer types
8552   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8553   // integers other than by their names.
8554   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8555 
8556   // Remove typedefs one by one until we reach a typedef
8557   // for a size dependent type.
8558   QualType DesugaredTy = Ty;
8559   do {
8560     ArrayRef<StringRef> Names(SizeTypeNames);
8561     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8562     if (Names.end() != Match)
8563       return true;
8564 
8565     Ty = DesugaredTy;
8566     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8567   } while (DesugaredTy != Ty);
8568 
8569   return false;
8570 }
8571 
8572 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8573   if (PT->isPointerType()) {
8574     QualType PointeeType = PT->getPointeeType();
8575     if (PointeeType->isPointerType())
8576       return PtrPtrKernelParam;
8577     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8578         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8579         PointeeType.getAddressSpace() == LangAS::Default)
8580       return InvalidAddrSpacePtrKernelParam;
8581     return PtrKernelParam;
8582   }
8583 
8584   // OpenCL v1.2 s6.9.k:
8585   // Arguments to kernel functions in a program cannot be declared with the
8586   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8587   // uintptr_t or a struct and/or union that contain fields declared to be one
8588   // of these built-in scalar types.
8589   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8590     return InvalidKernelParam;
8591 
8592   if (PT->isImageType())
8593     return PtrKernelParam;
8594 
8595   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8596     return InvalidKernelParam;
8597 
8598   // OpenCL extension spec v1.2 s9.5:
8599   // This extension adds support for half scalar and vector types as built-in
8600   // types that can be used for arithmetic operations, conversions etc.
8601   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8602     return InvalidKernelParam;
8603 
8604   if (PT->isRecordType())
8605     return RecordKernelParam;
8606 
8607   // Look into an array argument to check if it has a forbidden type.
8608   if (PT->isArrayType()) {
8609     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8610     // Call ourself to check an underlying type of an array. Since the
8611     // getPointeeOrArrayElementType returns an innermost type which is not an
8612     // array, this recursive call only happens once.
8613     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8614   }
8615 
8616   return ValidKernelParam;
8617 }
8618 
8619 static void checkIsValidOpenCLKernelParameter(
8620   Sema &S,
8621   Declarator &D,
8622   ParmVarDecl *Param,
8623   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8624   QualType PT = Param->getType();
8625 
8626   // Cache the valid types we encounter to avoid rechecking structs that are
8627   // used again
8628   if (ValidTypes.count(PT.getTypePtr()))
8629     return;
8630 
8631   switch (getOpenCLKernelParameterType(S, PT)) {
8632   case PtrPtrKernelParam:
8633     // OpenCL v1.2 s6.9.a:
8634     // A kernel function argument cannot be declared as a
8635     // pointer to a pointer type.
8636     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8637     D.setInvalidType();
8638     return;
8639 
8640   case InvalidAddrSpacePtrKernelParam:
8641     // OpenCL v1.0 s6.5:
8642     // __kernel function arguments declared to be a pointer of a type can point
8643     // to one of the following address spaces only : __global, __local or
8644     // __constant.
8645     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8646     D.setInvalidType();
8647     return;
8648 
8649     // OpenCL v1.2 s6.9.k:
8650     // Arguments to kernel functions in a program cannot be declared with the
8651     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8652     // uintptr_t or a struct and/or union that contain fields declared to be
8653     // one of these built-in scalar types.
8654 
8655   case InvalidKernelParam:
8656     // OpenCL v1.2 s6.8 n:
8657     // A kernel function argument cannot be declared
8658     // of event_t type.
8659     // Do not diagnose half type since it is diagnosed as invalid argument
8660     // type for any function elsewhere.
8661     if (!PT->isHalfType()) {
8662       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8663 
8664       // Explain what typedefs are involved.
8665       const TypedefType *Typedef = nullptr;
8666       while ((Typedef = PT->getAs<TypedefType>())) {
8667         SourceLocation Loc = Typedef->getDecl()->getLocation();
8668         // SourceLocation may be invalid for a built-in type.
8669         if (Loc.isValid())
8670           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8671         PT = Typedef->desugar();
8672       }
8673     }
8674 
8675     D.setInvalidType();
8676     return;
8677 
8678   case PtrKernelParam:
8679   case ValidKernelParam:
8680     ValidTypes.insert(PT.getTypePtr());
8681     return;
8682 
8683   case RecordKernelParam:
8684     break;
8685   }
8686 
8687   // Track nested structs we will inspect
8688   SmallVector<const Decl *, 4> VisitStack;
8689 
8690   // Track where we are in the nested structs. Items will migrate from
8691   // VisitStack to HistoryStack as we do the DFS for bad field.
8692   SmallVector<const FieldDecl *, 4> HistoryStack;
8693   HistoryStack.push_back(nullptr);
8694 
8695   // At this point we already handled everything except of a RecordType or
8696   // an ArrayType of a RecordType.
8697   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8698   const RecordType *RecTy =
8699       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8700   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8701 
8702   VisitStack.push_back(RecTy->getDecl());
8703   assert(VisitStack.back() && "First decl null?");
8704 
8705   do {
8706     const Decl *Next = VisitStack.pop_back_val();
8707     if (!Next) {
8708       assert(!HistoryStack.empty());
8709       // Found a marker, we have gone up a level
8710       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8711         ValidTypes.insert(Hist->getType().getTypePtr());
8712 
8713       continue;
8714     }
8715 
8716     // Adds everything except the original parameter declaration (which is not a
8717     // field itself) to the history stack.
8718     const RecordDecl *RD;
8719     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8720       HistoryStack.push_back(Field);
8721 
8722       QualType FieldTy = Field->getType();
8723       // Other field types (known to be valid or invalid) are handled while we
8724       // walk around RecordDecl::fields().
8725       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8726              "Unexpected type.");
8727       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8728 
8729       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8730     } else {
8731       RD = cast<RecordDecl>(Next);
8732     }
8733 
8734     // Add a null marker so we know when we've gone back up a level
8735     VisitStack.push_back(nullptr);
8736 
8737     for (const auto *FD : RD->fields()) {
8738       QualType QT = FD->getType();
8739 
8740       if (ValidTypes.count(QT.getTypePtr()))
8741         continue;
8742 
8743       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8744       if (ParamType == ValidKernelParam)
8745         continue;
8746 
8747       if (ParamType == RecordKernelParam) {
8748         VisitStack.push_back(FD);
8749         continue;
8750       }
8751 
8752       // OpenCL v1.2 s6.9.p:
8753       // Arguments to kernel functions that are declared to be a struct or union
8754       // do not allow OpenCL objects to be passed as elements of the struct or
8755       // union.
8756       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8757           ParamType == InvalidAddrSpacePtrKernelParam) {
8758         S.Diag(Param->getLocation(),
8759                diag::err_record_with_pointers_kernel_param)
8760           << PT->isUnionType()
8761           << PT;
8762       } else {
8763         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8764       }
8765 
8766       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8767           << OrigRecDecl->getDeclName();
8768 
8769       // We have an error, now let's go back up through history and show where
8770       // the offending field came from
8771       for (ArrayRef<const FieldDecl *>::const_iterator
8772                I = HistoryStack.begin() + 1,
8773                E = HistoryStack.end();
8774            I != E; ++I) {
8775         const FieldDecl *OuterField = *I;
8776         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8777           << OuterField->getType();
8778       }
8779 
8780       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8781         << QT->isPointerType()
8782         << QT;
8783       D.setInvalidType();
8784       return;
8785     }
8786   } while (!VisitStack.empty());
8787 }
8788 
8789 /// Find the DeclContext in which a tag is implicitly declared if we see an
8790 /// elaborated type specifier in the specified context, and lookup finds
8791 /// nothing.
8792 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8793   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8794     DC = DC->getParent();
8795   return DC;
8796 }
8797 
8798 /// Find the Scope in which a tag is implicitly declared if we see an
8799 /// elaborated type specifier in the specified context, and lookup finds
8800 /// nothing.
8801 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8802   while (S->isClassScope() ||
8803          (LangOpts.CPlusPlus &&
8804           S->isFunctionPrototypeScope()) ||
8805          ((S->getFlags() & Scope::DeclScope) == 0) ||
8806          (S->getEntity() && S->getEntity()->isTransparentContext()))
8807     S = S->getParent();
8808   return S;
8809 }
8810 
8811 NamedDecl*
8812 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8813                               TypeSourceInfo *TInfo, LookupResult &Previous,
8814                               MultiTemplateParamsArg TemplateParamListsRef,
8815                               bool &AddToScope) {
8816   QualType R = TInfo->getType();
8817 
8818   assert(R->isFunctionType());
8819   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8820     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8821 
8822   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8823   for (TemplateParameterList *TPL : TemplateParamListsRef)
8824     TemplateParamLists.push_back(TPL);
8825   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8826     if (!TemplateParamLists.empty() &&
8827         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8828       TemplateParamLists.back() = Invented;
8829     else
8830       TemplateParamLists.push_back(Invented);
8831   }
8832 
8833   // TODO: consider using NameInfo for diagnostic.
8834   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8835   DeclarationName Name = NameInfo.getName();
8836   StorageClass SC = getFunctionStorageClass(*this, D);
8837 
8838   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8839     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8840          diag::err_invalid_thread)
8841       << DeclSpec::getSpecifierName(TSCS);
8842 
8843   if (D.isFirstDeclarationOfMember())
8844     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8845                            D.getIdentifierLoc());
8846 
8847   bool isFriend = false;
8848   FunctionTemplateDecl *FunctionTemplate = nullptr;
8849   bool isMemberSpecialization = false;
8850   bool isFunctionTemplateSpecialization = false;
8851 
8852   bool isDependentClassScopeExplicitSpecialization = false;
8853   bool HasExplicitTemplateArgs = false;
8854   TemplateArgumentListInfo TemplateArgs;
8855 
8856   bool isVirtualOkay = false;
8857 
8858   DeclContext *OriginalDC = DC;
8859   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8860 
8861   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8862                                               isVirtualOkay);
8863   if (!NewFD) return nullptr;
8864 
8865   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8866     NewFD->setTopLevelDeclInObjCContainer();
8867 
8868   // Set the lexical context. If this is a function-scope declaration, or has a
8869   // C++ scope specifier, or is the object of a friend declaration, the lexical
8870   // context will be different from the semantic context.
8871   NewFD->setLexicalDeclContext(CurContext);
8872 
8873   if (IsLocalExternDecl)
8874     NewFD->setLocalExternDecl();
8875 
8876   if (getLangOpts().CPlusPlus) {
8877     bool isInline = D.getDeclSpec().isInlineSpecified();
8878     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8879     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8880     isFriend = D.getDeclSpec().isFriendSpecified();
8881     if (isFriend && !isInline && D.isFunctionDefinition()) {
8882       // C++ [class.friend]p5
8883       //   A function can be defined in a friend declaration of a
8884       //   class . . . . Such a function is implicitly inline.
8885       NewFD->setImplicitlyInline();
8886     }
8887 
8888     // If this is a method defined in an __interface, and is not a constructor
8889     // or an overloaded operator, then set the pure flag (isVirtual will already
8890     // return true).
8891     if (const CXXRecordDecl *Parent =
8892           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8893       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8894         NewFD->setPure(true);
8895 
8896       // C++ [class.union]p2
8897       //   A union can have member functions, but not virtual functions.
8898       if (isVirtual && Parent->isUnion())
8899         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8900     }
8901 
8902     SetNestedNameSpecifier(*this, NewFD, D);
8903     isMemberSpecialization = false;
8904     isFunctionTemplateSpecialization = false;
8905     if (D.isInvalidType())
8906       NewFD->setInvalidDecl();
8907 
8908     // Match up the template parameter lists with the scope specifier, then
8909     // determine whether we have a template or a template specialization.
8910     bool Invalid = false;
8911     TemplateParameterList *TemplateParams =
8912         MatchTemplateParametersToScopeSpecifier(
8913             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8914             D.getCXXScopeSpec(),
8915             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8916                 ? D.getName().TemplateId
8917                 : nullptr,
8918             TemplateParamLists, isFriend, isMemberSpecialization,
8919             Invalid);
8920     if (TemplateParams) {
8921       // Check that we can declare a template here.
8922       if (CheckTemplateDeclScope(S, TemplateParams))
8923         NewFD->setInvalidDecl();
8924 
8925       if (TemplateParams->size() > 0) {
8926         // This is a function template
8927 
8928         // A destructor cannot be a template.
8929         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8930           Diag(NewFD->getLocation(), diag::err_destructor_template);
8931           NewFD->setInvalidDecl();
8932         }
8933 
8934         // If we're adding a template to a dependent context, we may need to
8935         // rebuilding some of the types used within the template parameter list,
8936         // now that we know what the current instantiation is.
8937         if (DC->isDependentContext()) {
8938           ContextRAII SavedContext(*this, DC);
8939           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8940             Invalid = true;
8941         }
8942 
8943         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8944                                                         NewFD->getLocation(),
8945                                                         Name, TemplateParams,
8946                                                         NewFD);
8947         FunctionTemplate->setLexicalDeclContext(CurContext);
8948         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8949 
8950         // For source fidelity, store the other template param lists.
8951         if (TemplateParamLists.size() > 1) {
8952           NewFD->setTemplateParameterListsInfo(Context,
8953               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8954                   .drop_back(1));
8955         }
8956       } else {
8957         // This is a function template specialization.
8958         isFunctionTemplateSpecialization = true;
8959         // For source fidelity, store all the template param lists.
8960         if (TemplateParamLists.size() > 0)
8961           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8962 
8963         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8964         if (isFriend) {
8965           // We want to remove the "template<>", found here.
8966           SourceRange RemoveRange = TemplateParams->getSourceRange();
8967 
8968           // If we remove the template<> and the name is not a
8969           // template-id, we're actually silently creating a problem:
8970           // the friend declaration will refer to an untemplated decl,
8971           // and clearly the user wants a template specialization.  So
8972           // we need to insert '<>' after the name.
8973           SourceLocation InsertLoc;
8974           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8975             InsertLoc = D.getName().getSourceRange().getEnd();
8976             InsertLoc = getLocForEndOfToken(InsertLoc);
8977           }
8978 
8979           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8980             << Name << RemoveRange
8981             << FixItHint::CreateRemoval(RemoveRange)
8982             << FixItHint::CreateInsertion(InsertLoc, "<>");
8983         }
8984       }
8985     } else {
8986       // Check that we can declare a template here.
8987       if (!TemplateParamLists.empty() && isMemberSpecialization &&
8988           CheckTemplateDeclScope(S, TemplateParamLists.back()))
8989         NewFD->setInvalidDecl();
8990 
8991       // All template param lists were matched against the scope specifier:
8992       // this is NOT (an explicit specialization of) a template.
8993       if (TemplateParamLists.size() > 0)
8994         // For source fidelity, store all the template param lists.
8995         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8996     }
8997 
8998     if (Invalid) {
8999       NewFD->setInvalidDecl();
9000       if (FunctionTemplate)
9001         FunctionTemplate->setInvalidDecl();
9002     }
9003 
9004     // C++ [dcl.fct.spec]p5:
9005     //   The virtual specifier shall only be used in declarations of
9006     //   nonstatic class member functions that appear within a
9007     //   member-specification of a class declaration; see 10.3.
9008     //
9009     if (isVirtual && !NewFD->isInvalidDecl()) {
9010       if (!isVirtualOkay) {
9011         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9012              diag::err_virtual_non_function);
9013       } else if (!CurContext->isRecord()) {
9014         // 'virtual' was specified outside of the class.
9015         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9016              diag::err_virtual_out_of_class)
9017           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9018       } else if (NewFD->getDescribedFunctionTemplate()) {
9019         // C++ [temp.mem]p3:
9020         //  A member function template shall not be virtual.
9021         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9022              diag::err_virtual_member_function_template)
9023           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9024       } else {
9025         // Okay: Add virtual to the method.
9026         NewFD->setVirtualAsWritten(true);
9027       }
9028 
9029       if (getLangOpts().CPlusPlus14 &&
9030           NewFD->getReturnType()->isUndeducedType())
9031         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9032     }
9033 
9034     if (getLangOpts().CPlusPlus14 &&
9035         (NewFD->isDependentContext() ||
9036          (isFriend && CurContext->isDependentContext())) &&
9037         NewFD->getReturnType()->isUndeducedType()) {
9038       // If the function template is referenced directly (for instance, as a
9039       // member of the current instantiation), pretend it has a dependent type.
9040       // This is not really justified by the standard, but is the only sane
9041       // thing to do.
9042       // FIXME: For a friend function, we have not marked the function as being
9043       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9044       const FunctionProtoType *FPT =
9045           NewFD->getType()->castAs<FunctionProtoType>();
9046       QualType Result =
9047           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9048       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9049                                              FPT->getExtProtoInfo()));
9050     }
9051 
9052     // C++ [dcl.fct.spec]p3:
9053     //  The inline specifier shall not appear on a block scope function
9054     //  declaration.
9055     if (isInline && !NewFD->isInvalidDecl()) {
9056       if (CurContext->isFunctionOrMethod()) {
9057         // 'inline' is not allowed on block scope function declaration.
9058         Diag(D.getDeclSpec().getInlineSpecLoc(),
9059              diag::err_inline_declaration_block_scope) << Name
9060           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9061       }
9062     }
9063 
9064     // C++ [dcl.fct.spec]p6:
9065     //  The explicit specifier shall be used only in the declaration of a
9066     //  constructor or conversion function within its class definition;
9067     //  see 12.3.1 and 12.3.2.
9068     if (hasExplicit && !NewFD->isInvalidDecl() &&
9069         !isa<CXXDeductionGuideDecl>(NewFD)) {
9070       if (!CurContext->isRecord()) {
9071         // 'explicit' was specified outside of the class.
9072         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9073              diag::err_explicit_out_of_class)
9074             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9075       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9076                  !isa<CXXConversionDecl>(NewFD)) {
9077         // 'explicit' was specified on a function that wasn't a constructor
9078         // or conversion function.
9079         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9080              diag::err_explicit_non_ctor_or_conv_function)
9081             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9082       }
9083     }
9084 
9085     if (ConstexprSpecKind ConstexprKind =
9086             D.getDeclSpec().getConstexprSpecifier()) {
9087       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9088       // are implicitly inline.
9089       NewFD->setImplicitlyInline();
9090 
9091       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9092       // be either constructors or to return a literal type. Therefore,
9093       // destructors cannot be declared constexpr.
9094       if (isa<CXXDestructorDecl>(NewFD) &&
9095           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9096         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9097             << ConstexprKind;
9098         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9099       }
9100       // C++20 [dcl.constexpr]p2: An allocation function, or a
9101       // deallocation function shall not be declared with the consteval
9102       // specifier.
9103       if (ConstexprKind == CSK_consteval &&
9104           (NewFD->getOverloadedOperator() == OO_New ||
9105            NewFD->getOverloadedOperator() == OO_Array_New ||
9106            NewFD->getOverloadedOperator() == OO_Delete ||
9107            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9108         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9109              diag::err_invalid_consteval_decl_kind)
9110             << NewFD;
9111         NewFD->setConstexprKind(CSK_constexpr);
9112       }
9113     }
9114 
9115     // If __module_private__ was specified, mark the function accordingly.
9116     if (D.getDeclSpec().isModulePrivateSpecified()) {
9117       if (isFunctionTemplateSpecialization) {
9118         SourceLocation ModulePrivateLoc
9119           = D.getDeclSpec().getModulePrivateSpecLoc();
9120         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9121           << 0
9122           << FixItHint::CreateRemoval(ModulePrivateLoc);
9123       } else {
9124         NewFD->setModulePrivate();
9125         if (FunctionTemplate)
9126           FunctionTemplate->setModulePrivate();
9127       }
9128     }
9129 
9130     if (isFriend) {
9131       if (FunctionTemplate) {
9132         FunctionTemplate->setObjectOfFriendDecl();
9133         FunctionTemplate->setAccess(AS_public);
9134       }
9135       NewFD->setObjectOfFriendDecl();
9136       NewFD->setAccess(AS_public);
9137     }
9138 
9139     // If a function is defined as defaulted or deleted, mark it as such now.
9140     // We'll do the relevant checks on defaulted / deleted functions later.
9141     switch (D.getFunctionDefinitionKind()) {
9142       case FDK_Declaration:
9143       case FDK_Definition:
9144         break;
9145 
9146       case FDK_Defaulted:
9147         NewFD->setDefaulted();
9148         break;
9149 
9150       case FDK_Deleted:
9151         NewFD->setDeletedAsWritten();
9152         break;
9153     }
9154 
9155     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9156         D.isFunctionDefinition()) {
9157       // C++ [class.mfct]p2:
9158       //   A member function may be defined (8.4) in its class definition, in
9159       //   which case it is an inline member function (7.1.2)
9160       NewFD->setImplicitlyInline();
9161     }
9162 
9163     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9164         !CurContext->isRecord()) {
9165       // C++ [class.static]p1:
9166       //   A data or function member of a class may be declared static
9167       //   in a class definition, in which case it is a static member of
9168       //   the class.
9169 
9170       // Complain about the 'static' specifier if it's on an out-of-line
9171       // member function definition.
9172 
9173       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9174       // member function template declaration and class member template
9175       // declaration (MSVC versions before 2015), warn about this.
9176       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9177            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9178              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9179            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9180            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9181         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9182     }
9183 
9184     // C++11 [except.spec]p15:
9185     //   A deallocation function with no exception-specification is treated
9186     //   as if it were specified with noexcept(true).
9187     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9188     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9189          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9190         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9191       NewFD->setType(Context.getFunctionType(
9192           FPT->getReturnType(), FPT->getParamTypes(),
9193           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9194   }
9195 
9196   // Filter out previous declarations that don't match the scope.
9197   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9198                        D.getCXXScopeSpec().isNotEmpty() ||
9199                        isMemberSpecialization ||
9200                        isFunctionTemplateSpecialization);
9201 
9202   // Handle GNU asm-label extension (encoded as an attribute).
9203   if (Expr *E = (Expr*) D.getAsmLabel()) {
9204     // The parser guarantees this is a string.
9205     StringLiteral *SE = cast<StringLiteral>(E);
9206     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9207                                         /*IsLiteralLabel=*/true,
9208                                         SE->getStrTokenLoc(0)));
9209   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9210     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9211       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9212     if (I != ExtnameUndeclaredIdentifiers.end()) {
9213       if (isDeclExternC(NewFD)) {
9214         NewFD->addAttr(I->second);
9215         ExtnameUndeclaredIdentifiers.erase(I);
9216       } else
9217         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9218             << /*Variable*/0 << NewFD;
9219     }
9220   }
9221 
9222   // Copy the parameter declarations from the declarator D to the function
9223   // declaration NewFD, if they are available.  First scavenge them into Params.
9224   SmallVector<ParmVarDecl*, 16> Params;
9225   unsigned FTIIdx;
9226   if (D.isFunctionDeclarator(FTIIdx)) {
9227     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9228 
9229     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9230     // function that takes no arguments, not a function that takes a
9231     // single void argument.
9232     // We let through "const void" here because Sema::GetTypeForDeclarator
9233     // already checks for that case.
9234     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9235       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9236         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9237         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9238         Param->setDeclContext(NewFD);
9239         Params.push_back(Param);
9240 
9241         if (Param->isInvalidDecl())
9242           NewFD->setInvalidDecl();
9243       }
9244     }
9245 
9246     if (!getLangOpts().CPlusPlus) {
9247       // In C, find all the tag declarations from the prototype and move them
9248       // into the function DeclContext. Remove them from the surrounding tag
9249       // injection context of the function, which is typically but not always
9250       // the TU.
9251       DeclContext *PrototypeTagContext =
9252           getTagInjectionContext(NewFD->getLexicalDeclContext());
9253       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9254         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9255 
9256         // We don't want to reparent enumerators. Look at their parent enum
9257         // instead.
9258         if (!TD) {
9259           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9260             TD = cast<EnumDecl>(ECD->getDeclContext());
9261         }
9262         if (!TD)
9263           continue;
9264         DeclContext *TagDC = TD->getLexicalDeclContext();
9265         if (!TagDC->containsDecl(TD))
9266           continue;
9267         TagDC->removeDecl(TD);
9268         TD->setDeclContext(NewFD);
9269         NewFD->addDecl(TD);
9270 
9271         // Preserve the lexical DeclContext if it is not the surrounding tag
9272         // injection context of the FD. In this example, the semantic context of
9273         // E will be f and the lexical context will be S, while both the
9274         // semantic and lexical contexts of S will be f:
9275         //   void f(struct S { enum E { a } f; } s);
9276         if (TagDC != PrototypeTagContext)
9277           TD->setLexicalDeclContext(TagDC);
9278       }
9279     }
9280   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9281     // When we're declaring a function with a typedef, typeof, etc as in the
9282     // following example, we'll need to synthesize (unnamed)
9283     // parameters for use in the declaration.
9284     //
9285     // @code
9286     // typedef void fn(int);
9287     // fn f;
9288     // @endcode
9289 
9290     // Synthesize a parameter for each argument type.
9291     for (const auto &AI : FT->param_types()) {
9292       ParmVarDecl *Param =
9293           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9294       Param->setScopeInfo(0, Params.size());
9295       Params.push_back(Param);
9296     }
9297   } else {
9298     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9299            "Should not need args for typedef of non-prototype fn");
9300   }
9301 
9302   // Finally, we know we have the right number of parameters, install them.
9303   NewFD->setParams(Params);
9304 
9305   if (D.getDeclSpec().isNoreturnSpecified())
9306     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9307                                            D.getDeclSpec().getNoreturnSpecLoc(),
9308                                            AttributeCommonInfo::AS_Keyword));
9309 
9310   // Functions returning a variably modified type violate C99 6.7.5.2p2
9311   // because all functions have linkage.
9312   if (!NewFD->isInvalidDecl() &&
9313       NewFD->getReturnType()->isVariablyModifiedType()) {
9314     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9315     NewFD->setInvalidDecl();
9316   }
9317 
9318   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9319   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9320       !NewFD->hasAttr<SectionAttr>())
9321     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9322         Context, PragmaClangTextSection.SectionName,
9323         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9324 
9325   // Apply an implicit SectionAttr if #pragma code_seg is active.
9326   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9327       !NewFD->hasAttr<SectionAttr>()) {
9328     NewFD->addAttr(SectionAttr::CreateImplicit(
9329         Context, CodeSegStack.CurrentValue->getString(),
9330         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9331         SectionAttr::Declspec_allocate));
9332     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9333                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9334                          ASTContext::PSF_Read,
9335                      NewFD))
9336       NewFD->dropAttr<SectionAttr>();
9337   }
9338 
9339   // Apply an implicit CodeSegAttr from class declspec or
9340   // apply an implicit SectionAttr from #pragma code_seg if active.
9341   if (!NewFD->hasAttr<CodeSegAttr>()) {
9342     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9343                                                                  D.isFunctionDefinition())) {
9344       NewFD->addAttr(SAttr);
9345     }
9346   }
9347 
9348   // Handle attributes.
9349   ProcessDeclAttributes(S, NewFD, D);
9350 
9351   if (getLangOpts().OpenCL) {
9352     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9353     // type declaration will generate a compilation error.
9354     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9355     if (AddressSpace != LangAS::Default) {
9356       Diag(NewFD->getLocation(),
9357            diag::err_opencl_return_value_with_address_space);
9358       NewFD->setInvalidDecl();
9359     }
9360   }
9361 
9362   if (!getLangOpts().CPlusPlus) {
9363     // Perform semantic checking on the function declaration.
9364     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9365       CheckMain(NewFD, D.getDeclSpec());
9366 
9367     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9368       CheckMSVCRTEntryPoint(NewFD);
9369 
9370     if (!NewFD->isInvalidDecl())
9371       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9372                                                   isMemberSpecialization));
9373     else if (!Previous.empty())
9374       // Recover gracefully from an invalid redeclaration.
9375       D.setRedeclaration(true);
9376     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9377             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9378            "previous declaration set still overloaded");
9379 
9380     // Diagnose no-prototype function declarations with calling conventions that
9381     // don't support variadic calls. Only do this in C and do it after merging
9382     // possibly prototyped redeclarations.
9383     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9384     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9385       CallingConv CC = FT->getExtInfo().getCC();
9386       if (!supportsVariadicCall(CC)) {
9387         // Windows system headers sometimes accidentally use stdcall without
9388         // (void) parameters, so we relax this to a warning.
9389         int DiagID =
9390             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9391         Diag(NewFD->getLocation(), DiagID)
9392             << FunctionType::getNameForCallConv(CC);
9393       }
9394     }
9395 
9396    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9397        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9398      checkNonTrivialCUnion(NewFD->getReturnType(),
9399                            NewFD->getReturnTypeSourceRange().getBegin(),
9400                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9401   } else {
9402     // C++11 [replacement.functions]p3:
9403     //  The program's definitions shall not be specified as inline.
9404     //
9405     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9406     //
9407     // Suppress the diagnostic if the function is __attribute__((used)), since
9408     // that forces an external definition to be emitted.
9409     if (D.getDeclSpec().isInlineSpecified() &&
9410         NewFD->isReplaceableGlobalAllocationFunction() &&
9411         !NewFD->hasAttr<UsedAttr>())
9412       Diag(D.getDeclSpec().getInlineSpecLoc(),
9413            diag::ext_operator_new_delete_declared_inline)
9414         << NewFD->getDeclName();
9415 
9416     // If the declarator is a template-id, translate the parser's template
9417     // argument list into our AST format.
9418     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9419       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9420       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9421       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9422       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9423                                          TemplateId->NumArgs);
9424       translateTemplateArguments(TemplateArgsPtr,
9425                                  TemplateArgs);
9426 
9427       HasExplicitTemplateArgs = true;
9428 
9429       if (NewFD->isInvalidDecl()) {
9430         HasExplicitTemplateArgs = false;
9431       } else if (FunctionTemplate) {
9432         // Function template with explicit template arguments.
9433         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9434           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9435 
9436         HasExplicitTemplateArgs = false;
9437       } else {
9438         assert((isFunctionTemplateSpecialization ||
9439                 D.getDeclSpec().isFriendSpecified()) &&
9440                "should have a 'template<>' for this decl");
9441         // "friend void foo<>(int);" is an implicit specialization decl.
9442         isFunctionTemplateSpecialization = true;
9443       }
9444     } else if (isFriend && isFunctionTemplateSpecialization) {
9445       // This combination is only possible in a recovery case;  the user
9446       // wrote something like:
9447       //   template <> friend void foo(int);
9448       // which we're recovering from as if the user had written:
9449       //   friend void foo<>(int);
9450       // Go ahead and fake up a template id.
9451       HasExplicitTemplateArgs = true;
9452       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9453       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9454     }
9455 
9456     // We do not add HD attributes to specializations here because
9457     // they may have different constexpr-ness compared to their
9458     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9459     // may end up with different effective targets. Instead, a
9460     // specialization inherits its target attributes from its template
9461     // in the CheckFunctionTemplateSpecialization() call below.
9462     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9463       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9464 
9465     // If it's a friend (and only if it's a friend), it's possible
9466     // that either the specialized function type or the specialized
9467     // template is dependent, and therefore matching will fail.  In
9468     // this case, don't check the specialization yet.
9469     bool InstantiationDependent = false;
9470     if (isFunctionTemplateSpecialization && isFriend &&
9471         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9472          TemplateSpecializationType::anyDependentTemplateArguments(
9473             TemplateArgs,
9474             InstantiationDependent))) {
9475       assert(HasExplicitTemplateArgs &&
9476              "friend function specialization without template args");
9477       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9478                                                        Previous))
9479         NewFD->setInvalidDecl();
9480     } else if (isFunctionTemplateSpecialization) {
9481       if (CurContext->isDependentContext() && CurContext->isRecord()
9482           && !isFriend) {
9483         isDependentClassScopeExplicitSpecialization = true;
9484       } else if (!NewFD->isInvalidDecl() &&
9485                  CheckFunctionTemplateSpecialization(
9486                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9487                      Previous))
9488         NewFD->setInvalidDecl();
9489 
9490       // C++ [dcl.stc]p1:
9491       //   A storage-class-specifier shall not be specified in an explicit
9492       //   specialization (14.7.3)
9493       FunctionTemplateSpecializationInfo *Info =
9494           NewFD->getTemplateSpecializationInfo();
9495       if (Info && SC != SC_None) {
9496         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9497           Diag(NewFD->getLocation(),
9498                diag::err_explicit_specialization_inconsistent_storage_class)
9499             << SC
9500             << FixItHint::CreateRemoval(
9501                                       D.getDeclSpec().getStorageClassSpecLoc());
9502 
9503         else
9504           Diag(NewFD->getLocation(),
9505                diag::ext_explicit_specialization_storage_class)
9506             << FixItHint::CreateRemoval(
9507                                       D.getDeclSpec().getStorageClassSpecLoc());
9508       }
9509     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9510       if (CheckMemberSpecialization(NewFD, Previous))
9511           NewFD->setInvalidDecl();
9512     }
9513 
9514     // Perform semantic checking on the function declaration.
9515     if (!isDependentClassScopeExplicitSpecialization) {
9516       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9517         CheckMain(NewFD, D.getDeclSpec());
9518 
9519       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9520         CheckMSVCRTEntryPoint(NewFD);
9521 
9522       if (!NewFD->isInvalidDecl())
9523         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9524                                                     isMemberSpecialization));
9525       else if (!Previous.empty())
9526         // Recover gracefully from an invalid redeclaration.
9527         D.setRedeclaration(true);
9528     }
9529 
9530     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9531             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9532            "previous declaration set still overloaded");
9533 
9534     NamedDecl *PrincipalDecl = (FunctionTemplate
9535                                 ? cast<NamedDecl>(FunctionTemplate)
9536                                 : NewFD);
9537 
9538     if (isFriend && NewFD->getPreviousDecl()) {
9539       AccessSpecifier Access = AS_public;
9540       if (!NewFD->isInvalidDecl())
9541         Access = NewFD->getPreviousDecl()->getAccess();
9542 
9543       NewFD->setAccess(Access);
9544       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9545     }
9546 
9547     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9548         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9549       PrincipalDecl->setNonMemberOperator();
9550 
9551     // If we have a function template, check the template parameter
9552     // list. This will check and merge default template arguments.
9553     if (FunctionTemplate) {
9554       FunctionTemplateDecl *PrevTemplate =
9555                                      FunctionTemplate->getPreviousDecl();
9556       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9557                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9558                                     : nullptr,
9559                             D.getDeclSpec().isFriendSpecified()
9560                               ? (D.isFunctionDefinition()
9561                                    ? TPC_FriendFunctionTemplateDefinition
9562                                    : TPC_FriendFunctionTemplate)
9563                               : (D.getCXXScopeSpec().isSet() &&
9564                                  DC && DC->isRecord() &&
9565                                  DC->isDependentContext())
9566                                   ? TPC_ClassTemplateMember
9567                                   : TPC_FunctionTemplate);
9568     }
9569 
9570     if (NewFD->isInvalidDecl()) {
9571       // Ignore all the rest of this.
9572     } else if (!D.isRedeclaration()) {
9573       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9574                                        AddToScope };
9575       // Fake up an access specifier if it's supposed to be a class member.
9576       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9577         NewFD->setAccess(AS_public);
9578 
9579       // Qualified decls generally require a previous declaration.
9580       if (D.getCXXScopeSpec().isSet()) {
9581         // ...with the major exception of templated-scope or
9582         // dependent-scope friend declarations.
9583 
9584         // TODO: we currently also suppress this check in dependent
9585         // contexts because (1) the parameter depth will be off when
9586         // matching friend templates and (2) we might actually be
9587         // selecting a friend based on a dependent factor.  But there
9588         // are situations where these conditions don't apply and we
9589         // can actually do this check immediately.
9590         //
9591         // Unless the scope is dependent, it's always an error if qualified
9592         // redeclaration lookup found nothing at all. Diagnose that now;
9593         // nothing will diagnose that error later.
9594         if (isFriend &&
9595             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9596              (!Previous.empty() && CurContext->isDependentContext()))) {
9597           // ignore these
9598         } else {
9599           // The user tried to provide an out-of-line definition for a
9600           // function that is a member of a class or namespace, but there
9601           // was no such member function declared (C++ [class.mfct]p2,
9602           // C++ [namespace.memdef]p2). For example:
9603           //
9604           // class X {
9605           //   void f() const;
9606           // };
9607           //
9608           // void X::f() { } // ill-formed
9609           //
9610           // Complain about this problem, and attempt to suggest close
9611           // matches (e.g., those that differ only in cv-qualifiers and
9612           // whether the parameter types are references).
9613 
9614           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9615                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9616             AddToScope = ExtraArgs.AddToScope;
9617             return Result;
9618           }
9619         }
9620 
9621         // Unqualified local friend declarations are required to resolve
9622         // to something.
9623       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9624         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9625                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9626           AddToScope = ExtraArgs.AddToScope;
9627           return Result;
9628         }
9629       }
9630     } else if (!D.isFunctionDefinition() &&
9631                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9632                !isFriend && !isFunctionTemplateSpecialization &&
9633                !isMemberSpecialization) {
9634       // An out-of-line member function declaration must also be a
9635       // definition (C++ [class.mfct]p2).
9636       // Note that this is not the case for explicit specializations of
9637       // function templates or member functions of class templates, per
9638       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9639       // extension for compatibility with old SWIG code which likes to
9640       // generate them.
9641       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9642         << D.getCXXScopeSpec().getRange();
9643     }
9644   }
9645 
9646   // In C builtins get merged with implicitly lazily created declarations.
9647   // In C++ we need to check if it's a builtin and add the BuiltinAttr here.
9648   if (getLangOpts().CPlusPlus) {
9649     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9650       if (unsigned BuiltinID = II->getBuiltinID()) {
9651         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9652           // Declarations for builtins with custom typechecking by definition
9653           // don't make sense. Don't attempt typechecking and simply add the
9654           // attribute.
9655           if (Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
9656             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9657           } else {
9658             ASTContext::GetBuiltinTypeError Error;
9659             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9660             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9661 
9662             if (!Error && !BuiltinType.isNull() &&
9663                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9664                     NewFD->getType(), BuiltinType))
9665               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9666           }
9667         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9668                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9669           // FIXME: We should consider this a builtin only in the std namespace.
9670           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9671         }
9672       }
9673     }
9674   }
9675 
9676   ProcessPragmaWeak(S, NewFD);
9677   checkAttributesAfterMerging(*this, *NewFD);
9678 
9679   AddKnownFunctionAttributes(NewFD);
9680 
9681   if (NewFD->hasAttr<OverloadableAttr>() &&
9682       !NewFD->getType()->getAs<FunctionProtoType>()) {
9683     Diag(NewFD->getLocation(),
9684          diag::err_attribute_overloadable_no_prototype)
9685       << NewFD;
9686 
9687     // Turn this into a variadic function with no parameters.
9688     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9689     FunctionProtoType::ExtProtoInfo EPI(
9690         Context.getDefaultCallingConvention(true, false));
9691     EPI.Variadic = true;
9692     EPI.ExtInfo = FT->getExtInfo();
9693 
9694     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9695     NewFD->setType(R);
9696   }
9697 
9698   // If there's a #pragma GCC visibility in scope, and this isn't a class
9699   // member, set the visibility of this function.
9700   if (!DC->isRecord() && NewFD->isExternallyVisible())
9701     AddPushedVisibilityAttribute(NewFD);
9702 
9703   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9704   // marking the function.
9705   AddCFAuditedAttribute(NewFD);
9706 
9707   // If this is a function definition, check if we have to apply optnone due to
9708   // a pragma.
9709   if(D.isFunctionDefinition())
9710     AddRangeBasedOptnone(NewFD);
9711 
9712   // If this is the first declaration of an extern C variable, update
9713   // the map of such variables.
9714   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9715       isIncompleteDeclExternC(*this, NewFD))
9716     RegisterLocallyScopedExternCDecl(NewFD, S);
9717 
9718   // Set this FunctionDecl's range up to the right paren.
9719   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9720 
9721   if (D.isRedeclaration() && !Previous.empty()) {
9722     NamedDecl *Prev = Previous.getRepresentativeDecl();
9723     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9724                                    isMemberSpecialization ||
9725                                        isFunctionTemplateSpecialization,
9726                                    D.isFunctionDefinition());
9727   }
9728 
9729   if (getLangOpts().CUDA) {
9730     IdentifierInfo *II = NewFD->getIdentifier();
9731     if (II && II->isStr(getCudaConfigureFuncName()) &&
9732         !NewFD->isInvalidDecl() &&
9733         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9734       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9735         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9736             << getCudaConfigureFuncName();
9737       Context.setcudaConfigureCallDecl(NewFD);
9738     }
9739 
9740     // Variadic functions, other than a *declaration* of printf, are not allowed
9741     // in device-side CUDA code, unless someone passed
9742     // -fcuda-allow-variadic-functions.
9743     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9744         (NewFD->hasAttr<CUDADeviceAttr>() ||
9745          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9746         !(II && II->isStr("printf") && NewFD->isExternC() &&
9747           !D.isFunctionDefinition())) {
9748       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9749     }
9750   }
9751 
9752   MarkUnusedFileScopedDecl(NewFD);
9753 
9754 
9755 
9756   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9757     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9758     if ((getLangOpts().OpenCLVersion >= 120)
9759         && (SC == SC_Static)) {
9760       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9761       D.setInvalidType();
9762     }
9763 
9764     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9765     if (!NewFD->getReturnType()->isVoidType()) {
9766       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9767       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9768           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9769                                 : FixItHint());
9770       D.setInvalidType();
9771     }
9772 
9773     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9774     for (auto Param : NewFD->parameters())
9775       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9776 
9777     if (getLangOpts().OpenCLCPlusPlus) {
9778       if (DC->isRecord()) {
9779         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9780         D.setInvalidType();
9781       }
9782       if (FunctionTemplate) {
9783         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9784         D.setInvalidType();
9785       }
9786     }
9787   }
9788 
9789   if (getLangOpts().CPlusPlus) {
9790     if (FunctionTemplate) {
9791       if (NewFD->isInvalidDecl())
9792         FunctionTemplate->setInvalidDecl();
9793       return FunctionTemplate;
9794     }
9795 
9796     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9797       CompleteMemberSpecialization(NewFD, Previous);
9798   }
9799 
9800   for (const ParmVarDecl *Param : NewFD->parameters()) {
9801     QualType PT = Param->getType();
9802 
9803     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9804     // types.
9805     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9806       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9807         QualType ElemTy = PipeTy->getElementType();
9808           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9809             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9810             D.setInvalidType();
9811           }
9812       }
9813     }
9814   }
9815 
9816   // Here we have an function template explicit specialization at class scope.
9817   // The actual specialization will be postponed to template instatiation
9818   // time via the ClassScopeFunctionSpecializationDecl node.
9819   if (isDependentClassScopeExplicitSpecialization) {
9820     ClassScopeFunctionSpecializationDecl *NewSpec =
9821                          ClassScopeFunctionSpecializationDecl::Create(
9822                                 Context, CurContext, NewFD->getLocation(),
9823                                 cast<CXXMethodDecl>(NewFD),
9824                                 HasExplicitTemplateArgs, TemplateArgs);
9825     CurContext->addDecl(NewSpec);
9826     AddToScope = false;
9827   }
9828 
9829   // Diagnose availability attributes. Availability cannot be used on functions
9830   // that are run during load/unload.
9831   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9832     if (NewFD->hasAttr<ConstructorAttr>()) {
9833       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9834           << 1;
9835       NewFD->dropAttr<AvailabilityAttr>();
9836     }
9837     if (NewFD->hasAttr<DestructorAttr>()) {
9838       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9839           << 2;
9840       NewFD->dropAttr<AvailabilityAttr>();
9841     }
9842   }
9843 
9844   // Diagnose no_builtin attribute on function declaration that are not a
9845   // definition.
9846   // FIXME: We should really be doing this in
9847   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9848   // the FunctionDecl and at this point of the code
9849   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9850   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9851   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9852     switch (D.getFunctionDefinitionKind()) {
9853     case FDK_Defaulted:
9854     case FDK_Deleted:
9855       Diag(NBA->getLocation(),
9856            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9857           << NBA->getSpelling();
9858       break;
9859     case FDK_Declaration:
9860       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9861           << NBA->getSpelling();
9862       break;
9863     case FDK_Definition:
9864       break;
9865     }
9866 
9867   return NewFD;
9868 }
9869 
9870 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9871 /// when __declspec(code_seg) "is applied to a class, all member functions of
9872 /// the class and nested classes -- this includes compiler-generated special
9873 /// member functions -- are put in the specified segment."
9874 /// The actual behavior is a little more complicated. The Microsoft compiler
9875 /// won't check outer classes if there is an active value from #pragma code_seg.
9876 /// The CodeSeg is always applied from the direct parent but only from outer
9877 /// classes when the #pragma code_seg stack is empty. See:
9878 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9879 /// available since MS has removed the page.
9880 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9881   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9882   if (!Method)
9883     return nullptr;
9884   const CXXRecordDecl *Parent = Method->getParent();
9885   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9886     Attr *NewAttr = SAttr->clone(S.getASTContext());
9887     NewAttr->setImplicit(true);
9888     return NewAttr;
9889   }
9890 
9891   // The Microsoft compiler won't check outer classes for the CodeSeg
9892   // when the #pragma code_seg stack is active.
9893   if (S.CodeSegStack.CurrentValue)
9894    return nullptr;
9895 
9896   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9897     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9898       Attr *NewAttr = SAttr->clone(S.getASTContext());
9899       NewAttr->setImplicit(true);
9900       return NewAttr;
9901     }
9902   }
9903   return nullptr;
9904 }
9905 
9906 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9907 /// containing class. Otherwise it will return implicit SectionAttr if the
9908 /// function is a definition and there is an active value on CodeSegStack
9909 /// (from the current #pragma code-seg value).
9910 ///
9911 /// \param FD Function being declared.
9912 /// \param IsDefinition Whether it is a definition or just a declarartion.
9913 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9914 ///          nullptr if no attribute should be added.
9915 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9916                                                        bool IsDefinition) {
9917   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9918     return A;
9919   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9920       CodeSegStack.CurrentValue)
9921     return SectionAttr::CreateImplicit(
9922         getASTContext(), CodeSegStack.CurrentValue->getString(),
9923         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9924         SectionAttr::Declspec_allocate);
9925   return nullptr;
9926 }
9927 
9928 /// Determines if we can perform a correct type check for \p D as a
9929 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9930 /// best-effort check.
9931 ///
9932 /// \param NewD The new declaration.
9933 /// \param OldD The old declaration.
9934 /// \param NewT The portion of the type of the new declaration to check.
9935 /// \param OldT The portion of the type of the old declaration to check.
9936 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9937                                           QualType NewT, QualType OldT) {
9938   if (!NewD->getLexicalDeclContext()->isDependentContext())
9939     return true;
9940 
9941   // For dependently-typed local extern declarations and friends, we can't
9942   // perform a correct type check in general until instantiation:
9943   //
9944   //   int f();
9945   //   template<typename T> void g() { T f(); }
9946   //
9947   // (valid if g() is only instantiated with T = int).
9948   if (NewT->isDependentType() &&
9949       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9950     return false;
9951 
9952   // Similarly, if the previous declaration was a dependent local extern
9953   // declaration, we don't really know its type yet.
9954   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9955     return false;
9956 
9957   return true;
9958 }
9959 
9960 /// Checks if the new declaration declared in dependent context must be
9961 /// put in the same redeclaration chain as the specified declaration.
9962 ///
9963 /// \param D Declaration that is checked.
9964 /// \param PrevDecl Previous declaration found with proper lookup method for the
9965 ///                 same declaration name.
9966 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9967 ///          belongs to.
9968 ///
9969 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9970   if (!D->getLexicalDeclContext()->isDependentContext())
9971     return true;
9972 
9973   // Don't chain dependent friend function definitions until instantiation, to
9974   // permit cases like
9975   //
9976   //   void func();
9977   //   template<typename T> class C1 { friend void func() {} };
9978   //   template<typename T> class C2 { friend void func() {} };
9979   //
9980   // ... which is valid if only one of C1 and C2 is ever instantiated.
9981   //
9982   // FIXME: This need only apply to function definitions. For now, we proxy
9983   // this by checking for a file-scope function. We do not want this to apply
9984   // to friend declarations nominating member functions, because that gets in
9985   // the way of access checks.
9986   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9987     return false;
9988 
9989   auto *VD = dyn_cast<ValueDecl>(D);
9990   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9991   return !VD || !PrevVD ||
9992          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9993                                         PrevVD->getType());
9994 }
9995 
9996 /// Check the target attribute of the function for MultiVersion
9997 /// validity.
9998 ///
9999 /// Returns true if there was an error, false otherwise.
10000 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10001   const auto *TA = FD->getAttr<TargetAttr>();
10002   assert(TA && "MultiVersion Candidate requires a target attribute");
10003   ParsedTargetAttr ParseInfo = TA->parse();
10004   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10005   enum ErrType { Feature = 0, Architecture = 1 };
10006 
10007   if (!ParseInfo.Architecture.empty() &&
10008       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10009     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10010         << Architecture << ParseInfo.Architecture;
10011     return true;
10012   }
10013 
10014   for (const auto &Feat : ParseInfo.Features) {
10015     auto BareFeat = StringRef{Feat}.substr(1);
10016     if (Feat[0] == '-') {
10017       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10018           << Feature << ("no-" + BareFeat).str();
10019       return true;
10020     }
10021 
10022     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10023         !TargetInfo.isValidFeatureName(BareFeat)) {
10024       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10025           << Feature << BareFeat;
10026       return true;
10027     }
10028   }
10029   return false;
10030 }
10031 
10032 // Provide a white-list of attributes that are allowed to be combined with
10033 // multiversion functions.
10034 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10035                                            MultiVersionKind MVType) {
10036   // Note: this list/diagnosis must match the list in
10037   // checkMultiversionAttributesAllSame.
10038   switch (Kind) {
10039   default:
10040     return false;
10041   case attr::Used:
10042     return MVType == MultiVersionKind::Target;
10043   case attr::NonNull:
10044   case attr::NoThrow:
10045     return true;
10046   }
10047 }
10048 
10049 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10050                                                  const FunctionDecl *FD,
10051                                                  const FunctionDecl *CausedFD,
10052                                                  MultiVersionKind MVType) {
10053   bool IsCPUSpecificCPUDispatchMVType =
10054       MVType == MultiVersionKind::CPUDispatch ||
10055       MVType == MultiVersionKind::CPUSpecific;
10056   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10057                             Sema &S, const Attr *A) {
10058     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10059         << IsCPUSpecificCPUDispatchMVType << A;
10060     if (CausedFD)
10061       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10062     return true;
10063   };
10064 
10065   for (const Attr *A : FD->attrs()) {
10066     switch (A->getKind()) {
10067     case attr::CPUDispatch:
10068     case attr::CPUSpecific:
10069       if (MVType != MultiVersionKind::CPUDispatch &&
10070           MVType != MultiVersionKind::CPUSpecific)
10071         return Diagnose(S, A);
10072       break;
10073     case attr::Target:
10074       if (MVType != MultiVersionKind::Target)
10075         return Diagnose(S, A);
10076       break;
10077     default:
10078       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10079         return Diagnose(S, A);
10080       break;
10081     }
10082   }
10083   return false;
10084 }
10085 
10086 bool Sema::areMultiversionVariantFunctionsCompatible(
10087     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10088     const PartialDiagnostic &NoProtoDiagID,
10089     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10090     const PartialDiagnosticAt &NoSupportDiagIDAt,
10091     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10092     bool ConstexprSupported, bool CLinkageMayDiffer) {
10093   enum DoesntSupport {
10094     FuncTemplates = 0,
10095     VirtFuncs = 1,
10096     DeducedReturn = 2,
10097     Constructors = 3,
10098     Destructors = 4,
10099     DeletedFuncs = 5,
10100     DefaultedFuncs = 6,
10101     ConstexprFuncs = 7,
10102     ConstevalFuncs = 8,
10103   };
10104   enum Different {
10105     CallingConv = 0,
10106     ReturnType = 1,
10107     ConstexprSpec = 2,
10108     InlineSpec = 3,
10109     StorageClass = 4,
10110     Linkage = 5,
10111   };
10112 
10113   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10114       !OldFD->getType()->getAs<FunctionProtoType>()) {
10115     Diag(OldFD->getLocation(), NoProtoDiagID);
10116     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10117     return true;
10118   }
10119 
10120   if (NoProtoDiagID.getDiagID() != 0 &&
10121       !NewFD->getType()->getAs<FunctionProtoType>())
10122     return Diag(NewFD->getLocation(), NoProtoDiagID);
10123 
10124   if (!TemplatesSupported &&
10125       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10126     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10127            << FuncTemplates;
10128 
10129   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10130     if (NewCXXFD->isVirtual())
10131       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10132              << VirtFuncs;
10133 
10134     if (isa<CXXConstructorDecl>(NewCXXFD))
10135       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10136              << Constructors;
10137 
10138     if (isa<CXXDestructorDecl>(NewCXXFD))
10139       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10140              << Destructors;
10141   }
10142 
10143   if (NewFD->isDeleted())
10144     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10145            << DeletedFuncs;
10146 
10147   if (NewFD->isDefaulted())
10148     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10149            << DefaultedFuncs;
10150 
10151   if (!ConstexprSupported && NewFD->isConstexpr())
10152     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10153            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10154 
10155   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10156   const auto *NewType = cast<FunctionType>(NewQType);
10157   QualType NewReturnType = NewType->getReturnType();
10158 
10159   if (NewReturnType->isUndeducedType())
10160     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10161            << DeducedReturn;
10162 
10163   // Ensure the return type is identical.
10164   if (OldFD) {
10165     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10166     const auto *OldType = cast<FunctionType>(OldQType);
10167     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10168     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10169 
10170     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10171       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10172 
10173     QualType OldReturnType = OldType->getReturnType();
10174 
10175     if (OldReturnType != NewReturnType)
10176       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10177 
10178     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10179       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10180 
10181     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10182       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10183 
10184     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10185       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10186 
10187     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10188       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10189 
10190     if (CheckEquivalentExceptionSpec(
10191             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10192             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10193       return true;
10194   }
10195   return false;
10196 }
10197 
10198 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10199                                              const FunctionDecl *NewFD,
10200                                              bool CausesMV,
10201                                              MultiVersionKind MVType) {
10202   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10203     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10204     if (OldFD)
10205       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10206     return true;
10207   }
10208 
10209   bool IsCPUSpecificCPUDispatchMVType =
10210       MVType == MultiVersionKind::CPUDispatch ||
10211       MVType == MultiVersionKind::CPUSpecific;
10212 
10213   if (CausesMV && OldFD &&
10214       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10215     return true;
10216 
10217   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10218     return true;
10219 
10220   // Only allow transition to MultiVersion if it hasn't been used.
10221   if (OldFD && CausesMV && OldFD->isUsed(false))
10222     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10223 
10224   return S.areMultiversionVariantFunctionsCompatible(
10225       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10226       PartialDiagnosticAt(NewFD->getLocation(),
10227                           S.PDiag(diag::note_multiversioning_caused_here)),
10228       PartialDiagnosticAt(NewFD->getLocation(),
10229                           S.PDiag(diag::err_multiversion_doesnt_support)
10230                               << IsCPUSpecificCPUDispatchMVType),
10231       PartialDiagnosticAt(NewFD->getLocation(),
10232                           S.PDiag(diag::err_multiversion_diff)),
10233       /*TemplatesSupported=*/false,
10234       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10235       /*CLinkageMayDiffer=*/false);
10236 }
10237 
10238 /// Check the validity of a multiversion function declaration that is the
10239 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10240 ///
10241 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10242 ///
10243 /// Returns true if there was an error, false otherwise.
10244 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10245                                            MultiVersionKind MVType,
10246                                            const TargetAttr *TA) {
10247   assert(MVType != MultiVersionKind::None &&
10248          "Function lacks multiversion attribute");
10249 
10250   // Target only causes MV if it is default, otherwise this is a normal
10251   // function.
10252   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10253     return false;
10254 
10255   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10256     FD->setInvalidDecl();
10257     return true;
10258   }
10259 
10260   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10261     FD->setInvalidDecl();
10262     return true;
10263   }
10264 
10265   FD->setIsMultiVersion();
10266   return false;
10267 }
10268 
10269 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10270   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10271     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10272       return true;
10273   }
10274 
10275   return false;
10276 }
10277 
10278 static bool CheckTargetCausesMultiVersioning(
10279     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10280     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10281     LookupResult &Previous) {
10282   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10283   ParsedTargetAttr NewParsed = NewTA->parse();
10284   // Sort order doesn't matter, it just needs to be consistent.
10285   llvm::sort(NewParsed.Features);
10286 
10287   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10288   // to change, this is a simple redeclaration.
10289   if (!NewTA->isDefaultVersion() &&
10290       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10291     return false;
10292 
10293   // Otherwise, this decl causes MultiVersioning.
10294   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10295     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10296     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10297     NewFD->setInvalidDecl();
10298     return true;
10299   }
10300 
10301   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10302                                        MultiVersionKind::Target)) {
10303     NewFD->setInvalidDecl();
10304     return true;
10305   }
10306 
10307   if (CheckMultiVersionValue(S, NewFD)) {
10308     NewFD->setInvalidDecl();
10309     return true;
10310   }
10311 
10312   // If this is 'default', permit the forward declaration.
10313   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10314     Redeclaration = true;
10315     OldDecl = OldFD;
10316     OldFD->setIsMultiVersion();
10317     NewFD->setIsMultiVersion();
10318     return false;
10319   }
10320 
10321   if (CheckMultiVersionValue(S, OldFD)) {
10322     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10323     NewFD->setInvalidDecl();
10324     return true;
10325   }
10326 
10327   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10328 
10329   if (OldParsed == NewParsed) {
10330     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10331     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10332     NewFD->setInvalidDecl();
10333     return true;
10334   }
10335 
10336   for (const auto *FD : OldFD->redecls()) {
10337     const auto *CurTA = FD->getAttr<TargetAttr>();
10338     // We allow forward declarations before ANY multiversioning attributes, but
10339     // nothing after the fact.
10340     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10341         (!CurTA || CurTA->isInherited())) {
10342       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10343           << 0;
10344       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10345       NewFD->setInvalidDecl();
10346       return true;
10347     }
10348   }
10349 
10350   OldFD->setIsMultiVersion();
10351   NewFD->setIsMultiVersion();
10352   Redeclaration = false;
10353   MergeTypeWithPrevious = false;
10354   OldDecl = nullptr;
10355   Previous.clear();
10356   return false;
10357 }
10358 
10359 /// Check the validity of a new function declaration being added to an existing
10360 /// multiversioned declaration collection.
10361 static bool CheckMultiVersionAdditionalDecl(
10362     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10363     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10364     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10365     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10366     LookupResult &Previous) {
10367 
10368   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10369   // Disallow mixing of multiversioning types.
10370   if ((OldMVType == MultiVersionKind::Target &&
10371        NewMVType != MultiVersionKind::Target) ||
10372       (NewMVType == MultiVersionKind::Target &&
10373        OldMVType != MultiVersionKind::Target)) {
10374     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10375     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10376     NewFD->setInvalidDecl();
10377     return true;
10378   }
10379 
10380   ParsedTargetAttr NewParsed;
10381   if (NewTA) {
10382     NewParsed = NewTA->parse();
10383     llvm::sort(NewParsed.Features);
10384   }
10385 
10386   bool UseMemberUsingDeclRules =
10387       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10388 
10389   // Next, check ALL non-overloads to see if this is a redeclaration of a
10390   // previous member of the MultiVersion set.
10391   for (NamedDecl *ND : Previous) {
10392     FunctionDecl *CurFD = ND->getAsFunction();
10393     if (!CurFD)
10394       continue;
10395     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10396       continue;
10397 
10398     if (NewMVType == MultiVersionKind::Target) {
10399       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10400       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10401         NewFD->setIsMultiVersion();
10402         Redeclaration = true;
10403         OldDecl = ND;
10404         return false;
10405       }
10406 
10407       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10408       if (CurParsed == NewParsed) {
10409         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10410         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10411         NewFD->setInvalidDecl();
10412         return true;
10413       }
10414     } else {
10415       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10416       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10417       // Handle CPUDispatch/CPUSpecific versions.
10418       // Only 1 CPUDispatch function is allowed, this will make it go through
10419       // the redeclaration errors.
10420       if (NewMVType == MultiVersionKind::CPUDispatch &&
10421           CurFD->hasAttr<CPUDispatchAttr>()) {
10422         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10423             std::equal(
10424                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10425                 NewCPUDisp->cpus_begin(),
10426                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10427                   return Cur->getName() == New->getName();
10428                 })) {
10429           NewFD->setIsMultiVersion();
10430           Redeclaration = true;
10431           OldDecl = ND;
10432           return false;
10433         }
10434 
10435         // If the declarations don't match, this is an error condition.
10436         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10437         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10438         NewFD->setInvalidDecl();
10439         return true;
10440       }
10441       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10442 
10443         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10444             std::equal(
10445                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10446                 NewCPUSpec->cpus_begin(),
10447                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10448                   return Cur->getName() == New->getName();
10449                 })) {
10450           NewFD->setIsMultiVersion();
10451           Redeclaration = true;
10452           OldDecl = ND;
10453           return false;
10454         }
10455 
10456         // Only 1 version of CPUSpecific is allowed for each CPU.
10457         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10458           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10459             if (CurII == NewII) {
10460               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10461                   << NewII;
10462               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10463               NewFD->setInvalidDecl();
10464               return true;
10465             }
10466           }
10467         }
10468       }
10469       // If the two decls aren't the same MVType, there is no possible error
10470       // condition.
10471     }
10472   }
10473 
10474   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10475   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10476   // handled in the attribute adding step.
10477   if (NewMVType == MultiVersionKind::Target &&
10478       CheckMultiVersionValue(S, NewFD)) {
10479     NewFD->setInvalidDecl();
10480     return true;
10481   }
10482 
10483   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10484                                        !OldFD->isMultiVersion(), NewMVType)) {
10485     NewFD->setInvalidDecl();
10486     return true;
10487   }
10488 
10489   // Permit forward declarations in the case where these two are compatible.
10490   if (!OldFD->isMultiVersion()) {
10491     OldFD->setIsMultiVersion();
10492     NewFD->setIsMultiVersion();
10493     Redeclaration = true;
10494     OldDecl = OldFD;
10495     return false;
10496   }
10497 
10498   NewFD->setIsMultiVersion();
10499   Redeclaration = false;
10500   MergeTypeWithPrevious = false;
10501   OldDecl = nullptr;
10502   Previous.clear();
10503   return false;
10504 }
10505 
10506 
10507 /// Check the validity of a mulitversion function declaration.
10508 /// Also sets the multiversion'ness' of the function itself.
10509 ///
10510 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10511 ///
10512 /// Returns true if there was an error, false otherwise.
10513 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10514                                       bool &Redeclaration, NamedDecl *&OldDecl,
10515                                       bool &MergeTypeWithPrevious,
10516                                       LookupResult &Previous) {
10517   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10518   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10519   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10520 
10521   // Mixing Multiversioning types is prohibited.
10522   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10523       (NewCPUDisp && NewCPUSpec)) {
10524     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10525     NewFD->setInvalidDecl();
10526     return true;
10527   }
10528 
10529   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10530 
10531   // Main isn't allowed to become a multiversion function, however it IS
10532   // permitted to have 'main' be marked with the 'target' optimization hint.
10533   if (NewFD->isMain()) {
10534     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10535         MVType == MultiVersionKind::CPUDispatch ||
10536         MVType == MultiVersionKind::CPUSpecific) {
10537       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10538       NewFD->setInvalidDecl();
10539       return true;
10540     }
10541     return false;
10542   }
10543 
10544   if (!OldDecl || !OldDecl->getAsFunction() ||
10545       OldDecl->getDeclContext()->getRedeclContext() !=
10546           NewFD->getDeclContext()->getRedeclContext()) {
10547     // If there's no previous declaration, AND this isn't attempting to cause
10548     // multiversioning, this isn't an error condition.
10549     if (MVType == MultiVersionKind::None)
10550       return false;
10551     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10552   }
10553 
10554   FunctionDecl *OldFD = OldDecl->getAsFunction();
10555 
10556   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10557     return false;
10558 
10559   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10560     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10561         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10562     NewFD->setInvalidDecl();
10563     return true;
10564   }
10565 
10566   // Handle the target potentially causes multiversioning case.
10567   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10568     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10569                                             Redeclaration, OldDecl,
10570                                             MergeTypeWithPrevious, Previous);
10571 
10572   // At this point, we have a multiversion function decl (in OldFD) AND an
10573   // appropriate attribute in the current function decl.  Resolve that these are
10574   // still compatible with previous declarations.
10575   return CheckMultiVersionAdditionalDecl(
10576       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10577       OldDecl, MergeTypeWithPrevious, Previous);
10578 }
10579 
10580 /// Perform semantic checking of a new function declaration.
10581 ///
10582 /// Performs semantic analysis of the new function declaration
10583 /// NewFD. This routine performs all semantic checking that does not
10584 /// require the actual declarator involved in the declaration, and is
10585 /// used both for the declaration of functions as they are parsed
10586 /// (called via ActOnDeclarator) and for the declaration of functions
10587 /// that have been instantiated via C++ template instantiation (called
10588 /// via InstantiateDecl).
10589 ///
10590 /// \param IsMemberSpecialization whether this new function declaration is
10591 /// a member specialization (that replaces any definition provided by the
10592 /// previous declaration).
10593 ///
10594 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10595 ///
10596 /// \returns true if the function declaration is a redeclaration.
10597 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10598                                     LookupResult &Previous,
10599                                     bool IsMemberSpecialization) {
10600   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10601          "Variably modified return types are not handled here");
10602 
10603   // Determine whether the type of this function should be merged with
10604   // a previous visible declaration. This never happens for functions in C++,
10605   // and always happens in C if the previous declaration was visible.
10606   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10607                                !Previous.isShadowed();
10608 
10609   bool Redeclaration = false;
10610   NamedDecl *OldDecl = nullptr;
10611   bool MayNeedOverloadableChecks = false;
10612 
10613   // Merge or overload the declaration with an existing declaration of
10614   // the same name, if appropriate.
10615   if (!Previous.empty()) {
10616     // Determine whether NewFD is an overload of PrevDecl or
10617     // a declaration that requires merging. If it's an overload,
10618     // there's no more work to do here; we'll just add the new
10619     // function to the scope.
10620     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10621       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10622       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10623         Redeclaration = true;
10624         OldDecl = Candidate;
10625       }
10626     } else {
10627       MayNeedOverloadableChecks = true;
10628       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10629                             /*NewIsUsingDecl*/ false)) {
10630       case Ovl_Match:
10631         Redeclaration = true;
10632         break;
10633 
10634       case Ovl_NonFunction:
10635         Redeclaration = true;
10636         break;
10637 
10638       case Ovl_Overload:
10639         Redeclaration = false;
10640         break;
10641       }
10642     }
10643   }
10644 
10645   // Check for a previous extern "C" declaration with this name.
10646   if (!Redeclaration &&
10647       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10648     if (!Previous.empty()) {
10649       // This is an extern "C" declaration with the same name as a previous
10650       // declaration, and thus redeclares that entity...
10651       Redeclaration = true;
10652       OldDecl = Previous.getFoundDecl();
10653       MergeTypeWithPrevious = false;
10654 
10655       // ... except in the presence of __attribute__((overloadable)).
10656       if (OldDecl->hasAttr<OverloadableAttr>() ||
10657           NewFD->hasAttr<OverloadableAttr>()) {
10658         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10659           MayNeedOverloadableChecks = true;
10660           Redeclaration = false;
10661           OldDecl = nullptr;
10662         }
10663       }
10664     }
10665   }
10666 
10667   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10668                                 MergeTypeWithPrevious, Previous))
10669     return Redeclaration;
10670 
10671   // C++11 [dcl.constexpr]p8:
10672   //   A constexpr specifier for a non-static member function that is not
10673   //   a constructor declares that member function to be const.
10674   //
10675   // This needs to be delayed until we know whether this is an out-of-line
10676   // definition of a static member function.
10677   //
10678   // This rule is not present in C++1y, so we produce a backwards
10679   // compatibility warning whenever it happens in C++11.
10680   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10681   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10682       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10683       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10684     CXXMethodDecl *OldMD = nullptr;
10685     if (OldDecl)
10686       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10687     if (!OldMD || !OldMD->isStatic()) {
10688       const FunctionProtoType *FPT =
10689         MD->getType()->castAs<FunctionProtoType>();
10690       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10691       EPI.TypeQuals.addConst();
10692       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10693                                           FPT->getParamTypes(), EPI));
10694 
10695       // Warn that we did this, if we're not performing template instantiation.
10696       // In that case, we'll have warned already when the template was defined.
10697       if (!inTemplateInstantiation()) {
10698         SourceLocation AddConstLoc;
10699         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10700                 .IgnoreParens().getAs<FunctionTypeLoc>())
10701           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10702 
10703         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10704           << FixItHint::CreateInsertion(AddConstLoc, " const");
10705       }
10706     }
10707   }
10708 
10709   if (Redeclaration) {
10710     // NewFD and OldDecl represent declarations that need to be
10711     // merged.
10712     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10713       NewFD->setInvalidDecl();
10714       return Redeclaration;
10715     }
10716 
10717     Previous.clear();
10718     Previous.addDecl(OldDecl);
10719 
10720     if (FunctionTemplateDecl *OldTemplateDecl =
10721             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10722       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10723       FunctionTemplateDecl *NewTemplateDecl
10724         = NewFD->getDescribedFunctionTemplate();
10725       assert(NewTemplateDecl && "Template/non-template mismatch");
10726 
10727       // The call to MergeFunctionDecl above may have created some state in
10728       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10729       // can add it as a redeclaration.
10730       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10731 
10732       NewFD->setPreviousDeclaration(OldFD);
10733       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10734       if (NewFD->isCXXClassMember()) {
10735         NewFD->setAccess(OldTemplateDecl->getAccess());
10736         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10737       }
10738 
10739       // If this is an explicit specialization of a member that is a function
10740       // template, mark it as a member specialization.
10741       if (IsMemberSpecialization &&
10742           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10743         NewTemplateDecl->setMemberSpecialization();
10744         assert(OldTemplateDecl->isMemberSpecialization());
10745         // Explicit specializations of a member template do not inherit deleted
10746         // status from the parent member template that they are specializing.
10747         if (OldFD->isDeleted()) {
10748           // FIXME: This assert will not hold in the presence of modules.
10749           assert(OldFD->getCanonicalDecl() == OldFD);
10750           // FIXME: We need an update record for this AST mutation.
10751           OldFD->setDeletedAsWritten(false);
10752         }
10753       }
10754 
10755     } else {
10756       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10757         auto *OldFD = cast<FunctionDecl>(OldDecl);
10758         // This needs to happen first so that 'inline' propagates.
10759         NewFD->setPreviousDeclaration(OldFD);
10760         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10761         if (NewFD->isCXXClassMember())
10762           NewFD->setAccess(OldFD->getAccess());
10763       }
10764     }
10765   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10766              !NewFD->getAttr<OverloadableAttr>()) {
10767     assert((Previous.empty() ||
10768             llvm::any_of(Previous,
10769                          [](const NamedDecl *ND) {
10770                            return ND->hasAttr<OverloadableAttr>();
10771                          })) &&
10772            "Non-redecls shouldn't happen without overloadable present");
10773 
10774     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10775       const auto *FD = dyn_cast<FunctionDecl>(ND);
10776       return FD && !FD->hasAttr<OverloadableAttr>();
10777     });
10778 
10779     if (OtherUnmarkedIter != Previous.end()) {
10780       Diag(NewFD->getLocation(),
10781            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10782       Diag((*OtherUnmarkedIter)->getLocation(),
10783            diag::note_attribute_overloadable_prev_overload)
10784           << false;
10785 
10786       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10787     }
10788   }
10789 
10790   // Semantic checking for this function declaration (in isolation).
10791 
10792   if (getLangOpts().CPlusPlus) {
10793     // C++-specific checks.
10794     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10795       CheckConstructor(Constructor);
10796     } else if (CXXDestructorDecl *Destructor =
10797                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10798       CXXRecordDecl *Record = Destructor->getParent();
10799       QualType ClassType = Context.getTypeDeclType(Record);
10800 
10801       // FIXME: Shouldn't we be able to perform this check even when the class
10802       // type is dependent? Both gcc and edg can handle that.
10803       if (!ClassType->isDependentType()) {
10804         DeclarationName Name
10805           = Context.DeclarationNames.getCXXDestructorName(
10806                                         Context.getCanonicalType(ClassType));
10807         if (NewFD->getDeclName() != Name) {
10808           Diag(NewFD->getLocation(), diag::err_destructor_name);
10809           NewFD->setInvalidDecl();
10810           return Redeclaration;
10811         }
10812       }
10813     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10814       if (auto *TD = Guide->getDescribedFunctionTemplate())
10815         CheckDeductionGuideTemplate(TD);
10816 
10817       // A deduction guide is not on the list of entities that can be
10818       // explicitly specialized.
10819       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10820         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10821             << /*explicit specialization*/ 1;
10822     }
10823 
10824     // Find any virtual functions that this function overrides.
10825     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10826       if (!Method->isFunctionTemplateSpecialization() &&
10827           !Method->getDescribedFunctionTemplate() &&
10828           Method->isCanonicalDecl()) {
10829         AddOverriddenMethods(Method->getParent(), Method);
10830       }
10831       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10832         // C++2a [class.virtual]p6
10833         // A virtual method shall not have a requires-clause.
10834         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10835              diag::err_constrained_virtual_method);
10836 
10837       if (Method->isStatic())
10838         checkThisInStaticMemberFunctionType(Method);
10839     }
10840 
10841     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10842       ActOnConversionDeclarator(Conversion);
10843 
10844     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10845     if (NewFD->isOverloadedOperator() &&
10846         CheckOverloadedOperatorDeclaration(NewFD)) {
10847       NewFD->setInvalidDecl();
10848       return Redeclaration;
10849     }
10850 
10851     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10852     if (NewFD->getLiteralIdentifier() &&
10853         CheckLiteralOperatorDeclaration(NewFD)) {
10854       NewFD->setInvalidDecl();
10855       return Redeclaration;
10856     }
10857 
10858     // In C++, check default arguments now that we have merged decls. Unless
10859     // the lexical context is the class, because in this case this is done
10860     // during delayed parsing anyway.
10861     if (!CurContext->isRecord())
10862       CheckCXXDefaultArguments(NewFD);
10863 
10864     // If this function declares a builtin function, check the type of this
10865     // declaration against the expected type for the builtin.
10866     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10867       ASTContext::GetBuiltinTypeError Error;
10868       LookupNecessaryTypesForBuiltin(S, BuiltinID);
10869       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10870       // If the type of the builtin differs only in its exception
10871       // specification, that's OK.
10872       // FIXME: If the types do differ in this way, it would be better to
10873       // retain the 'noexcept' form of the type.
10874       if (!T.isNull() &&
10875           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10876                                                             NewFD->getType()))
10877         // The type of this function differs from the type of the builtin,
10878         // so forget about the builtin entirely.
10879         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10880     }
10881 
10882     // If this function is declared as being extern "C", then check to see if
10883     // the function returns a UDT (class, struct, or union type) that is not C
10884     // compatible, and if it does, warn the user.
10885     // But, issue any diagnostic on the first declaration only.
10886     if (Previous.empty() && NewFD->isExternC()) {
10887       QualType R = NewFD->getReturnType();
10888       if (R->isIncompleteType() && !R->isVoidType())
10889         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10890             << NewFD << R;
10891       else if (!R.isPODType(Context) && !R->isVoidType() &&
10892                !R->isObjCObjectPointerType())
10893         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10894     }
10895 
10896     // C++1z [dcl.fct]p6:
10897     //   [...] whether the function has a non-throwing exception-specification
10898     //   [is] part of the function type
10899     //
10900     // This results in an ABI break between C++14 and C++17 for functions whose
10901     // declared type includes an exception-specification in a parameter or
10902     // return type. (Exception specifications on the function itself are OK in
10903     // most cases, and exception specifications are not permitted in most other
10904     // contexts where they could make it into a mangling.)
10905     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10906       auto HasNoexcept = [&](QualType T) -> bool {
10907         // Strip off declarator chunks that could be between us and a function
10908         // type. We don't need to look far, exception specifications are very
10909         // restricted prior to C++17.
10910         if (auto *RT = T->getAs<ReferenceType>())
10911           T = RT->getPointeeType();
10912         else if (T->isAnyPointerType())
10913           T = T->getPointeeType();
10914         else if (auto *MPT = T->getAs<MemberPointerType>())
10915           T = MPT->getPointeeType();
10916         if (auto *FPT = T->getAs<FunctionProtoType>())
10917           if (FPT->isNothrow())
10918             return true;
10919         return false;
10920       };
10921 
10922       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10923       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10924       for (QualType T : FPT->param_types())
10925         AnyNoexcept |= HasNoexcept(T);
10926       if (AnyNoexcept)
10927         Diag(NewFD->getLocation(),
10928              diag::warn_cxx17_compat_exception_spec_in_signature)
10929             << NewFD;
10930     }
10931 
10932     if (!Redeclaration && LangOpts.CUDA)
10933       checkCUDATargetOverload(NewFD, Previous);
10934   }
10935   return Redeclaration;
10936 }
10937 
10938 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10939   // C++11 [basic.start.main]p3:
10940   //   A program that [...] declares main to be inline, static or
10941   //   constexpr is ill-formed.
10942   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10943   //   appear in a declaration of main.
10944   // static main is not an error under C99, but we should warn about it.
10945   // We accept _Noreturn main as an extension.
10946   if (FD->getStorageClass() == SC_Static)
10947     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10948          ? diag::err_static_main : diag::warn_static_main)
10949       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10950   if (FD->isInlineSpecified())
10951     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10952       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10953   if (DS.isNoreturnSpecified()) {
10954     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10955     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10956     Diag(NoreturnLoc, diag::ext_noreturn_main);
10957     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10958       << FixItHint::CreateRemoval(NoreturnRange);
10959   }
10960   if (FD->isConstexpr()) {
10961     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10962         << FD->isConsteval()
10963         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10964     FD->setConstexprKind(CSK_unspecified);
10965   }
10966 
10967   if (getLangOpts().OpenCL) {
10968     Diag(FD->getLocation(), diag::err_opencl_no_main)
10969         << FD->hasAttr<OpenCLKernelAttr>();
10970     FD->setInvalidDecl();
10971     return;
10972   }
10973 
10974   QualType T = FD->getType();
10975   assert(T->isFunctionType() && "function decl is not of function type");
10976   const FunctionType* FT = T->castAs<FunctionType>();
10977 
10978   // Set default calling convention for main()
10979   if (FT->getCallConv() != CC_C) {
10980     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10981     FD->setType(QualType(FT, 0));
10982     T = Context.getCanonicalType(FD->getType());
10983   }
10984 
10985   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10986     // In C with GNU extensions we allow main() to have non-integer return
10987     // type, but we should warn about the extension, and we disable the
10988     // implicit-return-zero rule.
10989 
10990     // GCC in C mode accepts qualified 'int'.
10991     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10992       FD->setHasImplicitReturnZero(true);
10993     else {
10994       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10995       SourceRange RTRange = FD->getReturnTypeSourceRange();
10996       if (RTRange.isValid())
10997         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10998             << FixItHint::CreateReplacement(RTRange, "int");
10999     }
11000   } else {
11001     // In C and C++, main magically returns 0 if you fall off the end;
11002     // set the flag which tells us that.
11003     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11004 
11005     // All the standards say that main() should return 'int'.
11006     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11007       FD->setHasImplicitReturnZero(true);
11008     else {
11009       // Otherwise, this is just a flat-out error.
11010       SourceRange RTRange = FD->getReturnTypeSourceRange();
11011       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11012           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11013                                 : FixItHint());
11014       FD->setInvalidDecl(true);
11015     }
11016   }
11017 
11018   // Treat protoless main() as nullary.
11019   if (isa<FunctionNoProtoType>(FT)) return;
11020 
11021   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11022   unsigned nparams = FTP->getNumParams();
11023   assert(FD->getNumParams() == nparams);
11024 
11025   bool HasExtraParameters = (nparams > 3);
11026 
11027   if (FTP->isVariadic()) {
11028     Diag(FD->getLocation(), diag::ext_variadic_main);
11029     // FIXME: if we had information about the location of the ellipsis, we
11030     // could add a FixIt hint to remove it as a parameter.
11031   }
11032 
11033   // Darwin passes an undocumented fourth argument of type char**.  If
11034   // other platforms start sprouting these, the logic below will start
11035   // getting shifty.
11036   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11037     HasExtraParameters = false;
11038 
11039   if (HasExtraParameters) {
11040     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11041     FD->setInvalidDecl(true);
11042     nparams = 3;
11043   }
11044 
11045   // FIXME: a lot of the following diagnostics would be improved
11046   // if we had some location information about types.
11047 
11048   QualType CharPP =
11049     Context.getPointerType(Context.getPointerType(Context.CharTy));
11050   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11051 
11052   for (unsigned i = 0; i < nparams; ++i) {
11053     QualType AT = FTP->getParamType(i);
11054 
11055     bool mismatch = true;
11056 
11057     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11058       mismatch = false;
11059     else if (Expected[i] == CharPP) {
11060       // As an extension, the following forms are okay:
11061       //   char const **
11062       //   char const * const *
11063       //   char * const *
11064 
11065       QualifierCollector qs;
11066       const PointerType* PT;
11067       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11068           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11069           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11070                               Context.CharTy)) {
11071         qs.removeConst();
11072         mismatch = !qs.empty();
11073       }
11074     }
11075 
11076     if (mismatch) {
11077       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11078       // TODO: suggest replacing given type with expected type
11079       FD->setInvalidDecl(true);
11080     }
11081   }
11082 
11083   if (nparams == 1 && !FD->isInvalidDecl()) {
11084     Diag(FD->getLocation(), diag::warn_main_one_arg);
11085   }
11086 
11087   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11088     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11089     FD->setInvalidDecl();
11090   }
11091 }
11092 
11093 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11094   QualType T = FD->getType();
11095   assert(T->isFunctionType() && "function decl is not of function type");
11096   const FunctionType *FT = T->castAs<FunctionType>();
11097 
11098   // Set an implicit return of 'zero' if the function can return some integral,
11099   // enumeration, pointer or nullptr type.
11100   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11101       FT->getReturnType()->isAnyPointerType() ||
11102       FT->getReturnType()->isNullPtrType())
11103     // DllMain is exempt because a return value of zero means it failed.
11104     if (FD->getName() != "DllMain")
11105       FD->setHasImplicitReturnZero(true);
11106 
11107   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11108     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11109     FD->setInvalidDecl();
11110   }
11111 }
11112 
11113 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11114   // FIXME: Need strict checking.  In C89, we need to check for
11115   // any assignment, increment, decrement, function-calls, or
11116   // commas outside of a sizeof.  In C99, it's the same list,
11117   // except that the aforementioned are allowed in unevaluated
11118   // expressions.  Everything else falls under the
11119   // "may accept other forms of constant expressions" exception.
11120   //
11121   // Regular C++ code will not end up here (exceptions: language extensions,
11122   // OpenCL C++ etc), so the constant expression rules there don't matter.
11123   if (Init->isValueDependent()) {
11124     assert(Init->containsErrors() &&
11125            "Dependent code should only occur in error-recovery path.");
11126     return true;
11127   }
11128   const Expr *Culprit;
11129   if (Init->isConstantInitializer(Context, false, &Culprit))
11130     return false;
11131   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11132     << Culprit->getSourceRange();
11133   return true;
11134 }
11135 
11136 namespace {
11137   // Visits an initialization expression to see if OrigDecl is evaluated in
11138   // its own initialization and throws a warning if it does.
11139   class SelfReferenceChecker
11140       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11141     Sema &S;
11142     Decl *OrigDecl;
11143     bool isRecordType;
11144     bool isPODType;
11145     bool isReferenceType;
11146 
11147     bool isInitList;
11148     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11149 
11150   public:
11151     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11152 
11153     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11154                                                     S(S), OrigDecl(OrigDecl) {
11155       isPODType = false;
11156       isRecordType = false;
11157       isReferenceType = false;
11158       isInitList = false;
11159       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11160         isPODType = VD->getType().isPODType(S.Context);
11161         isRecordType = VD->getType()->isRecordType();
11162         isReferenceType = VD->getType()->isReferenceType();
11163       }
11164     }
11165 
11166     // For most expressions, just call the visitor.  For initializer lists,
11167     // track the index of the field being initialized since fields are
11168     // initialized in order allowing use of previously initialized fields.
11169     void CheckExpr(Expr *E) {
11170       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11171       if (!InitList) {
11172         Visit(E);
11173         return;
11174       }
11175 
11176       // Track and increment the index here.
11177       isInitList = true;
11178       InitFieldIndex.push_back(0);
11179       for (auto Child : InitList->children()) {
11180         CheckExpr(cast<Expr>(Child));
11181         ++InitFieldIndex.back();
11182       }
11183       InitFieldIndex.pop_back();
11184     }
11185 
11186     // Returns true if MemberExpr is checked and no further checking is needed.
11187     // Returns false if additional checking is required.
11188     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11189       llvm::SmallVector<FieldDecl*, 4> Fields;
11190       Expr *Base = E;
11191       bool ReferenceField = false;
11192 
11193       // Get the field members used.
11194       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11195         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11196         if (!FD)
11197           return false;
11198         Fields.push_back(FD);
11199         if (FD->getType()->isReferenceType())
11200           ReferenceField = true;
11201         Base = ME->getBase()->IgnoreParenImpCasts();
11202       }
11203 
11204       // Keep checking only if the base Decl is the same.
11205       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11206       if (!DRE || DRE->getDecl() != OrigDecl)
11207         return false;
11208 
11209       // A reference field can be bound to an unininitialized field.
11210       if (CheckReference && !ReferenceField)
11211         return true;
11212 
11213       // Convert FieldDecls to their index number.
11214       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11215       for (const FieldDecl *I : llvm::reverse(Fields))
11216         UsedFieldIndex.push_back(I->getFieldIndex());
11217 
11218       // See if a warning is needed by checking the first difference in index
11219       // numbers.  If field being used has index less than the field being
11220       // initialized, then the use is safe.
11221       for (auto UsedIter = UsedFieldIndex.begin(),
11222                 UsedEnd = UsedFieldIndex.end(),
11223                 OrigIter = InitFieldIndex.begin(),
11224                 OrigEnd = InitFieldIndex.end();
11225            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11226         if (*UsedIter < *OrigIter)
11227           return true;
11228         if (*UsedIter > *OrigIter)
11229           break;
11230       }
11231 
11232       // TODO: Add a different warning which will print the field names.
11233       HandleDeclRefExpr(DRE);
11234       return true;
11235     }
11236 
11237     // For most expressions, the cast is directly above the DeclRefExpr.
11238     // For conditional operators, the cast can be outside the conditional
11239     // operator if both expressions are DeclRefExpr's.
11240     void HandleValue(Expr *E) {
11241       E = E->IgnoreParens();
11242       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11243         HandleDeclRefExpr(DRE);
11244         return;
11245       }
11246 
11247       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11248         Visit(CO->getCond());
11249         HandleValue(CO->getTrueExpr());
11250         HandleValue(CO->getFalseExpr());
11251         return;
11252       }
11253 
11254       if (BinaryConditionalOperator *BCO =
11255               dyn_cast<BinaryConditionalOperator>(E)) {
11256         Visit(BCO->getCond());
11257         HandleValue(BCO->getFalseExpr());
11258         return;
11259       }
11260 
11261       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11262         HandleValue(OVE->getSourceExpr());
11263         return;
11264       }
11265 
11266       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11267         if (BO->getOpcode() == BO_Comma) {
11268           Visit(BO->getLHS());
11269           HandleValue(BO->getRHS());
11270           return;
11271         }
11272       }
11273 
11274       if (isa<MemberExpr>(E)) {
11275         if (isInitList) {
11276           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11277                                       false /*CheckReference*/))
11278             return;
11279         }
11280 
11281         Expr *Base = E->IgnoreParenImpCasts();
11282         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11283           // Check for static member variables and don't warn on them.
11284           if (!isa<FieldDecl>(ME->getMemberDecl()))
11285             return;
11286           Base = ME->getBase()->IgnoreParenImpCasts();
11287         }
11288         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11289           HandleDeclRefExpr(DRE);
11290         return;
11291       }
11292 
11293       Visit(E);
11294     }
11295 
11296     // Reference types not handled in HandleValue are handled here since all
11297     // uses of references are bad, not just r-value uses.
11298     void VisitDeclRefExpr(DeclRefExpr *E) {
11299       if (isReferenceType)
11300         HandleDeclRefExpr(E);
11301     }
11302 
11303     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11304       if (E->getCastKind() == CK_LValueToRValue) {
11305         HandleValue(E->getSubExpr());
11306         return;
11307       }
11308 
11309       Inherited::VisitImplicitCastExpr(E);
11310     }
11311 
11312     void VisitMemberExpr(MemberExpr *E) {
11313       if (isInitList) {
11314         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11315           return;
11316       }
11317 
11318       // Don't warn on arrays since they can be treated as pointers.
11319       if (E->getType()->canDecayToPointerType()) return;
11320 
11321       // Warn when a non-static method call is followed by non-static member
11322       // field accesses, which is followed by a DeclRefExpr.
11323       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11324       bool Warn = (MD && !MD->isStatic());
11325       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11326       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11327         if (!isa<FieldDecl>(ME->getMemberDecl()))
11328           Warn = false;
11329         Base = ME->getBase()->IgnoreParenImpCasts();
11330       }
11331 
11332       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11333         if (Warn)
11334           HandleDeclRefExpr(DRE);
11335         return;
11336       }
11337 
11338       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11339       // Visit that expression.
11340       Visit(Base);
11341     }
11342 
11343     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11344       Expr *Callee = E->getCallee();
11345 
11346       if (isa<UnresolvedLookupExpr>(Callee))
11347         return Inherited::VisitCXXOperatorCallExpr(E);
11348 
11349       Visit(Callee);
11350       for (auto Arg: E->arguments())
11351         HandleValue(Arg->IgnoreParenImpCasts());
11352     }
11353 
11354     void VisitUnaryOperator(UnaryOperator *E) {
11355       // For POD record types, addresses of its own members are well-defined.
11356       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11357           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11358         if (!isPODType)
11359           HandleValue(E->getSubExpr());
11360         return;
11361       }
11362 
11363       if (E->isIncrementDecrementOp()) {
11364         HandleValue(E->getSubExpr());
11365         return;
11366       }
11367 
11368       Inherited::VisitUnaryOperator(E);
11369     }
11370 
11371     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11372 
11373     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11374       if (E->getConstructor()->isCopyConstructor()) {
11375         Expr *ArgExpr = E->getArg(0);
11376         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11377           if (ILE->getNumInits() == 1)
11378             ArgExpr = ILE->getInit(0);
11379         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11380           if (ICE->getCastKind() == CK_NoOp)
11381             ArgExpr = ICE->getSubExpr();
11382         HandleValue(ArgExpr);
11383         return;
11384       }
11385       Inherited::VisitCXXConstructExpr(E);
11386     }
11387 
11388     void VisitCallExpr(CallExpr *E) {
11389       // Treat std::move as a use.
11390       if (E->isCallToStdMove()) {
11391         HandleValue(E->getArg(0));
11392         return;
11393       }
11394 
11395       Inherited::VisitCallExpr(E);
11396     }
11397 
11398     void VisitBinaryOperator(BinaryOperator *E) {
11399       if (E->isCompoundAssignmentOp()) {
11400         HandleValue(E->getLHS());
11401         Visit(E->getRHS());
11402         return;
11403       }
11404 
11405       Inherited::VisitBinaryOperator(E);
11406     }
11407 
11408     // A custom visitor for BinaryConditionalOperator is needed because the
11409     // regular visitor would check the condition and true expression separately
11410     // but both point to the same place giving duplicate diagnostics.
11411     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11412       Visit(E->getCond());
11413       Visit(E->getFalseExpr());
11414     }
11415 
11416     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11417       Decl* ReferenceDecl = DRE->getDecl();
11418       if (OrigDecl != ReferenceDecl) return;
11419       unsigned diag;
11420       if (isReferenceType) {
11421         diag = diag::warn_uninit_self_reference_in_reference_init;
11422       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11423         diag = diag::warn_static_self_reference_in_init;
11424       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11425                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11426                  DRE->getDecl()->getType()->isRecordType()) {
11427         diag = diag::warn_uninit_self_reference_in_init;
11428       } else {
11429         // Local variables will be handled by the CFG analysis.
11430         return;
11431       }
11432 
11433       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11434                             S.PDiag(diag)
11435                                 << DRE->getDecl() << OrigDecl->getLocation()
11436                                 << DRE->getSourceRange());
11437     }
11438   };
11439 
11440   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11441   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11442                                  bool DirectInit) {
11443     // Parameters arguments are occassionially constructed with itself,
11444     // for instance, in recursive functions.  Skip them.
11445     if (isa<ParmVarDecl>(OrigDecl))
11446       return;
11447 
11448     E = E->IgnoreParens();
11449 
11450     // Skip checking T a = a where T is not a record or reference type.
11451     // Doing so is a way to silence uninitialized warnings.
11452     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11453       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11454         if (ICE->getCastKind() == CK_LValueToRValue)
11455           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11456             if (DRE->getDecl() == OrigDecl)
11457               return;
11458 
11459     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11460   }
11461 } // end anonymous namespace
11462 
11463 namespace {
11464   // Simple wrapper to add the name of a variable or (if no variable is
11465   // available) a DeclarationName into a diagnostic.
11466   struct VarDeclOrName {
11467     VarDecl *VDecl;
11468     DeclarationName Name;
11469 
11470     friend const Sema::SemaDiagnosticBuilder &
11471     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11472       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11473     }
11474   };
11475 } // end anonymous namespace
11476 
11477 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11478                                             DeclarationName Name, QualType Type,
11479                                             TypeSourceInfo *TSI,
11480                                             SourceRange Range, bool DirectInit,
11481                                             Expr *Init) {
11482   bool IsInitCapture = !VDecl;
11483   assert((!VDecl || !VDecl->isInitCapture()) &&
11484          "init captures are expected to be deduced prior to initialization");
11485 
11486   VarDeclOrName VN{VDecl, Name};
11487 
11488   DeducedType *Deduced = Type->getContainedDeducedType();
11489   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11490 
11491   // C++11 [dcl.spec.auto]p3
11492   if (!Init) {
11493     assert(VDecl && "no init for init capture deduction?");
11494 
11495     // Except for class argument deduction, and then for an initializing
11496     // declaration only, i.e. no static at class scope or extern.
11497     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11498         VDecl->hasExternalStorage() ||
11499         VDecl->isStaticDataMember()) {
11500       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11501         << VDecl->getDeclName() << Type;
11502       return QualType();
11503     }
11504   }
11505 
11506   ArrayRef<Expr*> DeduceInits;
11507   if (Init)
11508     DeduceInits = Init;
11509 
11510   if (DirectInit) {
11511     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11512       DeduceInits = PL->exprs();
11513   }
11514 
11515   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11516     assert(VDecl && "non-auto type for init capture deduction?");
11517     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11518     InitializationKind Kind = InitializationKind::CreateForInit(
11519         VDecl->getLocation(), DirectInit, Init);
11520     // FIXME: Initialization should not be taking a mutable list of inits.
11521     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11522     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11523                                                        InitsCopy);
11524   }
11525 
11526   if (DirectInit) {
11527     if (auto *IL = dyn_cast<InitListExpr>(Init))
11528       DeduceInits = IL->inits();
11529   }
11530 
11531   // Deduction only works if we have exactly one source expression.
11532   if (DeduceInits.empty()) {
11533     // It isn't possible to write this directly, but it is possible to
11534     // end up in this situation with "auto x(some_pack...);"
11535     Diag(Init->getBeginLoc(), IsInitCapture
11536                                   ? diag::err_init_capture_no_expression
11537                                   : diag::err_auto_var_init_no_expression)
11538         << VN << Type << Range;
11539     return QualType();
11540   }
11541 
11542   if (DeduceInits.size() > 1) {
11543     Diag(DeduceInits[1]->getBeginLoc(),
11544          IsInitCapture ? diag::err_init_capture_multiple_expressions
11545                        : diag::err_auto_var_init_multiple_expressions)
11546         << VN << Type << Range;
11547     return QualType();
11548   }
11549 
11550   Expr *DeduceInit = DeduceInits[0];
11551   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11552     Diag(Init->getBeginLoc(), IsInitCapture
11553                                   ? diag::err_init_capture_paren_braces
11554                                   : diag::err_auto_var_init_paren_braces)
11555         << isa<InitListExpr>(Init) << VN << Type << Range;
11556     return QualType();
11557   }
11558 
11559   // Expressions default to 'id' when we're in a debugger.
11560   bool DefaultedAnyToId = false;
11561   if (getLangOpts().DebuggerCastResultToId &&
11562       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11563     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11564     if (Result.isInvalid()) {
11565       return QualType();
11566     }
11567     Init = Result.get();
11568     DefaultedAnyToId = true;
11569   }
11570 
11571   // C++ [dcl.decomp]p1:
11572   //   If the assignment-expression [...] has array type A and no ref-qualifier
11573   //   is present, e has type cv A
11574   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11575       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11576       DeduceInit->getType()->isConstantArrayType())
11577     return Context.getQualifiedType(DeduceInit->getType(),
11578                                     Type.getQualifiers());
11579 
11580   QualType DeducedType;
11581   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11582     if (!IsInitCapture)
11583       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11584     else if (isa<InitListExpr>(Init))
11585       Diag(Range.getBegin(),
11586            diag::err_init_capture_deduction_failure_from_init_list)
11587           << VN
11588           << (DeduceInit->getType().isNull() ? TSI->getType()
11589                                              : DeduceInit->getType())
11590           << DeduceInit->getSourceRange();
11591     else
11592       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11593           << VN << TSI->getType()
11594           << (DeduceInit->getType().isNull() ? TSI->getType()
11595                                              : DeduceInit->getType())
11596           << DeduceInit->getSourceRange();
11597   }
11598 
11599   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11600   // 'id' instead of a specific object type prevents most of our usual
11601   // checks.
11602   // We only want to warn outside of template instantiations, though:
11603   // inside a template, the 'id' could have come from a parameter.
11604   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11605       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11606     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11607     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11608   }
11609 
11610   return DeducedType;
11611 }
11612 
11613 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11614                                          Expr *Init) {
11615   assert(!Init || !Init->containsErrors());
11616   QualType DeducedType = deduceVarTypeFromInitializer(
11617       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11618       VDecl->getSourceRange(), DirectInit, Init);
11619   if (DeducedType.isNull()) {
11620     VDecl->setInvalidDecl();
11621     return true;
11622   }
11623 
11624   VDecl->setType(DeducedType);
11625   assert(VDecl->isLinkageValid());
11626 
11627   // In ARC, infer lifetime.
11628   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11629     VDecl->setInvalidDecl();
11630 
11631   if (getLangOpts().OpenCL)
11632     deduceOpenCLAddressSpace(VDecl);
11633 
11634   // If this is a redeclaration, check that the type we just deduced matches
11635   // the previously declared type.
11636   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11637     // We never need to merge the type, because we cannot form an incomplete
11638     // array of auto, nor deduce such a type.
11639     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11640   }
11641 
11642   // Check the deduced type is valid for a variable declaration.
11643   CheckVariableDeclarationType(VDecl);
11644   return VDecl->isInvalidDecl();
11645 }
11646 
11647 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11648                                               SourceLocation Loc) {
11649   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11650     Init = EWC->getSubExpr();
11651 
11652   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11653     Init = CE->getSubExpr();
11654 
11655   QualType InitType = Init->getType();
11656   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11657           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11658          "shouldn't be called if type doesn't have a non-trivial C struct");
11659   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11660     for (auto I : ILE->inits()) {
11661       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11662           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11663         continue;
11664       SourceLocation SL = I->getExprLoc();
11665       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11666     }
11667     return;
11668   }
11669 
11670   if (isa<ImplicitValueInitExpr>(Init)) {
11671     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11672       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11673                             NTCUK_Init);
11674   } else {
11675     // Assume all other explicit initializers involving copying some existing
11676     // object.
11677     // TODO: ignore any explicit initializers where we can guarantee
11678     // copy-elision.
11679     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11680       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11681   }
11682 }
11683 
11684 namespace {
11685 
11686 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11687   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11688   // in the source code or implicitly by the compiler if it is in a union
11689   // defined in a system header and has non-trivial ObjC ownership
11690   // qualifications. We don't want those fields to participate in determining
11691   // whether the containing union is non-trivial.
11692   return FD->hasAttr<UnavailableAttr>();
11693 }
11694 
11695 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11696     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11697                                     void> {
11698   using Super =
11699       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11700                                     void>;
11701 
11702   DiagNonTrivalCUnionDefaultInitializeVisitor(
11703       QualType OrigTy, SourceLocation OrigLoc,
11704       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11705       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11706 
11707   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11708                      const FieldDecl *FD, bool InNonTrivialUnion) {
11709     if (const auto *AT = S.Context.getAsArrayType(QT))
11710       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11711                                      InNonTrivialUnion);
11712     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11713   }
11714 
11715   void visitARCStrong(QualType QT, const FieldDecl *FD,
11716                       bool InNonTrivialUnion) {
11717     if (InNonTrivialUnion)
11718       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11719           << 1 << 0 << QT << FD->getName();
11720   }
11721 
11722   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11723     if (InNonTrivialUnion)
11724       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11725           << 1 << 0 << QT << FD->getName();
11726   }
11727 
11728   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11729     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11730     if (RD->isUnion()) {
11731       if (OrigLoc.isValid()) {
11732         bool IsUnion = false;
11733         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11734           IsUnion = OrigRD->isUnion();
11735         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11736             << 0 << OrigTy << IsUnion << UseContext;
11737         // Reset OrigLoc so that this diagnostic is emitted only once.
11738         OrigLoc = SourceLocation();
11739       }
11740       InNonTrivialUnion = true;
11741     }
11742 
11743     if (InNonTrivialUnion)
11744       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11745           << 0 << 0 << QT.getUnqualifiedType() << "";
11746 
11747     for (const FieldDecl *FD : RD->fields())
11748       if (!shouldIgnoreForRecordTriviality(FD))
11749         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11750   }
11751 
11752   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11753 
11754   // The non-trivial C union type or the struct/union type that contains a
11755   // non-trivial C union.
11756   QualType OrigTy;
11757   SourceLocation OrigLoc;
11758   Sema::NonTrivialCUnionContext UseContext;
11759   Sema &S;
11760 };
11761 
11762 struct DiagNonTrivalCUnionDestructedTypeVisitor
11763     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11764   using Super =
11765       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11766 
11767   DiagNonTrivalCUnionDestructedTypeVisitor(
11768       QualType OrigTy, SourceLocation OrigLoc,
11769       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11770       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11771 
11772   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11773                      const FieldDecl *FD, bool InNonTrivialUnion) {
11774     if (const auto *AT = S.Context.getAsArrayType(QT))
11775       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11776                                      InNonTrivialUnion);
11777     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11778   }
11779 
11780   void visitARCStrong(QualType QT, const FieldDecl *FD,
11781                       bool InNonTrivialUnion) {
11782     if (InNonTrivialUnion)
11783       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11784           << 1 << 1 << QT << FD->getName();
11785   }
11786 
11787   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11788     if (InNonTrivialUnion)
11789       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11790           << 1 << 1 << QT << FD->getName();
11791   }
11792 
11793   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11794     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11795     if (RD->isUnion()) {
11796       if (OrigLoc.isValid()) {
11797         bool IsUnion = false;
11798         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11799           IsUnion = OrigRD->isUnion();
11800         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11801             << 1 << OrigTy << IsUnion << UseContext;
11802         // Reset OrigLoc so that this diagnostic is emitted only once.
11803         OrigLoc = SourceLocation();
11804       }
11805       InNonTrivialUnion = true;
11806     }
11807 
11808     if (InNonTrivialUnion)
11809       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11810           << 0 << 1 << QT.getUnqualifiedType() << "";
11811 
11812     for (const FieldDecl *FD : RD->fields())
11813       if (!shouldIgnoreForRecordTriviality(FD))
11814         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11815   }
11816 
11817   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11818   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11819                           bool InNonTrivialUnion) {}
11820 
11821   // The non-trivial C union type or the struct/union type that contains a
11822   // non-trivial C union.
11823   QualType OrigTy;
11824   SourceLocation OrigLoc;
11825   Sema::NonTrivialCUnionContext UseContext;
11826   Sema &S;
11827 };
11828 
11829 struct DiagNonTrivalCUnionCopyVisitor
11830     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11831   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11832 
11833   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11834                                  Sema::NonTrivialCUnionContext UseContext,
11835                                  Sema &S)
11836       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11837 
11838   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11839                      const FieldDecl *FD, bool InNonTrivialUnion) {
11840     if (const auto *AT = S.Context.getAsArrayType(QT))
11841       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11842                                      InNonTrivialUnion);
11843     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11844   }
11845 
11846   void visitARCStrong(QualType QT, const FieldDecl *FD,
11847                       bool InNonTrivialUnion) {
11848     if (InNonTrivialUnion)
11849       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11850           << 1 << 2 << QT << FD->getName();
11851   }
11852 
11853   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11854     if (InNonTrivialUnion)
11855       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11856           << 1 << 2 << QT << FD->getName();
11857   }
11858 
11859   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11860     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11861     if (RD->isUnion()) {
11862       if (OrigLoc.isValid()) {
11863         bool IsUnion = false;
11864         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11865           IsUnion = OrigRD->isUnion();
11866         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11867             << 2 << OrigTy << IsUnion << UseContext;
11868         // Reset OrigLoc so that this diagnostic is emitted only once.
11869         OrigLoc = SourceLocation();
11870       }
11871       InNonTrivialUnion = true;
11872     }
11873 
11874     if (InNonTrivialUnion)
11875       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11876           << 0 << 2 << QT.getUnqualifiedType() << "";
11877 
11878     for (const FieldDecl *FD : RD->fields())
11879       if (!shouldIgnoreForRecordTriviality(FD))
11880         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11881   }
11882 
11883   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11884                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11885   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11886   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11887                             bool InNonTrivialUnion) {}
11888 
11889   // The non-trivial C union type or the struct/union type that contains a
11890   // non-trivial C union.
11891   QualType OrigTy;
11892   SourceLocation OrigLoc;
11893   Sema::NonTrivialCUnionContext UseContext;
11894   Sema &S;
11895 };
11896 
11897 } // namespace
11898 
11899 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11900                                  NonTrivialCUnionContext UseContext,
11901                                  unsigned NonTrivialKind) {
11902   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11903           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11904           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11905          "shouldn't be called if type doesn't have a non-trivial C union");
11906 
11907   if ((NonTrivialKind & NTCUK_Init) &&
11908       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11909     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11910         .visit(QT, nullptr, false);
11911   if ((NonTrivialKind & NTCUK_Destruct) &&
11912       QT.hasNonTrivialToPrimitiveDestructCUnion())
11913     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11914         .visit(QT, nullptr, false);
11915   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11916     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11917         .visit(QT, nullptr, false);
11918 }
11919 
11920 /// AddInitializerToDecl - Adds the initializer Init to the
11921 /// declaration dcl. If DirectInit is true, this is C++ direct
11922 /// initialization rather than copy initialization.
11923 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11924   // If there is no declaration, there was an error parsing it.  Just ignore
11925   // the initializer.
11926   if (!RealDecl || RealDecl->isInvalidDecl()) {
11927     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11928     return;
11929   }
11930 
11931   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11932     // Pure-specifiers are handled in ActOnPureSpecifier.
11933     Diag(Method->getLocation(), diag::err_member_function_initialization)
11934       << Method->getDeclName() << Init->getSourceRange();
11935     Method->setInvalidDecl();
11936     return;
11937   }
11938 
11939   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11940   if (!VDecl) {
11941     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11942     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11943     RealDecl->setInvalidDecl();
11944     return;
11945   }
11946 
11947   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11948   if (VDecl->getType()->isUndeducedType()) {
11949     // Attempt typo correction early so that the type of the init expression can
11950     // be deduced based on the chosen correction if the original init contains a
11951     // TypoExpr.
11952     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11953     if (!Res.isUsable()) {
11954       // There are unresolved typos in Init, just drop them.
11955       // FIXME: improve the recovery strategy to preserve the Init.
11956       RealDecl->setInvalidDecl();
11957       return;
11958     }
11959     if (Res.get()->containsErrors()) {
11960       // Invalidate the decl as we don't know the type for recovery-expr yet.
11961       RealDecl->setInvalidDecl();
11962       VDecl->setInit(Res.get());
11963       return;
11964     }
11965     Init = Res.get();
11966 
11967     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11968       return;
11969   }
11970 
11971   // dllimport cannot be used on variable definitions.
11972   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11973     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11974     VDecl->setInvalidDecl();
11975     return;
11976   }
11977 
11978   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11979     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11980     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11981     VDecl->setInvalidDecl();
11982     return;
11983   }
11984 
11985   if (!VDecl->getType()->isDependentType()) {
11986     // A definition must end up with a complete type, which means it must be
11987     // complete with the restriction that an array type might be completed by
11988     // the initializer; note that later code assumes this restriction.
11989     QualType BaseDeclType = VDecl->getType();
11990     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11991       BaseDeclType = Array->getElementType();
11992     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11993                             diag::err_typecheck_decl_incomplete_type)) {
11994       RealDecl->setInvalidDecl();
11995       return;
11996     }
11997 
11998     // The variable can not have an abstract class type.
11999     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12000                                diag::err_abstract_type_in_decl,
12001                                AbstractVariableType))
12002       VDecl->setInvalidDecl();
12003   }
12004 
12005   // If adding the initializer will turn this declaration into a definition,
12006   // and we already have a definition for this variable, diagnose or otherwise
12007   // handle the situation.
12008   VarDecl *Def;
12009   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12010       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12011       !VDecl->isThisDeclarationADemotedDefinition() &&
12012       checkVarDeclRedefinition(Def, VDecl))
12013     return;
12014 
12015   if (getLangOpts().CPlusPlus) {
12016     // C++ [class.static.data]p4
12017     //   If a static data member is of const integral or const
12018     //   enumeration type, its declaration in the class definition can
12019     //   specify a constant-initializer which shall be an integral
12020     //   constant expression (5.19). In that case, the member can appear
12021     //   in integral constant expressions. The member shall still be
12022     //   defined in a namespace scope if it is used in the program and the
12023     //   namespace scope definition shall not contain an initializer.
12024     //
12025     // We already performed a redefinition check above, but for static
12026     // data members we also need to check whether there was an in-class
12027     // declaration with an initializer.
12028     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12029       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12030           << VDecl->getDeclName();
12031       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12032            diag::note_previous_initializer)
12033           << 0;
12034       return;
12035     }
12036 
12037     if (VDecl->hasLocalStorage())
12038       setFunctionHasBranchProtectedScope();
12039 
12040     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12041       VDecl->setInvalidDecl();
12042       return;
12043     }
12044   }
12045 
12046   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12047   // a kernel function cannot be initialized."
12048   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12049     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12050     VDecl->setInvalidDecl();
12051     return;
12052   }
12053 
12054   // The LoaderUninitialized attribute acts as a definition (of undef).
12055   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12056     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12057     VDecl->setInvalidDecl();
12058     return;
12059   }
12060 
12061   // Get the decls type and save a reference for later, since
12062   // CheckInitializerTypes may change it.
12063   QualType DclT = VDecl->getType(), SavT = DclT;
12064 
12065   // Expressions default to 'id' when we're in a debugger
12066   // and we are assigning it to a variable of Objective-C pointer type.
12067   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12068       Init->getType() == Context.UnknownAnyTy) {
12069     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12070     if (Result.isInvalid()) {
12071       VDecl->setInvalidDecl();
12072       return;
12073     }
12074     Init = Result.get();
12075   }
12076 
12077   // Perform the initialization.
12078   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12079   if (!VDecl->isInvalidDecl()) {
12080     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12081     InitializationKind Kind = InitializationKind::CreateForInit(
12082         VDecl->getLocation(), DirectInit, Init);
12083 
12084     MultiExprArg Args = Init;
12085     if (CXXDirectInit)
12086       Args = MultiExprArg(CXXDirectInit->getExprs(),
12087                           CXXDirectInit->getNumExprs());
12088 
12089     // Try to correct any TypoExprs in the initialization arguments.
12090     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12091       ExprResult Res = CorrectDelayedTyposInExpr(
12092           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12093           [this, Entity, Kind](Expr *E) {
12094             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12095             return Init.Failed() ? ExprError() : E;
12096           });
12097       if (Res.isInvalid()) {
12098         VDecl->setInvalidDecl();
12099       } else if (Res.get() != Args[Idx]) {
12100         Args[Idx] = Res.get();
12101       }
12102     }
12103     if (VDecl->isInvalidDecl())
12104       return;
12105 
12106     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12107                                    /*TopLevelOfInitList=*/false,
12108                                    /*TreatUnavailableAsInvalid=*/false);
12109     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12110     if (Result.isInvalid()) {
12111       // If the provied initializer fails to initialize the var decl,
12112       // we attach a recovery expr for better recovery.
12113       auto RecoveryExpr =
12114           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12115       if (RecoveryExpr.get())
12116         VDecl->setInit(RecoveryExpr.get());
12117       return;
12118     }
12119 
12120     Init = Result.getAs<Expr>();
12121   }
12122 
12123   // Check for self-references within variable initializers.
12124   // Variables declared within a function/method body (except for references)
12125   // are handled by a dataflow analysis.
12126   // This is undefined behavior in C++, but valid in C.
12127   if (getLangOpts().CPlusPlus) {
12128     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12129         VDecl->getType()->isReferenceType()) {
12130       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12131     }
12132   }
12133 
12134   // If the type changed, it means we had an incomplete type that was
12135   // completed by the initializer. For example:
12136   //   int ary[] = { 1, 3, 5 };
12137   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12138   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12139     VDecl->setType(DclT);
12140 
12141   if (!VDecl->isInvalidDecl()) {
12142     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12143 
12144     if (VDecl->hasAttr<BlocksAttr>())
12145       checkRetainCycles(VDecl, Init);
12146 
12147     // It is safe to assign a weak reference into a strong variable.
12148     // Although this code can still have problems:
12149     //   id x = self.weakProp;
12150     //   id y = self.weakProp;
12151     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12152     // paths through the function. This should be revisited if
12153     // -Wrepeated-use-of-weak is made flow-sensitive.
12154     if (FunctionScopeInfo *FSI = getCurFunction())
12155       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12156            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12157           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12158                            Init->getBeginLoc()))
12159         FSI->markSafeWeakUse(Init);
12160   }
12161 
12162   // The initialization is usually a full-expression.
12163   //
12164   // FIXME: If this is a braced initialization of an aggregate, it is not
12165   // an expression, and each individual field initializer is a separate
12166   // full-expression. For instance, in:
12167   //
12168   //   struct Temp { ~Temp(); };
12169   //   struct S { S(Temp); };
12170   //   struct T { S a, b; } t = { Temp(), Temp() }
12171   //
12172   // we should destroy the first Temp before constructing the second.
12173   ExprResult Result =
12174       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12175                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12176   if (Result.isInvalid()) {
12177     VDecl->setInvalidDecl();
12178     return;
12179   }
12180   Init = Result.get();
12181 
12182   // Attach the initializer to the decl.
12183   VDecl->setInit(Init);
12184 
12185   if (VDecl->isLocalVarDecl()) {
12186     // Don't check the initializer if the declaration is malformed.
12187     if (VDecl->isInvalidDecl()) {
12188       // do nothing
12189 
12190     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12191     // This is true even in C++ for OpenCL.
12192     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12193       CheckForConstantInitializer(Init, DclT);
12194 
12195     // Otherwise, C++ does not restrict the initializer.
12196     } else if (getLangOpts().CPlusPlus) {
12197       // do nothing
12198 
12199     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12200     // static storage duration shall be constant expressions or string literals.
12201     } else if (VDecl->getStorageClass() == SC_Static) {
12202       CheckForConstantInitializer(Init, DclT);
12203 
12204     // C89 is stricter than C99 for aggregate initializers.
12205     // C89 6.5.7p3: All the expressions [...] in an initializer list
12206     // for an object that has aggregate or union type shall be
12207     // constant expressions.
12208     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12209                isa<InitListExpr>(Init)) {
12210       const Expr *Culprit;
12211       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12212         Diag(Culprit->getExprLoc(),
12213              diag::ext_aggregate_init_not_constant)
12214           << Culprit->getSourceRange();
12215       }
12216     }
12217 
12218     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12219       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12220         if (VDecl->hasLocalStorage())
12221           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12222   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12223              VDecl->getLexicalDeclContext()->isRecord()) {
12224     // This is an in-class initialization for a static data member, e.g.,
12225     //
12226     // struct S {
12227     //   static const int value = 17;
12228     // };
12229 
12230     // C++ [class.mem]p4:
12231     //   A member-declarator can contain a constant-initializer only
12232     //   if it declares a static member (9.4) of const integral or
12233     //   const enumeration type, see 9.4.2.
12234     //
12235     // C++11 [class.static.data]p3:
12236     //   If a non-volatile non-inline const static data member is of integral
12237     //   or enumeration type, its declaration in the class definition can
12238     //   specify a brace-or-equal-initializer in which every initializer-clause
12239     //   that is an assignment-expression is a constant expression. A static
12240     //   data member of literal type can be declared in the class definition
12241     //   with the constexpr specifier; if so, its declaration shall specify a
12242     //   brace-or-equal-initializer in which every initializer-clause that is
12243     //   an assignment-expression is a constant expression.
12244 
12245     // Do nothing on dependent types.
12246     if (DclT->isDependentType()) {
12247 
12248     // Allow any 'static constexpr' members, whether or not they are of literal
12249     // type. We separately check that every constexpr variable is of literal
12250     // type.
12251     } else if (VDecl->isConstexpr()) {
12252 
12253     // Require constness.
12254     } else if (!DclT.isConstQualified()) {
12255       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12256         << Init->getSourceRange();
12257       VDecl->setInvalidDecl();
12258 
12259     // We allow integer constant expressions in all cases.
12260     } else if (DclT->isIntegralOrEnumerationType()) {
12261       // Check whether the expression is a constant expression.
12262       SourceLocation Loc;
12263       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12264         // In C++11, a non-constexpr const static data member with an
12265         // in-class initializer cannot be volatile.
12266         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12267       else if (Init->isValueDependent())
12268         ; // Nothing to check.
12269       else if (Init->isIntegerConstantExpr(Context, &Loc))
12270         ; // Ok, it's an ICE!
12271       else if (Init->getType()->isScopedEnumeralType() &&
12272                Init->isCXX11ConstantExpr(Context))
12273         ; // Ok, it is a scoped-enum constant expression.
12274       else if (Init->isEvaluatable(Context)) {
12275         // If we can constant fold the initializer through heroics, accept it,
12276         // but report this as a use of an extension for -pedantic.
12277         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12278           << Init->getSourceRange();
12279       } else {
12280         // Otherwise, this is some crazy unknown case.  Report the issue at the
12281         // location provided by the isIntegerConstantExpr failed check.
12282         Diag(Loc, diag::err_in_class_initializer_non_constant)
12283           << Init->getSourceRange();
12284         VDecl->setInvalidDecl();
12285       }
12286 
12287     // We allow foldable floating-point constants as an extension.
12288     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12289       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12290       // it anyway and provide a fixit to add the 'constexpr'.
12291       if (getLangOpts().CPlusPlus11) {
12292         Diag(VDecl->getLocation(),
12293              diag::ext_in_class_initializer_float_type_cxx11)
12294             << DclT << Init->getSourceRange();
12295         Diag(VDecl->getBeginLoc(),
12296              diag::note_in_class_initializer_float_type_cxx11)
12297             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12298       } else {
12299         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12300           << DclT << Init->getSourceRange();
12301 
12302         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12303           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12304             << Init->getSourceRange();
12305           VDecl->setInvalidDecl();
12306         }
12307       }
12308 
12309     // Suggest adding 'constexpr' in C++11 for literal types.
12310     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12311       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12312           << DclT << Init->getSourceRange()
12313           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12314       VDecl->setConstexpr(true);
12315 
12316     } else {
12317       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12318         << DclT << Init->getSourceRange();
12319       VDecl->setInvalidDecl();
12320     }
12321   } else if (VDecl->isFileVarDecl()) {
12322     // In C, extern is typically used to avoid tentative definitions when
12323     // declaring variables in headers, but adding an intializer makes it a
12324     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12325     // In C++, extern is often used to give implictly static const variables
12326     // external linkage, so don't warn in that case. If selectany is present,
12327     // this might be header code intended for C and C++ inclusion, so apply the
12328     // C++ rules.
12329     if (VDecl->getStorageClass() == SC_Extern &&
12330         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12331          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12332         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12333         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12334       Diag(VDecl->getLocation(), diag::warn_extern_init);
12335 
12336     // In Microsoft C++ mode, a const variable defined in namespace scope has
12337     // external linkage by default if the variable is declared with
12338     // __declspec(dllexport).
12339     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12340         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12341         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12342       VDecl->setStorageClass(SC_Extern);
12343 
12344     // C99 6.7.8p4. All file scoped initializers need to be constant.
12345     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12346       CheckForConstantInitializer(Init, DclT);
12347   }
12348 
12349   QualType InitType = Init->getType();
12350   if (!InitType.isNull() &&
12351       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12352        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12353     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12354 
12355   // We will represent direct-initialization similarly to copy-initialization:
12356   //    int x(1);  -as-> int x = 1;
12357   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12358   //
12359   // Clients that want to distinguish between the two forms, can check for
12360   // direct initializer using VarDecl::getInitStyle().
12361   // A major benefit is that clients that don't particularly care about which
12362   // exactly form was it (like the CodeGen) can handle both cases without
12363   // special case code.
12364 
12365   // C++ 8.5p11:
12366   // The form of initialization (using parentheses or '=') is generally
12367   // insignificant, but does matter when the entity being initialized has a
12368   // class type.
12369   if (CXXDirectInit) {
12370     assert(DirectInit && "Call-style initializer must be direct init.");
12371     VDecl->setInitStyle(VarDecl::CallInit);
12372   } else if (DirectInit) {
12373     // This must be list-initialization. No other way is direct-initialization.
12374     VDecl->setInitStyle(VarDecl::ListInit);
12375   }
12376 
12377   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12378     DeclsToCheckForDeferredDiags.push_back(VDecl);
12379   CheckCompleteVariableDeclaration(VDecl);
12380 }
12381 
12382 /// ActOnInitializerError - Given that there was an error parsing an
12383 /// initializer for the given declaration, try to return to some form
12384 /// of sanity.
12385 void Sema::ActOnInitializerError(Decl *D) {
12386   // Our main concern here is re-establishing invariants like "a
12387   // variable's type is either dependent or complete".
12388   if (!D || D->isInvalidDecl()) return;
12389 
12390   VarDecl *VD = dyn_cast<VarDecl>(D);
12391   if (!VD) return;
12392 
12393   // Bindings are not usable if we can't make sense of the initializer.
12394   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12395     for (auto *BD : DD->bindings())
12396       BD->setInvalidDecl();
12397 
12398   // Auto types are meaningless if we can't make sense of the initializer.
12399   if (VD->getType()->isUndeducedType()) {
12400     D->setInvalidDecl();
12401     return;
12402   }
12403 
12404   QualType Ty = VD->getType();
12405   if (Ty->isDependentType()) return;
12406 
12407   // Require a complete type.
12408   if (RequireCompleteType(VD->getLocation(),
12409                           Context.getBaseElementType(Ty),
12410                           diag::err_typecheck_decl_incomplete_type)) {
12411     VD->setInvalidDecl();
12412     return;
12413   }
12414 
12415   // Require a non-abstract type.
12416   if (RequireNonAbstractType(VD->getLocation(), Ty,
12417                              diag::err_abstract_type_in_decl,
12418                              AbstractVariableType)) {
12419     VD->setInvalidDecl();
12420     return;
12421   }
12422 
12423   // Don't bother complaining about constructors or destructors,
12424   // though.
12425 }
12426 
12427 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12428   // If there is no declaration, there was an error parsing it. Just ignore it.
12429   if (!RealDecl)
12430     return;
12431 
12432   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12433     QualType Type = Var->getType();
12434 
12435     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12436     if (isa<DecompositionDecl>(RealDecl)) {
12437       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12438       Var->setInvalidDecl();
12439       return;
12440     }
12441 
12442     if (Type->isUndeducedType() &&
12443         DeduceVariableDeclarationType(Var, false, nullptr))
12444       return;
12445 
12446     // C++11 [class.static.data]p3: A static data member can be declared with
12447     // the constexpr specifier; if so, its declaration shall specify
12448     // a brace-or-equal-initializer.
12449     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12450     // the definition of a variable [...] or the declaration of a static data
12451     // member.
12452     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12453         !Var->isThisDeclarationADemotedDefinition()) {
12454       if (Var->isStaticDataMember()) {
12455         // C++1z removes the relevant rule; the in-class declaration is always
12456         // a definition there.
12457         if (!getLangOpts().CPlusPlus17 &&
12458             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12459           Diag(Var->getLocation(),
12460                diag::err_constexpr_static_mem_var_requires_init)
12461               << Var;
12462           Var->setInvalidDecl();
12463           return;
12464         }
12465       } else {
12466         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12467         Var->setInvalidDecl();
12468         return;
12469       }
12470     }
12471 
12472     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12473     // be initialized.
12474     if (!Var->isInvalidDecl() &&
12475         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12476         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12477       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12478       Var->setInvalidDecl();
12479       return;
12480     }
12481 
12482     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12483       if (Var->getStorageClass() == SC_Extern) {
12484         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12485             << Var;
12486         Var->setInvalidDecl();
12487         return;
12488       }
12489       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12490                               diag::err_typecheck_decl_incomplete_type)) {
12491         Var->setInvalidDecl();
12492         return;
12493       }
12494       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12495         if (!RD->hasTrivialDefaultConstructor()) {
12496           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12497           Var->setInvalidDecl();
12498           return;
12499         }
12500       }
12501     }
12502 
12503     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12504     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12505         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12506       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12507                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12508 
12509 
12510     switch (DefKind) {
12511     case VarDecl::Definition:
12512       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12513         break;
12514 
12515       // We have an out-of-line definition of a static data member
12516       // that has an in-class initializer, so we type-check this like
12517       // a declaration.
12518       //
12519       LLVM_FALLTHROUGH;
12520 
12521     case VarDecl::DeclarationOnly:
12522       // It's only a declaration.
12523 
12524       // Block scope. C99 6.7p7: If an identifier for an object is
12525       // declared with no linkage (C99 6.2.2p6), the type for the
12526       // object shall be complete.
12527       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12528           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12529           RequireCompleteType(Var->getLocation(), Type,
12530                               diag::err_typecheck_decl_incomplete_type))
12531         Var->setInvalidDecl();
12532 
12533       // Make sure that the type is not abstract.
12534       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12535           RequireNonAbstractType(Var->getLocation(), Type,
12536                                  diag::err_abstract_type_in_decl,
12537                                  AbstractVariableType))
12538         Var->setInvalidDecl();
12539       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12540           Var->getStorageClass() == SC_PrivateExtern) {
12541         Diag(Var->getLocation(), diag::warn_private_extern);
12542         Diag(Var->getLocation(), diag::note_private_extern);
12543       }
12544 
12545       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12546           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12547         ExternalDeclarations.push_back(Var);
12548 
12549       return;
12550 
12551     case VarDecl::TentativeDefinition:
12552       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12553       // object that has file scope without an initializer, and without a
12554       // storage-class specifier or with the storage-class specifier "static",
12555       // constitutes a tentative definition. Note: A tentative definition with
12556       // external linkage is valid (C99 6.2.2p5).
12557       if (!Var->isInvalidDecl()) {
12558         if (const IncompleteArrayType *ArrayT
12559                                     = Context.getAsIncompleteArrayType(Type)) {
12560           if (RequireCompleteSizedType(
12561                   Var->getLocation(), ArrayT->getElementType(),
12562                   diag::err_array_incomplete_or_sizeless_type))
12563             Var->setInvalidDecl();
12564         } else if (Var->getStorageClass() == SC_Static) {
12565           // C99 6.9.2p3: If the declaration of an identifier for an object is
12566           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12567           // declared type shall not be an incomplete type.
12568           // NOTE: code such as the following
12569           //     static struct s;
12570           //     struct s { int a; };
12571           // is accepted by gcc. Hence here we issue a warning instead of
12572           // an error and we do not invalidate the static declaration.
12573           // NOTE: to avoid multiple warnings, only check the first declaration.
12574           if (Var->isFirstDecl())
12575             RequireCompleteType(Var->getLocation(), Type,
12576                                 diag::ext_typecheck_decl_incomplete_type);
12577         }
12578       }
12579 
12580       // Record the tentative definition; we're done.
12581       if (!Var->isInvalidDecl())
12582         TentativeDefinitions.push_back(Var);
12583       return;
12584     }
12585 
12586     // Provide a specific diagnostic for uninitialized variable
12587     // definitions with incomplete array type.
12588     if (Type->isIncompleteArrayType()) {
12589       Diag(Var->getLocation(),
12590            diag::err_typecheck_incomplete_array_needs_initializer);
12591       Var->setInvalidDecl();
12592       return;
12593     }
12594 
12595     // Provide a specific diagnostic for uninitialized variable
12596     // definitions with reference type.
12597     if (Type->isReferenceType()) {
12598       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12599           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12600       Var->setInvalidDecl();
12601       return;
12602     }
12603 
12604     // Do not attempt to type-check the default initializer for a
12605     // variable with dependent type.
12606     if (Type->isDependentType())
12607       return;
12608 
12609     if (Var->isInvalidDecl())
12610       return;
12611 
12612     if (!Var->hasAttr<AliasAttr>()) {
12613       if (RequireCompleteType(Var->getLocation(),
12614                               Context.getBaseElementType(Type),
12615                               diag::err_typecheck_decl_incomplete_type)) {
12616         Var->setInvalidDecl();
12617         return;
12618       }
12619     } else {
12620       return;
12621     }
12622 
12623     // The variable can not have an abstract class type.
12624     if (RequireNonAbstractType(Var->getLocation(), Type,
12625                                diag::err_abstract_type_in_decl,
12626                                AbstractVariableType)) {
12627       Var->setInvalidDecl();
12628       return;
12629     }
12630 
12631     // Check for jumps past the implicit initializer.  C++0x
12632     // clarifies that this applies to a "variable with automatic
12633     // storage duration", not a "local variable".
12634     // C++11 [stmt.dcl]p3
12635     //   A program that jumps from a point where a variable with automatic
12636     //   storage duration is not in scope to a point where it is in scope is
12637     //   ill-formed unless the variable has scalar type, class type with a
12638     //   trivial default constructor and a trivial destructor, a cv-qualified
12639     //   version of one of these types, or an array of one of the preceding
12640     //   types and is declared without an initializer.
12641     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12642       if (const RecordType *Record
12643             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12644         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12645         // Mark the function (if we're in one) for further checking even if the
12646         // looser rules of C++11 do not require such checks, so that we can
12647         // diagnose incompatibilities with C++98.
12648         if (!CXXRecord->isPOD())
12649           setFunctionHasBranchProtectedScope();
12650       }
12651     }
12652     // In OpenCL, we can't initialize objects in the __local address space,
12653     // even implicitly, so don't synthesize an implicit initializer.
12654     if (getLangOpts().OpenCL &&
12655         Var->getType().getAddressSpace() == LangAS::opencl_local)
12656       return;
12657     // C++03 [dcl.init]p9:
12658     //   If no initializer is specified for an object, and the
12659     //   object is of (possibly cv-qualified) non-POD class type (or
12660     //   array thereof), the object shall be default-initialized; if
12661     //   the object is of const-qualified type, the underlying class
12662     //   type shall have a user-declared default
12663     //   constructor. Otherwise, if no initializer is specified for
12664     //   a non- static object, the object and its subobjects, if
12665     //   any, have an indeterminate initial value); if the object
12666     //   or any of its subobjects are of const-qualified type, the
12667     //   program is ill-formed.
12668     // C++0x [dcl.init]p11:
12669     //   If no initializer is specified for an object, the object is
12670     //   default-initialized; [...].
12671     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12672     InitializationKind Kind
12673       = InitializationKind::CreateDefault(Var->getLocation());
12674 
12675     InitializationSequence InitSeq(*this, Entity, Kind, None);
12676     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12677 
12678     if (Init.get()) {
12679       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12680       // This is important for template substitution.
12681       Var->setInitStyle(VarDecl::CallInit);
12682     } else if (Init.isInvalid()) {
12683       // If default-init fails, attach a recovery-expr initializer to track
12684       // that initialization was attempted and failed.
12685       auto RecoveryExpr =
12686           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12687       if (RecoveryExpr.get())
12688         Var->setInit(RecoveryExpr.get());
12689     }
12690 
12691     CheckCompleteVariableDeclaration(Var);
12692   }
12693 }
12694 
12695 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12696   // If there is no declaration, there was an error parsing it. Ignore it.
12697   if (!D)
12698     return;
12699 
12700   VarDecl *VD = dyn_cast<VarDecl>(D);
12701   if (!VD) {
12702     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12703     D->setInvalidDecl();
12704     return;
12705   }
12706 
12707   VD->setCXXForRangeDecl(true);
12708 
12709   // for-range-declaration cannot be given a storage class specifier.
12710   int Error = -1;
12711   switch (VD->getStorageClass()) {
12712   case SC_None:
12713     break;
12714   case SC_Extern:
12715     Error = 0;
12716     break;
12717   case SC_Static:
12718     Error = 1;
12719     break;
12720   case SC_PrivateExtern:
12721     Error = 2;
12722     break;
12723   case SC_Auto:
12724     Error = 3;
12725     break;
12726   case SC_Register:
12727     Error = 4;
12728     break;
12729   }
12730   if (Error != -1) {
12731     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12732         << VD << Error;
12733     D->setInvalidDecl();
12734   }
12735 }
12736 
12737 StmtResult
12738 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12739                                  IdentifierInfo *Ident,
12740                                  ParsedAttributes &Attrs,
12741                                  SourceLocation AttrEnd) {
12742   // C++1y [stmt.iter]p1:
12743   //   A range-based for statement of the form
12744   //      for ( for-range-identifier : for-range-initializer ) statement
12745   //   is equivalent to
12746   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12747   DeclSpec DS(Attrs.getPool().getFactory());
12748 
12749   const char *PrevSpec;
12750   unsigned DiagID;
12751   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12752                      getPrintingPolicy());
12753 
12754   Declarator D(DS, DeclaratorContext::ForContext);
12755   D.SetIdentifier(Ident, IdentLoc);
12756   D.takeAttributes(Attrs, AttrEnd);
12757 
12758   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12759                 IdentLoc);
12760   Decl *Var = ActOnDeclarator(S, D);
12761   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12762   FinalizeDeclaration(Var);
12763   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12764                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12765 }
12766 
12767 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12768   if (var->isInvalidDecl()) return;
12769 
12770   if (getLangOpts().OpenCL) {
12771     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12772     // initialiser
12773     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12774         !var->hasInit()) {
12775       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12776           << 1 /*Init*/;
12777       var->setInvalidDecl();
12778       return;
12779     }
12780   }
12781 
12782   // In Objective-C, don't allow jumps past the implicit initialization of a
12783   // local retaining variable.
12784   if (getLangOpts().ObjC &&
12785       var->hasLocalStorage()) {
12786     switch (var->getType().getObjCLifetime()) {
12787     case Qualifiers::OCL_None:
12788     case Qualifiers::OCL_ExplicitNone:
12789     case Qualifiers::OCL_Autoreleasing:
12790       break;
12791 
12792     case Qualifiers::OCL_Weak:
12793     case Qualifiers::OCL_Strong:
12794       setFunctionHasBranchProtectedScope();
12795       break;
12796     }
12797   }
12798 
12799   if (var->hasLocalStorage() &&
12800       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12801     setFunctionHasBranchProtectedScope();
12802 
12803   // Warn about externally-visible variables being defined without a
12804   // prior declaration.  We only want to do this for global
12805   // declarations, but we also specifically need to avoid doing it for
12806   // class members because the linkage of an anonymous class can
12807   // change if it's later given a typedef name.
12808   if (var->isThisDeclarationADefinition() &&
12809       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12810       var->isExternallyVisible() && var->hasLinkage() &&
12811       !var->isInline() && !var->getDescribedVarTemplate() &&
12812       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12813       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12814       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12815                                   var->getLocation())) {
12816     // Find a previous declaration that's not a definition.
12817     VarDecl *prev = var->getPreviousDecl();
12818     while (prev && prev->isThisDeclarationADefinition())
12819       prev = prev->getPreviousDecl();
12820 
12821     if (!prev) {
12822       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12823       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12824           << /* variable */ 0;
12825     }
12826   }
12827 
12828   // Cache the result of checking for constant initialization.
12829   Optional<bool> CacheHasConstInit;
12830   const Expr *CacheCulprit = nullptr;
12831   auto checkConstInit = [&]() mutable {
12832     if (!CacheHasConstInit)
12833       CacheHasConstInit = var->getInit()->isConstantInitializer(
12834             Context, var->getType()->isReferenceType(), &CacheCulprit);
12835     return *CacheHasConstInit;
12836   };
12837 
12838   if (var->getTLSKind() == VarDecl::TLS_Static) {
12839     if (var->getType().isDestructedType()) {
12840       // GNU C++98 edits for __thread, [basic.start.term]p3:
12841       //   The type of an object with thread storage duration shall not
12842       //   have a non-trivial destructor.
12843       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12844       if (getLangOpts().CPlusPlus11)
12845         Diag(var->getLocation(), diag::note_use_thread_local);
12846     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12847       if (!checkConstInit()) {
12848         // GNU C++98 edits for __thread, [basic.start.init]p4:
12849         //   An object of thread storage duration shall not require dynamic
12850         //   initialization.
12851         // FIXME: Need strict checking here.
12852         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12853           << CacheCulprit->getSourceRange();
12854         if (getLangOpts().CPlusPlus11)
12855           Diag(var->getLocation(), diag::note_use_thread_local);
12856       }
12857     }
12858   }
12859 
12860   // Apply section attributes and pragmas to global variables.
12861   bool GlobalStorage = var->hasGlobalStorage();
12862   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12863       !inTemplateInstantiation()) {
12864     PragmaStack<StringLiteral *> *Stack = nullptr;
12865     int SectionFlags = ASTContext::PSF_Read;
12866     if (var->getType().isConstQualified())
12867       Stack = &ConstSegStack;
12868     else if (!var->getInit()) {
12869       Stack = &BSSSegStack;
12870       SectionFlags |= ASTContext::PSF_Write;
12871     } else {
12872       Stack = &DataSegStack;
12873       SectionFlags |= ASTContext::PSF_Write;
12874     }
12875     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12876       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12877         SectionFlags |= ASTContext::PSF_Implicit;
12878       UnifySection(SA->getName(), SectionFlags, var);
12879     } else if (Stack->CurrentValue) {
12880       SectionFlags |= ASTContext::PSF_Implicit;
12881       auto SectionName = Stack->CurrentValue->getString();
12882       var->addAttr(SectionAttr::CreateImplicit(
12883           Context, SectionName, Stack->CurrentPragmaLocation,
12884           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12885       if (UnifySection(SectionName, SectionFlags, var))
12886         var->dropAttr<SectionAttr>();
12887     }
12888 
12889     // Apply the init_seg attribute if this has an initializer.  If the
12890     // initializer turns out to not be dynamic, we'll end up ignoring this
12891     // attribute.
12892     if (CurInitSeg && var->getInit())
12893       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12894                                                CurInitSegLoc,
12895                                                AttributeCommonInfo::AS_Pragma));
12896   }
12897 
12898   if (!var->getType()->isStructureType() && var->hasInit() &&
12899       isa<InitListExpr>(var->getInit())) {
12900     const auto *ILE = cast<InitListExpr>(var->getInit());
12901     unsigned NumInits = ILE->getNumInits();
12902     if (NumInits > 2)
12903       for (unsigned I = 0; I < NumInits; ++I) {
12904         const auto *Init = ILE->getInit(I);
12905         if (!Init)
12906           break;
12907         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12908         if (!SL)
12909           break;
12910 
12911         unsigned NumConcat = SL->getNumConcatenated();
12912         // Diagnose missing comma in string array initialization.
12913         // Do not warn when all the elements in the initializer are concatenated
12914         // together. Do not warn for macros too.
12915         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12916           bool OnlyOneMissingComma = true;
12917           for (unsigned J = I + 1; J < NumInits; ++J) {
12918             const auto *Init = ILE->getInit(J);
12919             if (!Init)
12920               break;
12921             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12922             if (!SLJ || SLJ->getNumConcatenated() > 1) {
12923               OnlyOneMissingComma = false;
12924               break;
12925             }
12926           }
12927 
12928           if (OnlyOneMissingComma) {
12929             SmallVector<FixItHint, 1> Hints;
12930             for (unsigned i = 0; i < NumConcat - 1; ++i)
12931               Hints.push_back(FixItHint::CreateInsertion(
12932                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12933 
12934             Diag(SL->getStrTokenLoc(1),
12935                  diag::warn_concatenated_literal_array_init)
12936                 << Hints;
12937             Diag(SL->getBeginLoc(),
12938                  diag::note_concatenated_string_literal_silence);
12939           }
12940           // In any case, stop now.
12941           break;
12942         }
12943       }
12944   }
12945 
12946   // All the following checks are C++ only.
12947   if (!getLangOpts().CPlusPlus) {
12948       // If this variable must be emitted, add it as an initializer for the
12949       // current module.
12950      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12951        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12952      return;
12953   }
12954 
12955   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12956     CheckCompleteDecompositionDeclaration(DD);
12957 
12958   QualType type = var->getType();
12959   if (type->isDependentType()) return;
12960 
12961   if (var->hasAttr<BlocksAttr>())
12962     getCurFunction()->addByrefBlockVar(var);
12963 
12964   Expr *Init = var->getInit();
12965   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12966   QualType baseType = Context.getBaseElementType(type);
12967 
12968   if (Init && !Init->isValueDependent()) {
12969     if (var->isConstexpr()) {
12970       SmallVector<PartialDiagnosticAt, 8> Notes;
12971       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12972         SourceLocation DiagLoc = var->getLocation();
12973         // If the note doesn't add any useful information other than a source
12974         // location, fold it into the primary diagnostic.
12975         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12976               diag::note_invalid_subexpr_in_const_expr) {
12977           DiagLoc = Notes[0].first;
12978           Notes.clear();
12979         }
12980         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12981           << var << Init->getSourceRange();
12982         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12983           Diag(Notes[I].first, Notes[I].second);
12984       }
12985     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12986       // Check whether the initializer of a const variable of integral or
12987       // enumeration type is an ICE now, since we can't tell whether it was
12988       // initialized by a constant expression if we check later.
12989       var->checkInitIsICE();
12990     }
12991 
12992     // Don't emit further diagnostics about constexpr globals since they
12993     // were just diagnosed.
12994     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12995       // FIXME: Need strict checking in C++03 here.
12996       bool DiagErr = getLangOpts().CPlusPlus11
12997           ? !var->checkInitIsICE() : !checkConstInit();
12998       if (DiagErr) {
12999         auto *Attr = var->getAttr<ConstInitAttr>();
13000         Diag(var->getLocation(), diag::err_require_constant_init_failed)
13001           << Init->getSourceRange();
13002         Diag(Attr->getLocation(),
13003              diag::note_declared_required_constant_init_here)
13004             << Attr->getRange() << Attr->isConstinit();
13005         if (getLangOpts().CPlusPlus11) {
13006           APValue Value;
13007           SmallVector<PartialDiagnosticAt, 8> Notes;
13008           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
13009           for (auto &it : Notes)
13010             Diag(it.first, it.second);
13011         } else {
13012           Diag(CacheCulprit->getExprLoc(),
13013                diag::note_invalid_subexpr_in_const_expr)
13014               << CacheCulprit->getSourceRange();
13015         }
13016       }
13017     }
13018     else if (!var->isConstexpr() && IsGlobal &&
13019              !getDiagnostics().isIgnored(diag::warn_global_constructor,
13020                                     var->getLocation())) {
13021       // Warn about globals which don't have a constant initializer.  Don't
13022       // warn about globals with a non-trivial destructor because we already
13023       // warned about them.
13024       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13025       if (!(RD && !RD->hasTrivialDestructor())) {
13026         if (!checkConstInit())
13027           Diag(var->getLocation(), diag::warn_global_constructor)
13028             << Init->getSourceRange();
13029       }
13030     }
13031   }
13032 
13033   // Require the destructor.
13034   if (const RecordType *recordType = baseType->getAs<RecordType>())
13035     FinalizeVarWithDestructor(var, recordType);
13036 
13037   // If this variable must be emitted, add it as an initializer for the current
13038   // module.
13039   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13040     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13041 }
13042 
13043 /// Determines if a variable's alignment is dependent.
13044 static bool hasDependentAlignment(VarDecl *VD) {
13045   if (VD->getType()->isDependentType())
13046     return true;
13047   for (auto *I : VD->specific_attrs<AlignedAttr>())
13048     if (I->isAlignmentDependent())
13049       return true;
13050   return false;
13051 }
13052 
13053 /// Check if VD needs to be dllexport/dllimport due to being in a
13054 /// dllexport/import function.
13055 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13056   assert(VD->isStaticLocal());
13057 
13058   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13059 
13060   // Find outermost function when VD is in lambda function.
13061   while (FD && !getDLLAttr(FD) &&
13062          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13063          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13064     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13065   }
13066 
13067   if (!FD)
13068     return;
13069 
13070   // Static locals inherit dll attributes from their function.
13071   if (Attr *A = getDLLAttr(FD)) {
13072     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13073     NewAttr->setInherited(true);
13074     VD->addAttr(NewAttr);
13075   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13076     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13077     NewAttr->setInherited(true);
13078     VD->addAttr(NewAttr);
13079 
13080     // Export this function to enforce exporting this static variable even
13081     // if it is not used in this compilation unit.
13082     if (!FD->hasAttr<DLLExportAttr>())
13083       FD->addAttr(NewAttr);
13084 
13085   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13086     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13087     NewAttr->setInherited(true);
13088     VD->addAttr(NewAttr);
13089   }
13090 }
13091 
13092 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13093 /// any semantic actions necessary after any initializer has been attached.
13094 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13095   // Note that we are no longer parsing the initializer for this declaration.
13096   ParsingInitForAutoVars.erase(ThisDecl);
13097 
13098   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13099   if (!VD)
13100     return;
13101 
13102   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13103   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13104       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13105     if (PragmaClangBSSSection.Valid)
13106       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13107           Context, PragmaClangBSSSection.SectionName,
13108           PragmaClangBSSSection.PragmaLocation,
13109           AttributeCommonInfo::AS_Pragma));
13110     if (PragmaClangDataSection.Valid)
13111       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13112           Context, PragmaClangDataSection.SectionName,
13113           PragmaClangDataSection.PragmaLocation,
13114           AttributeCommonInfo::AS_Pragma));
13115     if (PragmaClangRodataSection.Valid)
13116       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13117           Context, PragmaClangRodataSection.SectionName,
13118           PragmaClangRodataSection.PragmaLocation,
13119           AttributeCommonInfo::AS_Pragma));
13120     if (PragmaClangRelroSection.Valid)
13121       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13122           Context, PragmaClangRelroSection.SectionName,
13123           PragmaClangRelroSection.PragmaLocation,
13124           AttributeCommonInfo::AS_Pragma));
13125   }
13126 
13127   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13128     for (auto *BD : DD->bindings()) {
13129       FinalizeDeclaration(BD);
13130     }
13131   }
13132 
13133   checkAttributesAfterMerging(*this, *VD);
13134 
13135   // Perform TLS alignment check here after attributes attached to the variable
13136   // which may affect the alignment have been processed. Only perform the check
13137   // if the target has a maximum TLS alignment (zero means no constraints).
13138   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13139     // Protect the check so that it's not performed on dependent types and
13140     // dependent alignments (we can't determine the alignment in that case).
13141     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13142         !VD->isInvalidDecl()) {
13143       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13144       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13145         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13146           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13147           << (unsigned)MaxAlignChars.getQuantity();
13148       }
13149     }
13150   }
13151 
13152   if (VD->isStaticLocal()) {
13153     CheckStaticLocalForDllExport(VD);
13154 
13155     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13156       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13157       // function, only __shared__ variables or variables without any device
13158       // memory qualifiers may be declared with static storage class.
13159       // Note: It is unclear how a function-scope non-const static variable
13160       // without device memory qualifier is implemented, therefore only static
13161       // const variable without device memory qualifier is allowed.
13162       [&]() {
13163         if (!getLangOpts().CUDA)
13164           return;
13165         if (VD->hasAttr<CUDASharedAttr>())
13166           return;
13167         if (VD->getType().isConstQualified() &&
13168             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13169           return;
13170         if (CUDADiagIfDeviceCode(VD->getLocation(),
13171                                  diag::err_device_static_local_var)
13172             << CurrentCUDATarget())
13173           VD->setInvalidDecl();
13174       }();
13175     }
13176   }
13177 
13178   // Perform check for initializers of device-side global variables.
13179   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13180   // 7.5). We must also apply the same checks to all __shared__
13181   // variables whether they are local or not. CUDA also allows
13182   // constant initializers for __constant__ and __device__ variables.
13183   if (getLangOpts().CUDA)
13184     checkAllowedCUDAInitializer(VD);
13185 
13186   // Grab the dllimport or dllexport attribute off of the VarDecl.
13187   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13188 
13189   // Imported static data members cannot be defined out-of-line.
13190   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13191     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13192         VD->isThisDeclarationADefinition()) {
13193       // We allow definitions of dllimport class template static data members
13194       // with a warning.
13195       CXXRecordDecl *Context =
13196         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13197       bool IsClassTemplateMember =
13198           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13199           Context->getDescribedClassTemplate();
13200 
13201       Diag(VD->getLocation(),
13202            IsClassTemplateMember
13203                ? diag::warn_attribute_dllimport_static_field_definition
13204                : diag::err_attribute_dllimport_static_field_definition);
13205       Diag(IA->getLocation(), diag::note_attribute);
13206       if (!IsClassTemplateMember)
13207         VD->setInvalidDecl();
13208     }
13209   }
13210 
13211   // dllimport/dllexport variables cannot be thread local, their TLS index
13212   // isn't exported with the variable.
13213   if (DLLAttr && VD->getTLSKind()) {
13214     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13215     if (F && getDLLAttr(F)) {
13216       assert(VD->isStaticLocal());
13217       // But if this is a static local in a dlimport/dllexport function, the
13218       // function will never be inlined, which means the var would never be
13219       // imported, so having it marked import/export is safe.
13220     } else {
13221       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13222                                                                     << DLLAttr;
13223       VD->setInvalidDecl();
13224     }
13225   }
13226 
13227   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13228     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13229       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13230       VD->dropAttr<UsedAttr>();
13231     }
13232   }
13233 
13234   const DeclContext *DC = VD->getDeclContext();
13235   // If there's a #pragma GCC visibility in scope, and this isn't a class
13236   // member, set the visibility of this variable.
13237   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13238     AddPushedVisibilityAttribute(VD);
13239 
13240   // FIXME: Warn on unused var template partial specializations.
13241   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13242     MarkUnusedFileScopedDecl(VD);
13243 
13244   // Now we have parsed the initializer and can update the table of magic
13245   // tag values.
13246   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13247       !VD->getType()->isIntegralOrEnumerationType())
13248     return;
13249 
13250   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13251     const Expr *MagicValueExpr = VD->getInit();
13252     if (!MagicValueExpr) {
13253       continue;
13254     }
13255     Optional<llvm::APSInt> MagicValueInt;
13256     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13257       Diag(I->getRange().getBegin(),
13258            diag::err_type_tag_for_datatype_not_ice)
13259         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13260       continue;
13261     }
13262     if (MagicValueInt->getActiveBits() > 64) {
13263       Diag(I->getRange().getBegin(),
13264            diag::err_type_tag_for_datatype_too_large)
13265         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13266       continue;
13267     }
13268     uint64_t MagicValue = MagicValueInt->getZExtValue();
13269     RegisterTypeTagForDatatype(I->getArgumentKind(),
13270                                MagicValue,
13271                                I->getMatchingCType(),
13272                                I->getLayoutCompatible(),
13273                                I->getMustBeNull());
13274   }
13275 }
13276 
13277 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13278   auto *VD = dyn_cast<VarDecl>(DD);
13279   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13280 }
13281 
13282 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13283                                                    ArrayRef<Decl *> Group) {
13284   SmallVector<Decl*, 8> Decls;
13285 
13286   if (DS.isTypeSpecOwned())
13287     Decls.push_back(DS.getRepAsDecl());
13288 
13289   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13290   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13291   bool DiagnosedMultipleDecomps = false;
13292   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13293   bool DiagnosedNonDeducedAuto = false;
13294 
13295   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13296     if (Decl *D = Group[i]) {
13297       // For declarators, there are some additional syntactic-ish checks we need
13298       // to perform.
13299       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13300         if (!FirstDeclaratorInGroup)
13301           FirstDeclaratorInGroup = DD;
13302         if (!FirstDecompDeclaratorInGroup)
13303           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13304         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13305             !hasDeducedAuto(DD))
13306           FirstNonDeducedAutoInGroup = DD;
13307 
13308         if (FirstDeclaratorInGroup != DD) {
13309           // A decomposition declaration cannot be combined with any other
13310           // declaration in the same group.
13311           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13312             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13313                  diag::err_decomp_decl_not_alone)
13314                 << FirstDeclaratorInGroup->getSourceRange()
13315                 << DD->getSourceRange();
13316             DiagnosedMultipleDecomps = true;
13317           }
13318 
13319           // A declarator that uses 'auto' in any way other than to declare a
13320           // variable with a deduced type cannot be combined with any other
13321           // declarator in the same group.
13322           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13323             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13324                  diag::err_auto_non_deduced_not_alone)
13325                 << FirstNonDeducedAutoInGroup->getType()
13326                        ->hasAutoForTrailingReturnType()
13327                 << FirstDeclaratorInGroup->getSourceRange()
13328                 << DD->getSourceRange();
13329             DiagnosedNonDeducedAuto = true;
13330           }
13331         }
13332       }
13333 
13334       Decls.push_back(D);
13335     }
13336   }
13337 
13338   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13339     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13340       handleTagNumbering(Tag, S);
13341       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13342           getLangOpts().CPlusPlus)
13343         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13344     }
13345   }
13346 
13347   return BuildDeclaratorGroup(Decls);
13348 }
13349 
13350 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13351 /// group, performing any necessary semantic checking.
13352 Sema::DeclGroupPtrTy
13353 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13354   // C++14 [dcl.spec.auto]p7: (DR1347)
13355   //   If the type that replaces the placeholder type is not the same in each
13356   //   deduction, the program is ill-formed.
13357   if (Group.size() > 1) {
13358     QualType Deduced;
13359     VarDecl *DeducedDecl = nullptr;
13360     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13361       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13362       if (!D || D->isInvalidDecl())
13363         break;
13364       DeducedType *DT = D->getType()->getContainedDeducedType();
13365       if (!DT || DT->getDeducedType().isNull())
13366         continue;
13367       if (Deduced.isNull()) {
13368         Deduced = DT->getDeducedType();
13369         DeducedDecl = D;
13370       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13371         auto *AT = dyn_cast<AutoType>(DT);
13372         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13373                         diag::err_auto_different_deductions)
13374                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13375                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13376                    << D->getDeclName();
13377         if (DeducedDecl->hasInit())
13378           Dia << DeducedDecl->getInit()->getSourceRange();
13379         if (D->getInit())
13380           Dia << D->getInit()->getSourceRange();
13381         D->setInvalidDecl();
13382         break;
13383       }
13384     }
13385   }
13386 
13387   ActOnDocumentableDecls(Group);
13388 
13389   return DeclGroupPtrTy::make(
13390       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13391 }
13392 
13393 void Sema::ActOnDocumentableDecl(Decl *D) {
13394   ActOnDocumentableDecls(D);
13395 }
13396 
13397 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13398   // Don't parse the comment if Doxygen diagnostics are ignored.
13399   if (Group.empty() || !Group[0])
13400     return;
13401 
13402   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13403                       Group[0]->getLocation()) &&
13404       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13405                       Group[0]->getLocation()))
13406     return;
13407 
13408   if (Group.size() >= 2) {
13409     // This is a decl group.  Normally it will contain only declarations
13410     // produced from declarator list.  But in case we have any definitions or
13411     // additional declaration references:
13412     //   'typedef struct S {} S;'
13413     //   'typedef struct S *S;'
13414     //   'struct S *pS;'
13415     // FinalizeDeclaratorGroup adds these as separate declarations.
13416     Decl *MaybeTagDecl = Group[0];
13417     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13418       Group = Group.slice(1);
13419     }
13420   }
13421 
13422   // FIMXE: We assume every Decl in the group is in the same file.
13423   // This is false when preprocessor constructs the group from decls in
13424   // different files (e. g. macros or #include).
13425   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13426 }
13427 
13428 /// Common checks for a parameter-declaration that should apply to both function
13429 /// parameters and non-type template parameters.
13430 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13431   // Check that there are no default arguments inside the type of this
13432   // parameter.
13433   if (getLangOpts().CPlusPlus)
13434     CheckExtraCXXDefaultArguments(D);
13435 
13436   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13437   if (D.getCXXScopeSpec().isSet()) {
13438     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13439       << D.getCXXScopeSpec().getRange();
13440   }
13441 
13442   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13443   // simple identifier except [...irrelevant cases...].
13444   switch (D.getName().getKind()) {
13445   case UnqualifiedIdKind::IK_Identifier:
13446     break;
13447 
13448   case UnqualifiedIdKind::IK_OperatorFunctionId:
13449   case UnqualifiedIdKind::IK_ConversionFunctionId:
13450   case UnqualifiedIdKind::IK_LiteralOperatorId:
13451   case UnqualifiedIdKind::IK_ConstructorName:
13452   case UnqualifiedIdKind::IK_DestructorName:
13453   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13454   case UnqualifiedIdKind::IK_DeductionGuideName:
13455     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13456       << GetNameForDeclarator(D).getName();
13457     break;
13458 
13459   case UnqualifiedIdKind::IK_TemplateId:
13460   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13461     // GetNameForDeclarator would not produce a useful name in this case.
13462     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13463     break;
13464   }
13465 }
13466 
13467 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13468 /// to introduce parameters into function prototype scope.
13469 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13470   const DeclSpec &DS = D.getDeclSpec();
13471 
13472   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13473 
13474   // C++03 [dcl.stc]p2 also permits 'auto'.
13475   StorageClass SC = SC_None;
13476   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13477     SC = SC_Register;
13478     // In C++11, the 'register' storage class specifier is deprecated.
13479     // In C++17, it is not allowed, but we tolerate it as an extension.
13480     if (getLangOpts().CPlusPlus11) {
13481       Diag(DS.getStorageClassSpecLoc(),
13482            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13483                                      : diag::warn_deprecated_register)
13484         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13485     }
13486   } else if (getLangOpts().CPlusPlus &&
13487              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13488     SC = SC_Auto;
13489   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13490     Diag(DS.getStorageClassSpecLoc(),
13491          diag::err_invalid_storage_class_in_func_decl);
13492     D.getMutableDeclSpec().ClearStorageClassSpecs();
13493   }
13494 
13495   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13496     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13497       << DeclSpec::getSpecifierName(TSCS);
13498   if (DS.isInlineSpecified())
13499     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13500         << getLangOpts().CPlusPlus17;
13501   if (DS.hasConstexprSpecifier())
13502     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13503         << 0 << D.getDeclSpec().getConstexprSpecifier();
13504 
13505   DiagnoseFunctionSpecifiers(DS);
13506 
13507   CheckFunctionOrTemplateParamDeclarator(S, D);
13508 
13509   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13510   QualType parmDeclType = TInfo->getType();
13511 
13512   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13513   IdentifierInfo *II = D.getIdentifier();
13514   if (II) {
13515     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13516                    ForVisibleRedeclaration);
13517     LookupName(R, S);
13518     if (R.isSingleResult()) {
13519       NamedDecl *PrevDecl = R.getFoundDecl();
13520       if (PrevDecl->isTemplateParameter()) {
13521         // Maybe we will complain about the shadowed template parameter.
13522         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13523         // Just pretend that we didn't see the previous declaration.
13524         PrevDecl = nullptr;
13525       } else if (S->isDeclScope(PrevDecl)) {
13526         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13527         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13528 
13529         // Recover by removing the name
13530         II = nullptr;
13531         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13532         D.setInvalidType(true);
13533       }
13534     }
13535   }
13536 
13537   // Temporarily put parameter variables in the translation unit, not
13538   // the enclosing context.  This prevents them from accidentally
13539   // looking like class members in C++.
13540   ParmVarDecl *New =
13541       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13542                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13543 
13544   if (D.isInvalidType())
13545     New->setInvalidDecl();
13546 
13547   assert(S->isFunctionPrototypeScope());
13548   assert(S->getFunctionPrototypeDepth() >= 1);
13549   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13550                     S->getNextFunctionPrototypeIndex());
13551 
13552   // Add the parameter declaration into this scope.
13553   S->AddDecl(New);
13554   if (II)
13555     IdResolver.AddDecl(New);
13556 
13557   ProcessDeclAttributes(S, New, D);
13558 
13559   if (D.getDeclSpec().isModulePrivateSpecified())
13560     Diag(New->getLocation(), diag::err_module_private_local)
13561         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13562         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13563 
13564   if (New->hasAttr<BlocksAttr>()) {
13565     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13566   }
13567 
13568   if (getLangOpts().OpenCL)
13569     deduceOpenCLAddressSpace(New);
13570 
13571   return New;
13572 }
13573 
13574 /// Synthesizes a variable for a parameter arising from a
13575 /// typedef.
13576 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13577                                               SourceLocation Loc,
13578                                               QualType T) {
13579   /* FIXME: setting StartLoc == Loc.
13580      Would it be worth to modify callers so as to provide proper source
13581      location for the unnamed parameters, embedding the parameter's type? */
13582   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13583                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13584                                            SC_None, nullptr);
13585   Param->setImplicit();
13586   return Param;
13587 }
13588 
13589 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13590   // Don't diagnose unused-parameter errors in template instantiations; we
13591   // will already have done so in the template itself.
13592   if (inTemplateInstantiation())
13593     return;
13594 
13595   for (const ParmVarDecl *Parameter : Parameters) {
13596     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13597         !Parameter->hasAttr<UnusedAttr>()) {
13598       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13599         << Parameter->getDeclName();
13600     }
13601   }
13602 }
13603 
13604 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13605     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13606   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13607     return;
13608 
13609   // Warn if the return value is pass-by-value and larger than the specified
13610   // threshold.
13611   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13612     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13613     if (Size > LangOpts.NumLargeByValueCopy)
13614       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13615   }
13616 
13617   // Warn if any parameter is pass-by-value and larger than the specified
13618   // threshold.
13619   for (const ParmVarDecl *Parameter : Parameters) {
13620     QualType T = Parameter->getType();
13621     if (T->isDependentType() || !T.isPODType(Context))
13622       continue;
13623     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13624     if (Size > LangOpts.NumLargeByValueCopy)
13625       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13626           << Parameter << Size;
13627   }
13628 }
13629 
13630 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13631                                   SourceLocation NameLoc, IdentifierInfo *Name,
13632                                   QualType T, TypeSourceInfo *TSInfo,
13633                                   StorageClass SC) {
13634   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13635   if (getLangOpts().ObjCAutoRefCount &&
13636       T.getObjCLifetime() == Qualifiers::OCL_None &&
13637       T->isObjCLifetimeType()) {
13638 
13639     Qualifiers::ObjCLifetime lifetime;
13640 
13641     // Special cases for arrays:
13642     //   - if it's const, use __unsafe_unretained
13643     //   - otherwise, it's an error
13644     if (T->isArrayType()) {
13645       if (!T.isConstQualified()) {
13646         if (DelayedDiagnostics.shouldDelayDiagnostics())
13647           DelayedDiagnostics.add(
13648               sema::DelayedDiagnostic::makeForbiddenType(
13649               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13650         else
13651           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13652               << TSInfo->getTypeLoc().getSourceRange();
13653       }
13654       lifetime = Qualifiers::OCL_ExplicitNone;
13655     } else {
13656       lifetime = T->getObjCARCImplicitLifetime();
13657     }
13658     T = Context.getLifetimeQualifiedType(T, lifetime);
13659   }
13660 
13661   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13662                                          Context.getAdjustedParameterType(T),
13663                                          TSInfo, SC, nullptr);
13664 
13665   // Make a note if we created a new pack in the scope of a lambda, so that
13666   // we know that references to that pack must also be expanded within the
13667   // lambda scope.
13668   if (New->isParameterPack())
13669     if (auto *LSI = getEnclosingLambda())
13670       LSI->LocalPacks.push_back(New);
13671 
13672   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13673       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13674     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13675                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13676 
13677   // Parameters can not be abstract class types.
13678   // For record types, this is done by the AbstractClassUsageDiagnoser once
13679   // the class has been completely parsed.
13680   if (!CurContext->isRecord() &&
13681       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13682                              AbstractParamType))
13683     New->setInvalidDecl();
13684 
13685   // Parameter declarators cannot be interface types. All ObjC objects are
13686   // passed by reference.
13687   if (T->isObjCObjectType()) {
13688     SourceLocation TypeEndLoc =
13689         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13690     Diag(NameLoc,
13691          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13692       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13693     T = Context.getObjCObjectPointerType(T);
13694     New->setType(T);
13695   }
13696 
13697   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13698   // duration shall not be qualified by an address-space qualifier."
13699   // Since all parameters have automatic store duration, they can not have
13700   // an address space.
13701   if (T.getAddressSpace() != LangAS::Default &&
13702       // OpenCL allows function arguments declared to be an array of a type
13703       // to be qualified with an address space.
13704       !(getLangOpts().OpenCL &&
13705         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13706     Diag(NameLoc, diag::err_arg_with_address_space);
13707     New->setInvalidDecl();
13708   }
13709 
13710   return New;
13711 }
13712 
13713 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13714                                            SourceLocation LocAfterDecls) {
13715   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13716 
13717   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13718   // for a K&R function.
13719   if (!FTI.hasPrototype) {
13720     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13721       --i;
13722       if (FTI.Params[i].Param == nullptr) {
13723         SmallString<256> Code;
13724         llvm::raw_svector_ostream(Code)
13725             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13726         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13727             << FTI.Params[i].Ident
13728             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13729 
13730         // Implicitly declare the argument as type 'int' for lack of a better
13731         // type.
13732         AttributeFactory attrs;
13733         DeclSpec DS(attrs);
13734         const char* PrevSpec; // unused
13735         unsigned DiagID; // unused
13736         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13737                            DiagID, Context.getPrintingPolicy());
13738         // Use the identifier location for the type source range.
13739         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13740         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13741         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13742         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13743         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13744       }
13745     }
13746   }
13747 }
13748 
13749 Decl *
13750 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13751                               MultiTemplateParamsArg TemplateParameterLists,
13752                               SkipBodyInfo *SkipBody) {
13753   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13754   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13755   Scope *ParentScope = FnBodyScope->getParent();
13756 
13757   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13758   // we define a non-templated function definition, we will create a declaration
13759   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13760   // The base function declaration will have the equivalent of an `omp declare
13761   // variant` annotation which specifies the mangled definition as a
13762   // specialization function under the OpenMP context defined as part of the
13763   // `omp begin declare variant`.
13764   SmallVector<FunctionDecl *, 4> Bases;
13765   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13766     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13767         ParentScope, D, TemplateParameterLists, Bases);
13768 
13769   D.setFunctionDefinitionKind(FDK_Definition);
13770   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13771   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13772 
13773   if (!Bases.empty())
13774     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13775 
13776   return Dcl;
13777 }
13778 
13779 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13780   Consumer.HandleInlineFunctionDefinition(D);
13781 }
13782 
13783 static bool
13784 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13785                                 const FunctionDecl *&PossiblePrototype) {
13786   // Don't warn about invalid declarations.
13787   if (FD->isInvalidDecl())
13788     return false;
13789 
13790   // Or declarations that aren't global.
13791   if (!FD->isGlobal())
13792     return false;
13793 
13794   // Don't warn about C++ member functions.
13795   if (isa<CXXMethodDecl>(FD))
13796     return false;
13797 
13798   // Don't warn about 'main'.
13799   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13800     if (IdentifierInfo *II = FD->getIdentifier())
13801       if (II->isStr("main"))
13802         return false;
13803 
13804   // Don't warn about inline functions.
13805   if (FD->isInlined())
13806     return false;
13807 
13808   // Don't warn about function templates.
13809   if (FD->getDescribedFunctionTemplate())
13810     return false;
13811 
13812   // Don't warn about function template specializations.
13813   if (FD->isFunctionTemplateSpecialization())
13814     return false;
13815 
13816   // Don't warn for OpenCL kernels.
13817   if (FD->hasAttr<OpenCLKernelAttr>())
13818     return false;
13819 
13820   // Don't warn on explicitly deleted functions.
13821   if (FD->isDeleted())
13822     return false;
13823 
13824   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13825        Prev; Prev = Prev->getPreviousDecl()) {
13826     // Ignore any declarations that occur in function or method
13827     // scope, because they aren't visible from the header.
13828     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13829       continue;
13830 
13831     PossiblePrototype = Prev;
13832     return Prev->getType()->isFunctionNoProtoType();
13833   }
13834 
13835   return true;
13836 }
13837 
13838 void
13839 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13840                                    const FunctionDecl *EffectiveDefinition,
13841                                    SkipBodyInfo *SkipBody) {
13842   const FunctionDecl *Definition = EffectiveDefinition;
13843   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13844     // If this is a friend function defined in a class template, it does not
13845     // have a body until it is used, nevertheless it is a definition, see
13846     // [temp.inst]p2:
13847     //
13848     // ... for the purpose of determining whether an instantiated redeclaration
13849     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13850     // corresponds to a definition in the template is considered to be a
13851     // definition.
13852     //
13853     // The following code must produce redefinition error:
13854     //
13855     //     template<typename T> struct C20 { friend void func_20() {} };
13856     //     C20<int> c20i;
13857     //     void func_20() {}
13858     //
13859     for (auto I : FD->redecls()) {
13860       if (I != FD && !I->isInvalidDecl() &&
13861           I->getFriendObjectKind() != Decl::FOK_None) {
13862         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13863           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13864             // A merged copy of the same function, instantiated as a member of
13865             // the same class, is OK.
13866             if (declaresSameEntity(OrigFD, Original) &&
13867                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13868                                    cast<Decl>(FD->getLexicalDeclContext())))
13869               continue;
13870           }
13871 
13872           if (Original->isThisDeclarationADefinition()) {
13873             Definition = I;
13874             break;
13875           }
13876         }
13877       }
13878     }
13879   }
13880 
13881   if (!Definition)
13882     // Similar to friend functions a friend function template may be a
13883     // definition and do not have a body if it is instantiated in a class
13884     // template.
13885     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13886       for (auto I : FTD->redecls()) {
13887         auto D = cast<FunctionTemplateDecl>(I);
13888         if (D != FTD) {
13889           assert(!D->isThisDeclarationADefinition() &&
13890                  "More than one definition in redeclaration chain");
13891           if (D->getFriendObjectKind() != Decl::FOK_None)
13892             if (FunctionTemplateDecl *FT =
13893                                        D->getInstantiatedFromMemberTemplate()) {
13894               if (FT->isThisDeclarationADefinition()) {
13895                 Definition = D->getTemplatedDecl();
13896                 break;
13897               }
13898             }
13899         }
13900       }
13901     }
13902 
13903   if (!Definition)
13904     return;
13905 
13906   if (canRedefineFunction(Definition, getLangOpts()))
13907     return;
13908 
13909   // Don't emit an error when this is redefinition of a typo-corrected
13910   // definition.
13911   if (TypoCorrectedFunctionDefinitions.count(Definition))
13912     return;
13913 
13914   // If we don't have a visible definition of the function, and it's inline or
13915   // a template, skip the new definition.
13916   if (SkipBody && !hasVisibleDefinition(Definition) &&
13917       (Definition->getFormalLinkage() == InternalLinkage ||
13918        Definition->isInlined() ||
13919        Definition->getDescribedFunctionTemplate() ||
13920        Definition->getNumTemplateParameterLists())) {
13921     SkipBody->ShouldSkip = true;
13922     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13923     if (auto *TD = Definition->getDescribedFunctionTemplate())
13924       makeMergedDefinitionVisible(TD);
13925     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13926     return;
13927   }
13928 
13929   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13930       Definition->getStorageClass() == SC_Extern)
13931     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13932         << FD << getLangOpts().CPlusPlus;
13933   else
13934     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13935 
13936   Diag(Definition->getLocation(), diag::note_previous_definition);
13937   FD->setInvalidDecl();
13938 }
13939 
13940 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13941                                    Sema &S) {
13942   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13943 
13944   LambdaScopeInfo *LSI = S.PushLambdaScope();
13945   LSI->CallOperator = CallOperator;
13946   LSI->Lambda = LambdaClass;
13947   LSI->ReturnType = CallOperator->getReturnType();
13948   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13949 
13950   if (LCD == LCD_None)
13951     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13952   else if (LCD == LCD_ByCopy)
13953     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13954   else if (LCD == LCD_ByRef)
13955     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13956   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13957 
13958   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13959   LSI->Mutable = !CallOperator->isConst();
13960 
13961   // Add the captures to the LSI so they can be noted as already
13962   // captured within tryCaptureVar.
13963   auto I = LambdaClass->field_begin();
13964   for (const auto &C : LambdaClass->captures()) {
13965     if (C.capturesVariable()) {
13966       VarDecl *VD = C.getCapturedVar();
13967       if (VD->isInitCapture())
13968         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13969       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13970       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13971           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13972           /*EllipsisLoc*/C.isPackExpansion()
13973                          ? C.getEllipsisLoc() : SourceLocation(),
13974           I->getType(), /*Invalid*/false);
13975 
13976     } else if (C.capturesThis()) {
13977       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13978                           C.getCaptureKind() == LCK_StarThis);
13979     } else {
13980       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13981                              I->getType());
13982     }
13983     ++I;
13984   }
13985 }
13986 
13987 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13988                                     SkipBodyInfo *SkipBody) {
13989   if (!D) {
13990     // Parsing the function declaration failed in some way. Push on a fake scope
13991     // anyway so we can try to parse the function body.
13992     PushFunctionScope();
13993     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13994     return D;
13995   }
13996 
13997   FunctionDecl *FD = nullptr;
13998 
13999   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14000     FD = FunTmpl->getTemplatedDecl();
14001   else
14002     FD = cast<FunctionDecl>(D);
14003 
14004   // Do not push if it is a lambda because one is already pushed when building
14005   // the lambda in ActOnStartOfLambdaDefinition().
14006   if (!isLambdaCallOperator(FD))
14007     PushExpressionEvaluationContext(
14008         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14009                           : ExprEvalContexts.back().Context);
14010 
14011   // Check for defining attributes before the check for redefinition.
14012   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14013     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14014     FD->dropAttr<AliasAttr>();
14015     FD->setInvalidDecl();
14016   }
14017   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14018     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14019     FD->dropAttr<IFuncAttr>();
14020     FD->setInvalidDecl();
14021   }
14022 
14023   // See if this is a redefinition. If 'will have body' is already set, then
14024   // these checks were already performed when it was set.
14025   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
14026     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14027 
14028     // If we're skipping the body, we're done. Don't enter the scope.
14029     if (SkipBody && SkipBody->ShouldSkip)
14030       return D;
14031   }
14032 
14033   // Mark this function as "will have a body eventually".  This lets users to
14034   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14035   // this function.
14036   FD->setWillHaveBody();
14037 
14038   // If we are instantiating a generic lambda call operator, push
14039   // a LambdaScopeInfo onto the function stack.  But use the information
14040   // that's already been calculated (ActOnLambdaExpr) to prime the current
14041   // LambdaScopeInfo.
14042   // When the template operator is being specialized, the LambdaScopeInfo,
14043   // has to be properly restored so that tryCaptureVariable doesn't try
14044   // and capture any new variables. In addition when calculating potential
14045   // captures during transformation of nested lambdas, it is necessary to
14046   // have the LSI properly restored.
14047   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14048     assert(inTemplateInstantiation() &&
14049            "There should be an active template instantiation on the stack "
14050            "when instantiating a generic lambda!");
14051     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14052   } else {
14053     // Enter a new function scope
14054     PushFunctionScope();
14055   }
14056 
14057   // Builtin functions cannot be defined.
14058   if (unsigned BuiltinID = FD->getBuiltinID()) {
14059     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14060         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14061       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14062       FD->setInvalidDecl();
14063     }
14064   }
14065 
14066   // The return type of a function definition must be complete
14067   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14068   QualType ResultType = FD->getReturnType();
14069   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14070       !FD->isInvalidDecl() &&
14071       RequireCompleteType(FD->getLocation(), ResultType,
14072                           diag::err_func_def_incomplete_result))
14073     FD->setInvalidDecl();
14074 
14075   if (FnBodyScope)
14076     PushDeclContext(FnBodyScope, FD);
14077 
14078   // Check the validity of our function parameters
14079   CheckParmsForFunctionDef(FD->parameters(),
14080                            /*CheckParameterNames=*/true);
14081 
14082   // Add non-parameter declarations already in the function to the current
14083   // scope.
14084   if (FnBodyScope) {
14085     for (Decl *NPD : FD->decls()) {
14086       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14087       if (!NonParmDecl)
14088         continue;
14089       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14090              "parameters should not be in newly created FD yet");
14091 
14092       // If the decl has a name, make it accessible in the current scope.
14093       if (NonParmDecl->getDeclName())
14094         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14095 
14096       // Similarly, dive into enums and fish their constants out, making them
14097       // accessible in this scope.
14098       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14099         for (auto *EI : ED->enumerators())
14100           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14101       }
14102     }
14103   }
14104 
14105   // Introduce our parameters into the function scope
14106   for (auto Param : FD->parameters()) {
14107     Param->setOwningFunction(FD);
14108 
14109     // If this has an identifier, add it to the scope stack.
14110     if (Param->getIdentifier() && FnBodyScope) {
14111       CheckShadow(FnBodyScope, Param);
14112 
14113       PushOnScopeChains(Param, FnBodyScope);
14114     }
14115   }
14116 
14117   // Ensure that the function's exception specification is instantiated.
14118   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14119     ResolveExceptionSpec(D->getLocation(), FPT);
14120 
14121   // dllimport cannot be applied to non-inline function definitions.
14122   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14123       !FD->isTemplateInstantiation()) {
14124     assert(!FD->hasAttr<DLLExportAttr>());
14125     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14126     FD->setInvalidDecl();
14127     return D;
14128   }
14129   // We want to attach documentation to original Decl (which might be
14130   // a function template).
14131   ActOnDocumentableDecl(D);
14132   if (getCurLexicalContext()->isObjCContainer() &&
14133       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14134       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14135     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14136 
14137   return D;
14138 }
14139 
14140 /// Given the set of return statements within a function body,
14141 /// compute the variables that are subject to the named return value
14142 /// optimization.
14143 ///
14144 /// Each of the variables that is subject to the named return value
14145 /// optimization will be marked as NRVO variables in the AST, and any
14146 /// return statement that has a marked NRVO variable as its NRVO candidate can
14147 /// use the named return value optimization.
14148 ///
14149 /// This function applies a very simplistic algorithm for NRVO: if every return
14150 /// statement in the scope of a variable has the same NRVO candidate, that
14151 /// candidate is an NRVO variable.
14152 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14153   ReturnStmt **Returns = Scope->Returns.data();
14154 
14155   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14156     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14157       if (!NRVOCandidate->isNRVOVariable())
14158         Returns[I]->setNRVOCandidate(nullptr);
14159     }
14160   }
14161 }
14162 
14163 bool Sema::canDelayFunctionBody(const Declarator &D) {
14164   // We can't delay parsing the body of a constexpr function template (yet).
14165   if (D.getDeclSpec().hasConstexprSpecifier())
14166     return false;
14167 
14168   // We can't delay parsing the body of a function template with a deduced
14169   // return type (yet).
14170   if (D.getDeclSpec().hasAutoTypeSpec()) {
14171     // If the placeholder introduces a non-deduced trailing return type,
14172     // we can still delay parsing it.
14173     if (D.getNumTypeObjects()) {
14174       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14175       if (Outer.Kind == DeclaratorChunk::Function &&
14176           Outer.Fun.hasTrailingReturnType()) {
14177         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14178         return Ty.isNull() || !Ty->isUndeducedType();
14179       }
14180     }
14181     return false;
14182   }
14183 
14184   return true;
14185 }
14186 
14187 bool Sema::canSkipFunctionBody(Decl *D) {
14188   // We cannot skip the body of a function (or function template) which is
14189   // constexpr, since we may need to evaluate its body in order to parse the
14190   // rest of the file.
14191   // We cannot skip the body of a function with an undeduced return type,
14192   // because any callers of that function need to know the type.
14193   if (const FunctionDecl *FD = D->getAsFunction()) {
14194     if (FD->isConstexpr())
14195       return false;
14196     // We can't simply call Type::isUndeducedType here, because inside template
14197     // auto can be deduced to a dependent type, which is not considered
14198     // "undeduced".
14199     if (FD->getReturnType()->getContainedDeducedType())
14200       return false;
14201   }
14202   return Consumer.shouldSkipFunctionBody(D);
14203 }
14204 
14205 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14206   if (!Decl)
14207     return nullptr;
14208   if (FunctionDecl *FD = Decl->getAsFunction())
14209     FD->setHasSkippedBody();
14210   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14211     MD->setHasSkippedBody();
14212   return Decl;
14213 }
14214 
14215 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14216   return ActOnFinishFunctionBody(D, BodyArg, false);
14217 }
14218 
14219 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14220 /// body.
14221 class ExitFunctionBodyRAII {
14222 public:
14223   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14224   ~ExitFunctionBodyRAII() {
14225     if (!IsLambda)
14226       S.PopExpressionEvaluationContext();
14227   }
14228 
14229 private:
14230   Sema &S;
14231   bool IsLambda = false;
14232 };
14233 
14234 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14235   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14236 
14237   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14238     if (EscapeInfo.count(BD))
14239       return EscapeInfo[BD];
14240 
14241     bool R = false;
14242     const BlockDecl *CurBD = BD;
14243 
14244     do {
14245       R = !CurBD->doesNotEscape();
14246       if (R)
14247         break;
14248       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14249     } while (CurBD);
14250 
14251     return EscapeInfo[BD] = R;
14252   };
14253 
14254   // If the location where 'self' is implicitly retained is inside a escaping
14255   // block, emit a diagnostic.
14256   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14257        S.ImplicitlyRetainedSelfLocs)
14258     if (IsOrNestedInEscapingBlock(P.second))
14259       S.Diag(P.first, diag::warn_implicitly_retains_self)
14260           << FixItHint::CreateInsertion(P.first, "self->");
14261 }
14262 
14263 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14264                                     bool IsInstantiation) {
14265   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14266 
14267   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14268   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14269 
14270   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14271     CheckCompletedCoroutineBody(FD, Body);
14272 
14273   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14274   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14275   // meant to pop the context added in ActOnStartOfFunctionDef().
14276   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14277 
14278   if (FD) {
14279     FD->setBody(Body);
14280     FD->setWillHaveBody(false);
14281 
14282     if (getLangOpts().CPlusPlus14) {
14283       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14284           FD->getReturnType()->isUndeducedType()) {
14285         // If the function has a deduced result type but contains no 'return'
14286         // statements, the result type as written must be exactly 'auto', and
14287         // the deduced result type is 'void'.
14288         if (!FD->getReturnType()->getAs<AutoType>()) {
14289           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14290               << FD->getReturnType();
14291           FD->setInvalidDecl();
14292         } else {
14293           // Substitute 'void' for the 'auto' in the type.
14294           TypeLoc ResultType = getReturnTypeLoc(FD);
14295           Context.adjustDeducedFunctionResultType(
14296               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14297         }
14298       }
14299     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14300       // In C++11, we don't use 'auto' deduction rules for lambda call
14301       // operators because we don't support return type deduction.
14302       auto *LSI = getCurLambda();
14303       if (LSI->HasImplicitReturnType) {
14304         deduceClosureReturnType(*LSI);
14305 
14306         // C++11 [expr.prim.lambda]p4:
14307         //   [...] if there are no return statements in the compound-statement
14308         //   [the deduced type is] the type void
14309         QualType RetType =
14310             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14311 
14312         // Update the return type to the deduced type.
14313         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14314         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14315                                             Proto->getExtProtoInfo()));
14316       }
14317     }
14318 
14319     // If the function implicitly returns zero (like 'main') or is naked,
14320     // don't complain about missing return statements.
14321     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14322       WP.disableCheckFallThrough();
14323 
14324     // MSVC permits the use of pure specifier (=0) on function definition,
14325     // defined at class scope, warn about this non-standard construct.
14326     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14327       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14328 
14329     if (!FD->isInvalidDecl()) {
14330       // Don't diagnose unused parameters of defaulted or deleted functions.
14331       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14332         DiagnoseUnusedParameters(FD->parameters());
14333       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14334                                              FD->getReturnType(), FD);
14335 
14336       // If this is a structor, we need a vtable.
14337       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14338         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14339       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14340         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14341 
14342       // Try to apply the named return value optimization. We have to check
14343       // if we can do this here because lambdas keep return statements around
14344       // to deduce an implicit return type.
14345       if (FD->getReturnType()->isRecordType() &&
14346           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14347         computeNRVO(Body, getCurFunction());
14348     }
14349 
14350     // GNU warning -Wmissing-prototypes:
14351     //   Warn if a global function is defined without a previous
14352     //   prototype declaration. This warning is issued even if the
14353     //   definition itself provides a prototype. The aim is to detect
14354     //   global functions that fail to be declared in header files.
14355     const FunctionDecl *PossiblePrototype = nullptr;
14356     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14357       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14358 
14359       if (PossiblePrototype) {
14360         // We found a declaration that is not a prototype,
14361         // but that could be a zero-parameter prototype
14362         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14363           TypeLoc TL = TI->getTypeLoc();
14364           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14365             Diag(PossiblePrototype->getLocation(),
14366                  diag::note_declaration_not_a_prototype)
14367                 << (FD->getNumParams() != 0)
14368                 << (FD->getNumParams() == 0
14369                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14370                         : FixItHint{});
14371         }
14372       } else {
14373         // Returns true if the token beginning at this Loc is `const`.
14374         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14375                                 const LangOptions &LangOpts) {
14376           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14377           if (LocInfo.first.isInvalid())
14378             return false;
14379 
14380           bool Invalid = false;
14381           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14382           if (Invalid)
14383             return false;
14384 
14385           if (LocInfo.second > Buffer.size())
14386             return false;
14387 
14388           const char *LexStart = Buffer.data() + LocInfo.second;
14389           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14390 
14391           return StartTok.consume_front("const") &&
14392                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14393                   StartTok.startswith("/*") || StartTok.startswith("//"));
14394         };
14395 
14396         auto findBeginLoc = [&]() {
14397           // If the return type has `const` qualifier, we want to insert
14398           // `static` before `const` (and not before the typename).
14399           if ((FD->getReturnType()->isAnyPointerType() &&
14400                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14401               FD->getReturnType().isConstQualified()) {
14402             // But only do this if we can determine where the `const` is.
14403 
14404             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14405                              getLangOpts()))
14406 
14407               return FD->getBeginLoc();
14408           }
14409           return FD->getTypeSpecStartLoc();
14410         };
14411         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14412             << /* function */ 1
14413             << (FD->getStorageClass() == SC_None
14414                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14415                     : FixItHint{});
14416       }
14417 
14418       // GNU warning -Wstrict-prototypes
14419       //   Warn if K&R function is defined without a previous declaration.
14420       //   This warning is issued only if the definition itself does not provide
14421       //   a prototype. Only K&R definitions do not provide a prototype.
14422       if (!FD->hasWrittenPrototype()) {
14423         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14424         TypeLoc TL = TI->getTypeLoc();
14425         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14426         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14427       }
14428     }
14429 
14430     // Warn on CPUDispatch with an actual body.
14431     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14432       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14433         if (!CmpndBody->body_empty())
14434           Diag(CmpndBody->body_front()->getBeginLoc(),
14435                diag::warn_dispatch_body_ignored);
14436 
14437     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14438       const CXXMethodDecl *KeyFunction;
14439       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14440           MD->isVirtual() &&
14441           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14442           MD == KeyFunction->getCanonicalDecl()) {
14443         // Update the key-function state if necessary for this ABI.
14444         if (FD->isInlined() &&
14445             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14446           Context.setNonKeyFunction(MD);
14447 
14448           // If the newly-chosen key function is already defined, then we
14449           // need to mark the vtable as used retroactively.
14450           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14451           const FunctionDecl *Definition;
14452           if (KeyFunction && KeyFunction->isDefined(Definition))
14453             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14454         } else {
14455           // We just defined they key function; mark the vtable as used.
14456           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14457         }
14458       }
14459     }
14460 
14461     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14462            "Function parsing confused");
14463   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14464     assert(MD == getCurMethodDecl() && "Method parsing confused");
14465     MD->setBody(Body);
14466     if (!MD->isInvalidDecl()) {
14467       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14468                                              MD->getReturnType(), MD);
14469 
14470       if (Body)
14471         computeNRVO(Body, getCurFunction());
14472     }
14473     if (getCurFunction()->ObjCShouldCallSuper) {
14474       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14475           << MD->getSelector().getAsString();
14476       getCurFunction()->ObjCShouldCallSuper = false;
14477     }
14478     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14479       const ObjCMethodDecl *InitMethod = nullptr;
14480       bool isDesignated =
14481           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14482       assert(isDesignated && InitMethod);
14483       (void)isDesignated;
14484 
14485       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14486         auto IFace = MD->getClassInterface();
14487         if (!IFace)
14488           return false;
14489         auto SuperD = IFace->getSuperClass();
14490         if (!SuperD)
14491           return false;
14492         return SuperD->getIdentifier() ==
14493             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14494       };
14495       // Don't issue this warning for unavailable inits or direct subclasses
14496       // of NSObject.
14497       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14498         Diag(MD->getLocation(),
14499              diag::warn_objc_designated_init_missing_super_call);
14500         Diag(InitMethod->getLocation(),
14501              diag::note_objc_designated_init_marked_here);
14502       }
14503       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14504     }
14505     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14506       // Don't issue this warning for unavaialable inits.
14507       if (!MD->isUnavailable())
14508         Diag(MD->getLocation(),
14509              diag::warn_objc_secondary_init_missing_init_call);
14510       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14511     }
14512 
14513     diagnoseImplicitlyRetainedSelf(*this);
14514   } else {
14515     // Parsing the function declaration failed in some way. Pop the fake scope
14516     // we pushed on.
14517     PopFunctionScopeInfo(ActivePolicy, dcl);
14518     return nullptr;
14519   }
14520 
14521   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14522     DiagnoseUnguardedAvailabilityViolations(dcl);
14523 
14524   assert(!getCurFunction()->ObjCShouldCallSuper &&
14525          "This should only be set for ObjC methods, which should have been "
14526          "handled in the block above.");
14527 
14528   // Verify and clean out per-function state.
14529   if (Body && (!FD || !FD->isDefaulted())) {
14530     // C++ constructors that have function-try-blocks can't have return
14531     // statements in the handlers of that block. (C++ [except.handle]p14)
14532     // Verify this.
14533     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14534       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14535 
14536     // Verify that gotos and switch cases don't jump into scopes illegally.
14537     if (getCurFunction()->NeedsScopeChecking() &&
14538         !PP.isCodeCompletionEnabled())
14539       DiagnoseInvalidJumps(Body);
14540 
14541     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14542       if (!Destructor->getParent()->isDependentType())
14543         CheckDestructor(Destructor);
14544 
14545       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14546                                              Destructor->getParent());
14547     }
14548 
14549     // If any errors have occurred, clear out any temporaries that may have
14550     // been leftover. This ensures that these temporaries won't be picked up for
14551     // deletion in some later function.
14552     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14553         getDiagnostics().getSuppressAllDiagnostics()) {
14554       DiscardCleanupsInEvaluationContext();
14555     }
14556     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14557         !isa<FunctionTemplateDecl>(dcl)) {
14558       // Since the body is valid, issue any analysis-based warnings that are
14559       // enabled.
14560       ActivePolicy = &WP;
14561     }
14562 
14563     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14564         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14565       FD->setInvalidDecl();
14566 
14567     if (FD && FD->hasAttr<NakedAttr>()) {
14568       for (const Stmt *S : Body->children()) {
14569         // Allow local register variables without initializer as they don't
14570         // require prologue.
14571         bool RegisterVariables = false;
14572         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14573           for (const auto *Decl : DS->decls()) {
14574             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14575               RegisterVariables =
14576                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14577               if (!RegisterVariables)
14578                 break;
14579             }
14580           }
14581         }
14582         if (RegisterVariables)
14583           continue;
14584         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14585           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14586           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14587           FD->setInvalidDecl();
14588           break;
14589         }
14590       }
14591     }
14592 
14593     assert(ExprCleanupObjects.size() ==
14594                ExprEvalContexts.back().NumCleanupObjects &&
14595            "Leftover temporaries in function");
14596     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14597     assert(MaybeODRUseExprs.empty() &&
14598            "Leftover expressions for odr-use checking");
14599   }
14600 
14601   if (!IsInstantiation)
14602     PopDeclContext();
14603 
14604   PopFunctionScopeInfo(ActivePolicy, dcl);
14605   // If any errors have occurred, clear out any temporaries that may have
14606   // been leftover. This ensures that these temporaries won't be picked up for
14607   // deletion in some later function.
14608   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14609     DiscardCleanupsInEvaluationContext();
14610   }
14611 
14612   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14613     auto ES = getEmissionStatus(FD);
14614     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14615         ES == Sema::FunctionEmissionStatus::Unknown)
14616       DeclsToCheckForDeferredDiags.push_back(FD);
14617   }
14618 
14619   return dcl;
14620 }
14621 
14622 /// When we finish delayed parsing of an attribute, we must attach it to the
14623 /// relevant Decl.
14624 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14625                                        ParsedAttributes &Attrs) {
14626   // Always attach attributes to the underlying decl.
14627   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14628     D = TD->getTemplatedDecl();
14629   ProcessDeclAttributeList(S, D, Attrs);
14630 
14631   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14632     if (Method->isStatic())
14633       checkThisInStaticMemberFunctionAttributes(Method);
14634 }
14635 
14636 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14637 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14638 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14639                                           IdentifierInfo &II, Scope *S) {
14640   // Find the scope in which the identifier is injected and the corresponding
14641   // DeclContext.
14642   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14643   // In that case, we inject the declaration into the translation unit scope
14644   // instead.
14645   Scope *BlockScope = S;
14646   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14647     BlockScope = BlockScope->getParent();
14648 
14649   Scope *ContextScope = BlockScope;
14650   while (!ContextScope->getEntity())
14651     ContextScope = ContextScope->getParent();
14652   ContextRAII SavedContext(*this, ContextScope->getEntity());
14653 
14654   // Before we produce a declaration for an implicitly defined
14655   // function, see whether there was a locally-scoped declaration of
14656   // this name as a function or variable. If so, use that
14657   // (non-visible) declaration, and complain about it.
14658   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14659   if (ExternCPrev) {
14660     // We still need to inject the function into the enclosing block scope so
14661     // that later (non-call) uses can see it.
14662     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14663 
14664     // C89 footnote 38:
14665     //   If in fact it is not defined as having type "function returning int",
14666     //   the behavior is undefined.
14667     if (!isa<FunctionDecl>(ExternCPrev) ||
14668         !Context.typesAreCompatible(
14669             cast<FunctionDecl>(ExternCPrev)->getType(),
14670             Context.getFunctionNoProtoType(Context.IntTy))) {
14671       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14672           << ExternCPrev << !getLangOpts().C99;
14673       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14674       return ExternCPrev;
14675     }
14676   }
14677 
14678   // Extension in C99.  Legal in C90, but warn about it.
14679   unsigned diag_id;
14680   if (II.getName().startswith("__builtin_"))
14681     diag_id = diag::warn_builtin_unknown;
14682   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14683   else if (getLangOpts().OpenCL)
14684     diag_id = diag::err_opencl_implicit_function_decl;
14685   else if (getLangOpts().C99)
14686     diag_id = diag::ext_implicit_function_decl;
14687   else
14688     diag_id = diag::warn_implicit_function_decl;
14689   Diag(Loc, diag_id) << &II;
14690 
14691   // If we found a prior declaration of this function, don't bother building
14692   // another one. We've already pushed that one into scope, so there's nothing
14693   // more to do.
14694   if (ExternCPrev)
14695     return ExternCPrev;
14696 
14697   // Because typo correction is expensive, only do it if the implicit
14698   // function declaration is going to be treated as an error.
14699   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14700     TypoCorrection Corrected;
14701     DeclFilterCCC<FunctionDecl> CCC{};
14702     if (S && (Corrected =
14703                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14704                               S, nullptr, CCC, CTK_NonError)))
14705       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14706                    /*ErrorRecovery*/false);
14707   }
14708 
14709   // Set a Declarator for the implicit definition: int foo();
14710   const char *Dummy;
14711   AttributeFactory attrFactory;
14712   DeclSpec DS(attrFactory);
14713   unsigned DiagID;
14714   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14715                                   Context.getPrintingPolicy());
14716   (void)Error; // Silence warning.
14717   assert(!Error && "Error setting up implicit decl!");
14718   SourceLocation NoLoc;
14719   Declarator D(DS, DeclaratorContext::BlockContext);
14720   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14721                                              /*IsAmbiguous=*/false,
14722                                              /*LParenLoc=*/NoLoc,
14723                                              /*Params=*/nullptr,
14724                                              /*NumParams=*/0,
14725                                              /*EllipsisLoc=*/NoLoc,
14726                                              /*RParenLoc=*/NoLoc,
14727                                              /*RefQualifierIsLvalueRef=*/true,
14728                                              /*RefQualifierLoc=*/NoLoc,
14729                                              /*MutableLoc=*/NoLoc, EST_None,
14730                                              /*ESpecRange=*/SourceRange(),
14731                                              /*Exceptions=*/nullptr,
14732                                              /*ExceptionRanges=*/nullptr,
14733                                              /*NumExceptions=*/0,
14734                                              /*NoexceptExpr=*/nullptr,
14735                                              /*ExceptionSpecTokens=*/nullptr,
14736                                              /*DeclsInPrototype=*/None, Loc,
14737                                              Loc, D),
14738                 std::move(DS.getAttributes()), SourceLocation());
14739   D.SetIdentifier(&II, Loc);
14740 
14741   // Insert this function into the enclosing block scope.
14742   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14743   FD->setImplicit();
14744 
14745   AddKnownFunctionAttributes(FD);
14746 
14747   return FD;
14748 }
14749 
14750 /// If this function is a C++ replaceable global allocation function
14751 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14752 /// adds any function attributes that we know a priori based on the standard.
14753 ///
14754 /// We need to check for duplicate attributes both here and where user-written
14755 /// attributes are applied to declarations.
14756 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14757     FunctionDecl *FD) {
14758   if (FD->isInvalidDecl())
14759     return;
14760 
14761   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14762       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14763     return;
14764 
14765   Optional<unsigned> AlignmentParam;
14766   bool IsNothrow = false;
14767   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14768     return;
14769 
14770   // C++2a [basic.stc.dynamic.allocation]p4:
14771   //   An allocation function that has a non-throwing exception specification
14772   //   indicates failure by returning a null pointer value. Any other allocation
14773   //   function never returns a null pointer value and indicates failure only by
14774   //   throwing an exception [...]
14775   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14776     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14777 
14778   // C++2a [basic.stc.dynamic.allocation]p2:
14779   //   An allocation function attempts to allocate the requested amount of
14780   //   storage. [...] If the request succeeds, the value returned by a
14781   //   replaceable allocation function is a [...] pointer value p0 different
14782   //   from any previously returned value p1 [...]
14783   //
14784   // However, this particular information is being added in codegen,
14785   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14786 
14787   // C++2a [basic.stc.dynamic.allocation]p2:
14788   //   An allocation function attempts to allocate the requested amount of
14789   //   storage. If it is successful, it returns the address of the start of a
14790   //   block of storage whose length in bytes is at least as large as the
14791   //   requested size.
14792   if (!FD->hasAttr<AllocSizeAttr>()) {
14793     FD->addAttr(AllocSizeAttr::CreateImplicit(
14794         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14795         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14796   }
14797 
14798   // C++2a [basic.stc.dynamic.allocation]p3:
14799   //   For an allocation function [...], the pointer returned on a successful
14800   //   call shall represent the address of storage that is aligned as follows:
14801   //   (3.1) If the allocation function takes an argument of type
14802   //         std​::​align_­val_­t, the storage will have the alignment
14803   //         specified by the value of this argument.
14804   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14805     FD->addAttr(AllocAlignAttr::CreateImplicit(
14806         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14807   }
14808 
14809   // FIXME:
14810   // C++2a [basic.stc.dynamic.allocation]p3:
14811   //   For an allocation function [...], the pointer returned on a successful
14812   //   call shall represent the address of storage that is aligned as follows:
14813   //   (3.2) Otherwise, if the allocation function is named operator new[],
14814   //         the storage is aligned for any object that does not have
14815   //         new-extended alignment ([basic.align]) and is no larger than the
14816   //         requested size.
14817   //   (3.3) Otherwise, the storage is aligned for any object that does not
14818   //         have new-extended alignment and is of the requested size.
14819 }
14820 
14821 /// Adds any function attributes that we know a priori based on
14822 /// the declaration of this function.
14823 ///
14824 /// These attributes can apply both to implicitly-declared builtins
14825 /// (like __builtin___printf_chk) or to library-declared functions
14826 /// like NSLog or printf.
14827 ///
14828 /// We need to check for duplicate attributes both here and where user-written
14829 /// attributes are applied to declarations.
14830 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14831   if (FD->isInvalidDecl())
14832     return;
14833 
14834   // If this is a built-in function, map its builtin attributes to
14835   // actual attributes.
14836   if (unsigned BuiltinID = FD->getBuiltinID()) {
14837     // Handle printf-formatting attributes.
14838     unsigned FormatIdx;
14839     bool HasVAListArg;
14840     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14841       if (!FD->hasAttr<FormatAttr>()) {
14842         const char *fmt = "printf";
14843         unsigned int NumParams = FD->getNumParams();
14844         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14845             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14846           fmt = "NSString";
14847         FD->addAttr(FormatAttr::CreateImplicit(Context,
14848                                                &Context.Idents.get(fmt),
14849                                                FormatIdx+1,
14850                                                HasVAListArg ? 0 : FormatIdx+2,
14851                                                FD->getLocation()));
14852       }
14853     }
14854     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14855                                              HasVAListArg)) {
14856      if (!FD->hasAttr<FormatAttr>())
14857        FD->addAttr(FormatAttr::CreateImplicit(Context,
14858                                               &Context.Idents.get("scanf"),
14859                                               FormatIdx+1,
14860                                               HasVAListArg ? 0 : FormatIdx+2,
14861                                               FD->getLocation()));
14862     }
14863 
14864     // Handle automatically recognized callbacks.
14865     SmallVector<int, 4> Encoding;
14866     if (!FD->hasAttr<CallbackAttr>() &&
14867         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14868       FD->addAttr(CallbackAttr::CreateImplicit(
14869           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14870 
14871     // Mark const if we don't care about errno and that is the only thing
14872     // preventing the function from being const. This allows IRgen to use LLVM
14873     // intrinsics for such functions.
14874     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14875         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14876       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14877 
14878     // We make "fma" on some platforms const because we know it does not set
14879     // errno in those environments even though it could set errno based on the
14880     // C standard.
14881     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14882     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14883         !FD->hasAttr<ConstAttr>()) {
14884       switch (BuiltinID) {
14885       case Builtin::BI__builtin_fma:
14886       case Builtin::BI__builtin_fmaf:
14887       case Builtin::BI__builtin_fmal:
14888       case Builtin::BIfma:
14889       case Builtin::BIfmaf:
14890       case Builtin::BIfmal:
14891         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14892         break;
14893       default:
14894         break;
14895       }
14896     }
14897 
14898     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14899         !FD->hasAttr<ReturnsTwiceAttr>())
14900       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14901                                          FD->getLocation()));
14902     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14903       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14904     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14905       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14906     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14907       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14908     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14909         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14910       // Add the appropriate attribute, depending on the CUDA compilation mode
14911       // and which target the builtin belongs to. For example, during host
14912       // compilation, aux builtins are __device__, while the rest are __host__.
14913       if (getLangOpts().CUDAIsDevice !=
14914           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14915         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14916       else
14917         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14918     }
14919   }
14920 
14921   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14922 
14923   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14924   // throw, add an implicit nothrow attribute to any extern "C" function we come
14925   // across.
14926   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14927       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14928     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14929     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14930       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14931   }
14932 
14933   IdentifierInfo *Name = FD->getIdentifier();
14934   if (!Name)
14935     return;
14936   if ((!getLangOpts().CPlusPlus &&
14937        FD->getDeclContext()->isTranslationUnit()) ||
14938       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14939        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14940        LinkageSpecDecl::lang_c)) {
14941     // Okay: this could be a libc/libm/Objective-C function we know
14942     // about.
14943   } else
14944     return;
14945 
14946   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14947     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14948     // target-specific builtins, perhaps?
14949     if (!FD->hasAttr<FormatAttr>())
14950       FD->addAttr(FormatAttr::CreateImplicit(Context,
14951                                              &Context.Idents.get("printf"), 2,
14952                                              Name->isStr("vasprintf") ? 0 : 3,
14953                                              FD->getLocation()));
14954   }
14955 
14956   if (Name->isStr("__CFStringMakeConstantString")) {
14957     // We already have a __builtin___CFStringMakeConstantString,
14958     // but builds that use -fno-constant-cfstrings don't go through that.
14959     if (!FD->hasAttr<FormatArgAttr>())
14960       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14961                                                 FD->getLocation()));
14962   }
14963 }
14964 
14965 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14966                                     TypeSourceInfo *TInfo) {
14967   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14968   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14969 
14970   if (!TInfo) {
14971     assert(D.isInvalidType() && "no declarator info for valid type");
14972     TInfo = Context.getTrivialTypeSourceInfo(T);
14973   }
14974 
14975   // Scope manipulation handled by caller.
14976   TypedefDecl *NewTD =
14977       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14978                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14979 
14980   // Bail out immediately if we have an invalid declaration.
14981   if (D.isInvalidType()) {
14982     NewTD->setInvalidDecl();
14983     return NewTD;
14984   }
14985 
14986   if (D.getDeclSpec().isModulePrivateSpecified()) {
14987     if (CurContext->isFunctionOrMethod())
14988       Diag(NewTD->getLocation(), diag::err_module_private_local)
14989           << 2 << NewTD
14990           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14991           << FixItHint::CreateRemoval(
14992                  D.getDeclSpec().getModulePrivateSpecLoc());
14993     else
14994       NewTD->setModulePrivate();
14995   }
14996 
14997   // C++ [dcl.typedef]p8:
14998   //   If the typedef declaration defines an unnamed class (or
14999   //   enum), the first typedef-name declared by the declaration
15000   //   to be that class type (or enum type) is used to denote the
15001   //   class type (or enum type) for linkage purposes only.
15002   // We need to check whether the type was declared in the declaration.
15003   switch (D.getDeclSpec().getTypeSpecType()) {
15004   case TST_enum:
15005   case TST_struct:
15006   case TST_interface:
15007   case TST_union:
15008   case TST_class: {
15009     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15010     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15011     break;
15012   }
15013 
15014   default:
15015     break;
15016   }
15017 
15018   return NewTD;
15019 }
15020 
15021 /// Check that this is a valid underlying type for an enum declaration.
15022 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15023   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15024   QualType T = TI->getType();
15025 
15026   if (T->isDependentType())
15027     return false;
15028 
15029   // This doesn't use 'isIntegralType' despite the error message mentioning
15030   // integral type because isIntegralType would also allow enum types in C.
15031   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15032     if (BT->isInteger())
15033       return false;
15034 
15035   if (T->isExtIntType())
15036     return false;
15037 
15038   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15039 }
15040 
15041 /// Check whether this is a valid redeclaration of a previous enumeration.
15042 /// \return true if the redeclaration was invalid.
15043 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15044                                   QualType EnumUnderlyingTy, bool IsFixed,
15045                                   const EnumDecl *Prev) {
15046   if (IsScoped != Prev->isScoped()) {
15047     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15048       << Prev->isScoped();
15049     Diag(Prev->getLocation(), diag::note_previous_declaration);
15050     return true;
15051   }
15052 
15053   if (IsFixed && Prev->isFixed()) {
15054     if (!EnumUnderlyingTy->isDependentType() &&
15055         !Prev->getIntegerType()->isDependentType() &&
15056         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15057                                         Prev->getIntegerType())) {
15058       // TODO: Highlight the underlying type of the redeclaration.
15059       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15060         << EnumUnderlyingTy << Prev->getIntegerType();
15061       Diag(Prev->getLocation(), diag::note_previous_declaration)
15062           << Prev->getIntegerTypeRange();
15063       return true;
15064     }
15065   } else if (IsFixed != Prev->isFixed()) {
15066     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15067       << Prev->isFixed();
15068     Diag(Prev->getLocation(), diag::note_previous_declaration);
15069     return true;
15070   }
15071 
15072   return false;
15073 }
15074 
15075 /// Get diagnostic %select index for tag kind for
15076 /// redeclaration diagnostic message.
15077 /// WARNING: Indexes apply to particular diagnostics only!
15078 ///
15079 /// \returns diagnostic %select index.
15080 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15081   switch (Tag) {
15082   case TTK_Struct: return 0;
15083   case TTK_Interface: return 1;
15084   case TTK_Class:  return 2;
15085   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15086   }
15087 }
15088 
15089 /// Determine if tag kind is a class-key compatible with
15090 /// class for redeclaration (class, struct, or __interface).
15091 ///
15092 /// \returns true iff the tag kind is compatible.
15093 static bool isClassCompatTagKind(TagTypeKind Tag)
15094 {
15095   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15096 }
15097 
15098 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15099                                              TagTypeKind TTK) {
15100   if (isa<TypedefDecl>(PrevDecl))
15101     return NTK_Typedef;
15102   else if (isa<TypeAliasDecl>(PrevDecl))
15103     return NTK_TypeAlias;
15104   else if (isa<ClassTemplateDecl>(PrevDecl))
15105     return NTK_Template;
15106   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15107     return NTK_TypeAliasTemplate;
15108   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15109     return NTK_TemplateTemplateArgument;
15110   switch (TTK) {
15111   case TTK_Struct:
15112   case TTK_Interface:
15113   case TTK_Class:
15114     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15115   case TTK_Union:
15116     return NTK_NonUnion;
15117   case TTK_Enum:
15118     return NTK_NonEnum;
15119   }
15120   llvm_unreachable("invalid TTK");
15121 }
15122 
15123 /// Determine whether a tag with a given kind is acceptable
15124 /// as a redeclaration of the given tag declaration.
15125 ///
15126 /// \returns true if the new tag kind is acceptable, false otherwise.
15127 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15128                                         TagTypeKind NewTag, bool isDefinition,
15129                                         SourceLocation NewTagLoc,
15130                                         const IdentifierInfo *Name) {
15131   // C++ [dcl.type.elab]p3:
15132   //   The class-key or enum keyword present in the
15133   //   elaborated-type-specifier shall agree in kind with the
15134   //   declaration to which the name in the elaborated-type-specifier
15135   //   refers. This rule also applies to the form of
15136   //   elaborated-type-specifier that declares a class-name or
15137   //   friend class since it can be construed as referring to the
15138   //   definition of the class. Thus, in any
15139   //   elaborated-type-specifier, the enum keyword shall be used to
15140   //   refer to an enumeration (7.2), the union class-key shall be
15141   //   used to refer to a union (clause 9), and either the class or
15142   //   struct class-key shall be used to refer to a class (clause 9)
15143   //   declared using the class or struct class-key.
15144   TagTypeKind OldTag = Previous->getTagKind();
15145   if (OldTag != NewTag &&
15146       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15147     return false;
15148 
15149   // Tags are compatible, but we might still want to warn on mismatched tags.
15150   // Non-class tags can't be mismatched at this point.
15151   if (!isClassCompatTagKind(NewTag))
15152     return true;
15153 
15154   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15155   // by our warning analysis. We don't want to warn about mismatches with (eg)
15156   // declarations in system headers that are designed to be specialized, but if
15157   // a user asks us to warn, we should warn if their code contains mismatched
15158   // declarations.
15159   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15160     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15161                                       Loc);
15162   };
15163   if (IsIgnoredLoc(NewTagLoc))
15164     return true;
15165 
15166   auto IsIgnored = [&](const TagDecl *Tag) {
15167     return IsIgnoredLoc(Tag->getLocation());
15168   };
15169   while (IsIgnored(Previous)) {
15170     Previous = Previous->getPreviousDecl();
15171     if (!Previous)
15172       return true;
15173     OldTag = Previous->getTagKind();
15174   }
15175 
15176   bool isTemplate = false;
15177   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15178     isTemplate = Record->getDescribedClassTemplate();
15179 
15180   if (inTemplateInstantiation()) {
15181     if (OldTag != NewTag) {
15182       // In a template instantiation, do not offer fix-its for tag mismatches
15183       // since they usually mess up the template instead of fixing the problem.
15184       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15185         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15186         << getRedeclDiagFromTagKind(OldTag);
15187       // FIXME: Note previous location?
15188     }
15189     return true;
15190   }
15191 
15192   if (isDefinition) {
15193     // On definitions, check all previous tags and issue a fix-it for each
15194     // one that doesn't match the current tag.
15195     if (Previous->getDefinition()) {
15196       // Don't suggest fix-its for redefinitions.
15197       return true;
15198     }
15199 
15200     bool previousMismatch = false;
15201     for (const TagDecl *I : Previous->redecls()) {
15202       if (I->getTagKind() != NewTag) {
15203         // Ignore previous declarations for which the warning was disabled.
15204         if (IsIgnored(I))
15205           continue;
15206 
15207         if (!previousMismatch) {
15208           previousMismatch = true;
15209           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15210             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15211             << getRedeclDiagFromTagKind(I->getTagKind());
15212         }
15213         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15214           << getRedeclDiagFromTagKind(NewTag)
15215           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15216                TypeWithKeyword::getTagTypeKindName(NewTag));
15217       }
15218     }
15219     return true;
15220   }
15221 
15222   // Identify the prevailing tag kind: this is the kind of the definition (if
15223   // there is a non-ignored definition), or otherwise the kind of the prior
15224   // (non-ignored) declaration.
15225   const TagDecl *PrevDef = Previous->getDefinition();
15226   if (PrevDef && IsIgnored(PrevDef))
15227     PrevDef = nullptr;
15228   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15229   if (Redecl->getTagKind() != NewTag) {
15230     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15231       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15232       << getRedeclDiagFromTagKind(OldTag);
15233     Diag(Redecl->getLocation(), diag::note_previous_use);
15234 
15235     // If there is a previous definition, suggest a fix-it.
15236     if (PrevDef) {
15237       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15238         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15239         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15240              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15241     }
15242   }
15243 
15244   return true;
15245 }
15246 
15247 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15248 /// from an outer enclosing namespace or file scope inside a friend declaration.
15249 /// This should provide the commented out code in the following snippet:
15250 ///   namespace N {
15251 ///     struct X;
15252 ///     namespace M {
15253 ///       struct Y { friend struct /*N::*/ X; };
15254 ///     }
15255 ///   }
15256 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15257                                          SourceLocation NameLoc) {
15258   // While the decl is in a namespace, do repeated lookup of that name and see
15259   // if we get the same namespace back.  If we do not, continue until
15260   // translation unit scope, at which point we have a fully qualified NNS.
15261   SmallVector<IdentifierInfo *, 4> Namespaces;
15262   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15263   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15264     // This tag should be declared in a namespace, which can only be enclosed by
15265     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15266     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15267     if (!Namespace || Namespace->isAnonymousNamespace())
15268       return FixItHint();
15269     IdentifierInfo *II = Namespace->getIdentifier();
15270     Namespaces.push_back(II);
15271     NamedDecl *Lookup = SemaRef.LookupSingleName(
15272         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15273     if (Lookup == Namespace)
15274       break;
15275   }
15276 
15277   // Once we have all the namespaces, reverse them to go outermost first, and
15278   // build an NNS.
15279   SmallString<64> Insertion;
15280   llvm::raw_svector_ostream OS(Insertion);
15281   if (DC->isTranslationUnit())
15282     OS << "::";
15283   std::reverse(Namespaces.begin(), Namespaces.end());
15284   for (auto *II : Namespaces)
15285     OS << II->getName() << "::";
15286   return FixItHint::CreateInsertion(NameLoc, Insertion);
15287 }
15288 
15289 /// Determine whether a tag originally declared in context \p OldDC can
15290 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15291 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15292 /// using-declaration).
15293 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15294                                          DeclContext *NewDC) {
15295   OldDC = OldDC->getRedeclContext();
15296   NewDC = NewDC->getRedeclContext();
15297 
15298   if (OldDC->Equals(NewDC))
15299     return true;
15300 
15301   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15302   // encloses the other).
15303   if (S.getLangOpts().MSVCCompat &&
15304       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15305     return true;
15306 
15307   return false;
15308 }
15309 
15310 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15311 /// former case, Name will be non-null.  In the later case, Name will be null.
15312 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15313 /// reference/declaration/definition of a tag.
15314 ///
15315 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15316 /// trailing-type-specifier) other than one in an alias-declaration.
15317 ///
15318 /// \param SkipBody If non-null, will be set to indicate if the caller should
15319 /// skip the definition of this tag and treat it as if it were a declaration.
15320 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15321                      SourceLocation KWLoc, CXXScopeSpec &SS,
15322                      IdentifierInfo *Name, SourceLocation NameLoc,
15323                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15324                      SourceLocation ModulePrivateLoc,
15325                      MultiTemplateParamsArg TemplateParameterLists,
15326                      bool &OwnedDecl, bool &IsDependent,
15327                      SourceLocation ScopedEnumKWLoc,
15328                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15329                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15330                      SkipBodyInfo *SkipBody) {
15331   // If this is not a definition, it must have a name.
15332   IdentifierInfo *OrigName = Name;
15333   assert((Name != nullptr || TUK == TUK_Definition) &&
15334          "Nameless record must be a definition!");
15335   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15336 
15337   OwnedDecl = false;
15338   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15339   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15340 
15341   // FIXME: Check member specializations more carefully.
15342   bool isMemberSpecialization = false;
15343   bool Invalid = false;
15344 
15345   // We only need to do this matching if we have template parameters
15346   // or a scope specifier, which also conveniently avoids this work
15347   // for non-C++ cases.
15348   if (TemplateParameterLists.size() > 0 ||
15349       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15350     if (TemplateParameterList *TemplateParams =
15351             MatchTemplateParametersToScopeSpecifier(
15352                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15353                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15354       if (Kind == TTK_Enum) {
15355         Diag(KWLoc, diag::err_enum_template);
15356         return nullptr;
15357       }
15358 
15359       if (TemplateParams->size() > 0) {
15360         // This is a declaration or definition of a class template (which may
15361         // be a member of another template).
15362 
15363         if (Invalid)
15364           return nullptr;
15365 
15366         OwnedDecl = false;
15367         DeclResult Result = CheckClassTemplate(
15368             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15369             AS, ModulePrivateLoc,
15370             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15371             TemplateParameterLists.data(), SkipBody);
15372         return Result.get();
15373       } else {
15374         // The "template<>" header is extraneous.
15375         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15376           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15377         isMemberSpecialization = true;
15378       }
15379     }
15380 
15381     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15382         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15383       return nullptr;
15384   }
15385 
15386   // Figure out the underlying type if this a enum declaration. We need to do
15387   // this early, because it's needed to detect if this is an incompatible
15388   // redeclaration.
15389   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15390   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15391 
15392   if (Kind == TTK_Enum) {
15393     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15394       // No underlying type explicitly specified, or we failed to parse the
15395       // type, default to int.
15396       EnumUnderlying = Context.IntTy.getTypePtr();
15397     } else if (UnderlyingType.get()) {
15398       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15399       // integral type; any cv-qualification is ignored.
15400       TypeSourceInfo *TI = nullptr;
15401       GetTypeFromParser(UnderlyingType.get(), &TI);
15402       EnumUnderlying = TI;
15403 
15404       if (CheckEnumUnderlyingType(TI))
15405         // Recover by falling back to int.
15406         EnumUnderlying = Context.IntTy.getTypePtr();
15407 
15408       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15409                                           UPPC_FixedUnderlyingType))
15410         EnumUnderlying = Context.IntTy.getTypePtr();
15411 
15412     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15413       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15414       // of 'int'. However, if this is an unfixed forward declaration, don't set
15415       // the underlying type unless the user enables -fms-compatibility. This
15416       // makes unfixed forward declared enums incomplete and is more conforming.
15417       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15418         EnumUnderlying = Context.IntTy.getTypePtr();
15419     }
15420   }
15421 
15422   DeclContext *SearchDC = CurContext;
15423   DeclContext *DC = CurContext;
15424   bool isStdBadAlloc = false;
15425   bool isStdAlignValT = false;
15426 
15427   RedeclarationKind Redecl = forRedeclarationInCurContext();
15428   if (TUK == TUK_Friend || TUK == TUK_Reference)
15429     Redecl = NotForRedeclaration;
15430 
15431   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15432   /// implemented asks for structural equivalence checking, the returned decl
15433   /// here is passed back to the parser, allowing the tag body to be parsed.
15434   auto createTagFromNewDecl = [&]() -> TagDecl * {
15435     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15436     // If there is an identifier, use the location of the identifier as the
15437     // location of the decl, otherwise use the location of the struct/union
15438     // keyword.
15439     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15440     TagDecl *New = nullptr;
15441 
15442     if (Kind == TTK_Enum) {
15443       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15444                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15445       // If this is an undefined enum, bail.
15446       if (TUK != TUK_Definition && !Invalid)
15447         return nullptr;
15448       if (EnumUnderlying) {
15449         EnumDecl *ED = cast<EnumDecl>(New);
15450         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15451           ED->setIntegerTypeSourceInfo(TI);
15452         else
15453           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15454         ED->setPromotionType(ED->getIntegerType());
15455       }
15456     } else { // struct/union
15457       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15458                                nullptr);
15459     }
15460 
15461     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15462       // Add alignment attributes if necessary; these attributes are checked
15463       // when the ASTContext lays out the structure.
15464       //
15465       // It is important for implementing the correct semantics that this
15466       // happen here (in ActOnTag). The #pragma pack stack is
15467       // maintained as a result of parser callbacks which can occur at
15468       // many points during the parsing of a struct declaration (because
15469       // the #pragma tokens are effectively skipped over during the
15470       // parsing of the struct).
15471       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15472         AddAlignmentAttributesForRecord(RD);
15473         AddMsStructLayoutForRecord(RD);
15474       }
15475     }
15476     New->setLexicalDeclContext(CurContext);
15477     return New;
15478   };
15479 
15480   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15481   if (Name && SS.isNotEmpty()) {
15482     // We have a nested-name tag ('struct foo::bar').
15483 
15484     // Check for invalid 'foo::'.
15485     if (SS.isInvalid()) {
15486       Name = nullptr;
15487       goto CreateNewDecl;
15488     }
15489 
15490     // If this is a friend or a reference to a class in a dependent
15491     // context, don't try to make a decl for it.
15492     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15493       DC = computeDeclContext(SS, false);
15494       if (!DC) {
15495         IsDependent = true;
15496         return nullptr;
15497       }
15498     } else {
15499       DC = computeDeclContext(SS, true);
15500       if (!DC) {
15501         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15502           << SS.getRange();
15503         return nullptr;
15504       }
15505     }
15506 
15507     if (RequireCompleteDeclContext(SS, DC))
15508       return nullptr;
15509 
15510     SearchDC = DC;
15511     // Look-up name inside 'foo::'.
15512     LookupQualifiedName(Previous, DC);
15513 
15514     if (Previous.isAmbiguous())
15515       return nullptr;
15516 
15517     if (Previous.empty()) {
15518       // Name lookup did not find anything. However, if the
15519       // nested-name-specifier refers to the current instantiation,
15520       // and that current instantiation has any dependent base
15521       // classes, we might find something at instantiation time: treat
15522       // this as a dependent elaborated-type-specifier.
15523       // But this only makes any sense for reference-like lookups.
15524       if (Previous.wasNotFoundInCurrentInstantiation() &&
15525           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15526         IsDependent = true;
15527         return nullptr;
15528       }
15529 
15530       // A tag 'foo::bar' must already exist.
15531       Diag(NameLoc, diag::err_not_tag_in_scope)
15532         << Kind << Name << DC << SS.getRange();
15533       Name = nullptr;
15534       Invalid = true;
15535       goto CreateNewDecl;
15536     }
15537   } else if (Name) {
15538     // C++14 [class.mem]p14:
15539     //   If T is the name of a class, then each of the following shall have a
15540     //   name different from T:
15541     //    -- every member of class T that is itself a type
15542     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15543         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15544       return nullptr;
15545 
15546     // If this is a named struct, check to see if there was a previous forward
15547     // declaration or definition.
15548     // FIXME: We're looking into outer scopes here, even when we
15549     // shouldn't be. Doing so can result in ambiguities that we
15550     // shouldn't be diagnosing.
15551     LookupName(Previous, S);
15552 
15553     // When declaring or defining a tag, ignore ambiguities introduced
15554     // by types using'ed into this scope.
15555     if (Previous.isAmbiguous() &&
15556         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15557       LookupResult::Filter F = Previous.makeFilter();
15558       while (F.hasNext()) {
15559         NamedDecl *ND = F.next();
15560         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15561                 SearchDC->getRedeclContext()))
15562           F.erase();
15563       }
15564       F.done();
15565     }
15566 
15567     // C++11 [namespace.memdef]p3:
15568     //   If the name in a friend declaration is neither qualified nor
15569     //   a template-id and the declaration is a function or an
15570     //   elaborated-type-specifier, the lookup to determine whether
15571     //   the entity has been previously declared shall not consider
15572     //   any scopes outside the innermost enclosing namespace.
15573     //
15574     // MSVC doesn't implement the above rule for types, so a friend tag
15575     // declaration may be a redeclaration of a type declared in an enclosing
15576     // scope.  They do implement this rule for friend functions.
15577     //
15578     // Does it matter that this should be by scope instead of by
15579     // semantic context?
15580     if (!Previous.empty() && TUK == TUK_Friend) {
15581       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15582       LookupResult::Filter F = Previous.makeFilter();
15583       bool FriendSawTagOutsideEnclosingNamespace = false;
15584       while (F.hasNext()) {
15585         NamedDecl *ND = F.next();
15586         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15587         if (DC->isFileContext() &&
15588             !EnclosingNS->Encloses(ND->getDeclContext())) {
15589           if (getLangOpts().MSVCCompat)
15590             FriendSawTagOutsideEnclosingNamespace = true;
15591           else
15592             F.erase();
15593         }
15594       }
15595       F.done();
15596 
15597       // Diagnose this MSVC extension in the easy case where lookup would have
15598       // unambiguously found something outside the enclosing namespace.
15599       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15600         NamedDecl *ND = Previous.getFoundDecl();
15601         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15602             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15603       }
15604     }
15605 
15606     // Note:  there used to be some attempt at recovery here.
15607     if (Previous.isAmbiguous())
15608       return nullptr;
15609 
15610     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15611       // FIXME: This makes sure that we ignore the contexts associated
15612       // with C structs, unions, and enums when looking for a matching
15613       // tag declaration or definition. See the similar lookup tweak
15614       // in Sema::LookupName; is there a better way to deal with this?
15615       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15616         SearchDC = SearchDC->getParent();
15617     }
15618   }
15619 
15620   if (Previous.isSingleResult() &&
15621       Previous.getFoundDecl()->isTemplateParameter()) {
15622     // Maybe we will complain about the shadowed template parameter.
15623     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15624     // Just pretend that we didn't see the previous declaration.
15625     Previous.clear();
15626   }
15627 
15628   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15629       DC->Equals(getStdNamespace())) {
15630     if (Name->isStr("bad_alloc")) {
15631       // This is a declaration of or a reference to "std::bad_alloc".
15632       isStdBadAlloc = true;
15633 
15634       // If std::bad_alloc has been implicitly declared (but made invisible to
15635       // name lookup), fill in this implicit declaration as the previous
15636       // declaration, so that the declarations get chained appropriately.
15637       if (Previous.empty() && StdBadAlloc)
15638         Previous.addDecl(getStdBadAlloc());
15639     } else if (Name->isStr("align_val_t")) {
15640       isStdAlignValT = true;
15641       if (Previous.empty() && StdAlignValT)
15642         Previous.addDecl(getStdAlignValT());
15643     }
15644   }
15645 
15646   // If we didn't find a previous declaration, and this is a reference
15647   // (or friend reference), move to the correct scope.  In C++, we
15648   // also need to do a redeclaration lookup there, just in case
15649   // there's a shadow friend decl.
15650   if (Name && Previous.empty() &&
15651       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15652     if (Invalid) goto CreateNewDecl;
15653     assert(SS.isEmpty());
15654 
15655     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15656       // C++ [basic.scope.pdecl]p5:
15657       //   -- for an elaborated-type-specifier of the form
15658       //
15659       //          class-key identifier
15660       //
15661       //      if the elaborated-type-specifier is used in the
15662       //      decl-specifier-seq or parameter-declaration-clause of a
15663       //      function defined in namespace scope, the identifier is
15664       //      declared as a class-name in the namespace that contains
15665       //      the declaration; otherwise, except as a friend
15666       //      declaration, the identifier is declared in the smallest
15667       //      non-class, non-function-prototype scope that contains the
15668       //      declaration.
15669       //
15670       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15671       // C structs and unions.
15672       //
15673       // It is an error in C++ to declare (rather than define) an enum
15674       // type, including via an elaborated type specifier.  We'll
15675       // diagnose that later; for now, declare the enum in the same
15676       // scope as we would have picked for any other tag type.
15677       //
15678       // GNU C also supports this behavior as part of its incomplete
15679       // enum types extension, while GNU C++ does not.
15680       //
15681       // Find the context where we'll be declaring the tag.
15682       // FIXME: We would like to maintain the current DeclContext as the
15683       // lexical context,
15684       SearchDC = getTagInjectionContext(SearchDC);
15685 
15686       // Find the scope where we'll be declaring the tag.
15687       S = getTagInjectionScope(S, getLangOpts());
15688     } else {
15689       assert(TUK == TUK_Friend);
15690       // C++ [namespace.memdef]p3:
15691       //   If a friend declaration in a non-local class first declares a
15692       //   class or function, the friend class or function is a member of
15693       //   the innermost enclosing namespace.
15694       SearchDC = SearchDC->getEnclosingNamespaceContext();
15695     }
15696 
15697     // In C++, we need to do a redeclaration lookup to properly
15698     // diagnose some problems.
15699     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15700     // hidden declaration so that we don't get ambiguity errors when using a
15701     // type declared by an elaborated-type-specifier.  In C that is not correct
15702     // and we should instead merge compatible types found by lookup.
15703     if (getLangOpts().CPlusPlus) {
15704       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15705       LookupQualifiedName(Previous, SearchDC);
15706     } else {
15707       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15708       LookupName(Previous, S);
15709     }
15710   }
15711 
15712   // If we have a known previous declaration to use, then use it.
15713   if (Previous.empty() && SkipBody && SkipBody->Previous)
15714     Previous.addDecl(SkipBody->Previous);
15715 
15716   if (!Previous.empty()) {
15717     NamedDecl *PrevDecl = Previous.getFoundDecl();
15718     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15719 
15720     // It's okay to have a tag decl in the same scope as a typedef
15721     // which hides a tag decl in the same scope.  Finding this
15722     // insanity with a redeclaration lookup can only actually happen
15723     // in C++.
15724     //
15725     // This is also okay for elaborated-type-specifiers, which is
15726     // technically forbidden by the current standard but which is
15727     // okay according to the likely resolution of an open issue;
15728     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15729     if (getLangOpts().CPlusPlus) {
15730       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15731         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15732           TagDecl *Tag = TT->getDecl();
15733           if (Tag->getDeclName() == Name &&
15734               Tag->getDeclContext()->getRedeclContext()
15735                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15736             PrevDecl = Tag;
15737             Previous.clear();
15738             Previous.addDecl(Tag);
15739             Previous.resolveKind();
15740           }
15741         }
15742       }
15743     }
15744 
15745     // If this is a redeclaration of a using shadow declaration, it must
15746     // declare a tag in the same context. In MSVC mode, we allow a
15747     // redefinition if either context is within the other.
15748     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15749       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15750       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15751           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15752           !(OldTag && isAcceptableTagRedeclContext(
15753                           *this, OldTag->getDeclContext(), SearchDC))) {
15754         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15755         Diag(Shadow->getTargetDecl()->getLocation(),
15756              diag::note_using_decl_target);
15757         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15758             << 0;
15759         // Recover by ignoring the old declaration.
15760         Previous.clear();
15761         goto CreateNewDecl;
15762       }
15763     }
15764 
15765     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15766       // If this is a use of a previous tag, or if the tag is already declared
15767       // in the same scope (so that the definition/declaration completes or
15768       // rementions the tag), reuse the decl.
15769       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15770           isDeclInScope(DirectPrevDecl, SearchDC, S,
15771                         SS.isNotEmpty() || isMemberSpecialization)) {
15772         // Make sure that this wasn't declared as an enum and now used as a
15773         // struct or something similar.
15774         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15775                                           TUK == TUK_Definition, KWLoc,
15776                                           Name)) {
15777           bool SafeToContinue
15778             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15779                Kind != TTK_Enum);
15780           if (SafeToContinue)
15781             Diag(KWLoc, diag::err_use_with_wrong_tag)
15782               << Name
15783               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15784                                               PrevTagDecl->getKindName());
15785           else
15786             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15787           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15788 
15789           if (SafeToContinue)
15790             Kind = PrevTagDecl->getTagKind();
15791           else {
15792             // Recover by making this an anonymous redefinition.
15793             Name = nullptr;
15794             Previous.clear();
15795             Invalid = true;
15796           }
15797         }
15798 
15799         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15800           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15801           if (TUK == TUK_Reference || TUK == TUK_Friend)
15802             return PrevTagDecl;
15803 
15804           QualType EnumUnderlyingTy;
15805           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15806             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15807           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15808             EnumUnderlyingTy = QualType(T, 0);
15809 
15810           // All conflicts with previous declarations are recovered by
15811           // returning the previous declaration, unless this is a definition,
15812           // in which case we want the caller to bail out.
15813           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15814                                      ScopedEnum, EnumUnderlyingTy,
15815                                      IsFixed, PrevEnum))
15816             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15817         }
15818 
15819         // C++11 [class.mem]p1:
15820         //   A member shall not be declared twice in the member-specification,
15821         //   except that a nested class or member class template can be declared
15822         //   and then later defined.
15823         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15824             S->isDeclScope(PrevDecl)) {
15825           Diag(NameLoc, diag::ext_member_redeclared);
15826           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15827         }
15828 
15829         if (!Invalid) {
15830           // If this is a use, just return the declaration we found, unless
15831           // we have attributes.
15832           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15833             if (!Attrs.empty()) {
15834               // FIXME: Diagnose these attributes. For now, we create a new
15835               // declaration to hold them.
15836             } else if (TUK == TUK_Reference &&
15837                        (PrevTagDecl->getFriendObjectKind() ==
15838                             Decl::FOK_Undeclared ||
15839                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15840                        SS.isEmpty()) {
15841               // This declaration is a reference to an existing entity, but
15842               // has different visibility from that entity: it either makes
15843               // a friend visible or it makes a type visible in a new module.
15844               // In either case, create a new declaration. We only do this if
15845               // the declaration would have meant the same thing if no prior
15846               // declaration were found, that is, if it was found in the same
15847               // scope where we would have injected a declaration.
15848               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15849                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15850                 return PrevTagDecl;
15851               // This is in the injected scope, create a new declaration in
15852               // that scope.
15853               S = getTagInjectionScope(S, getLangOpts());
15854             } else {
15855               return PrevTagDecl;
15856             }
15857           }
15858 
15859           // Diagnose attempts to redefine a tag.
15860           if (TUK == TUK_Definition) {
15861             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15862               // If we're defining a specialization and the previous definition
15863               // is from an implicit instantiation, don't emit an error
15864               // here; we'll catch this in the general case below.
15865               bool IsExplicitSpecializationAfterInstantiation = false;
15866               if (isMemberSpecialization) {
15867                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15868                   IsExplicitSpecializationAfterInstantiation =
15869                     RD->getTemplateSpecializationKind() !=
15870                     TSK_ExplicitSpecialization;
15871                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15872                   IsExplicitSpecializationAfterInstantiation =
15873                     ED->getTemplateSpecializationKind() !=
15874                     TSK_ExplicitSpecialization;
15875               }
15876 
15877               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15878               // not keep more that one definition around (merge them). However,
15879               // ensure the decl passes the structural compatibility check in
15880               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15881               NamedDecl *Hidden = nullptr;
15882               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15883                 // There is a definition of this tag, but it is not visible. We
15884                 // explicitly make use of C++'s one definition rule here, and
15885                 // assume that this definition is identical to the hidden one
15886                 // we already have. Make the existing definition visible and
15887                 // use it in place of this one.
15888                 if (!getLangOpts().CPlusPlus) {
15889                   // Postpone making the old definition visible until after we
15890                   // complete parsing the new one and do the structural
15891                   // comparison.
15892                   SkipBody->CheckSameAsPrevious = true;
15893                   SkipBody->New = createTagFromNewDecl();
15894                   SkipBody->Previous = Def;
15895                   return Def;
15896                 } else {
15897                   SkipBody->ShouldSkip = true;
15898                   SkipBody->Previous = Def;
15899                   makeMergedDefinitionVisible(Hidden);
15900                   // Carry on and handle it like a normal definition. We'll
15901                   // skip starting the definitiion later.
15902                 }
15903               } else if (!IsExplicitSpecializationAfterInstantiation) {
15904                 // A redeclaration in function prototype scope in C isn't
15905                 // visible elsewhere, so merely issue a warning.
15906                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15907                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15908                 else
15909                   Diag(NameLoc, diag::err_redefinition) << Name;
15910                 notePreviousDefinition(Def,
15911                                        NameLoc.isValid() ? NameLoc : KWLoc);
15912                 // If this is a redefinition, recover by making this
15913                 // struct be anonymous, which will make any later
15914                 // references get the previous definition.
15915                 Name = nullptr;
15916                 Previous.clear();
15917                 Invalid = true;
15918               }
15919             } else {
15920               // If the type is currently being defined, complain
15921               // about a nested redefinition.
15922               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15923               if (TD->isBeingDefined()) {
15924                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15925                 Diag(PrevTagDecl->getLocation(),
15926                      diag::note_previous_definition);
15927                 Name = nullptr;
15928                 Previous.clear();
15929                 Invalid = true;
15930               }
15931             }
15932 
15933             // Okay, this is definition of a previously declared or referenced
15934             // tag. We're going to create a new Decl for it.
15935           }
15936 
15937           // Okay, we're going to make a redeclaration.  If this is some kind
15938           // of reference, make sure we build the redeclaration in the same DC
15939           // as the original, and ignore the current access specifier.
15940           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15941             SearchDC = PrevTagDecl->getDeclContext();
15942             AS = AS_none;
15943           }
15944         }
15945         // If we get here we have (another) forward declaration or we
15946         // have a definition.  Just create a new decl.
15947 
15948       } else {
15949         // If we get here, this is a definition of a new tag type in a nested
15950         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15951         // new decl/type.  We set PrevDecl to NULL so that the entities
15952         // have distinct types.
15953         Previous.clear();
15954       }
15955       // If we get here, we're going to create a new Decl. If PrevDecl
15956       // is non-NULL, it's a definition of the tag declared by
15957       // PrevDecl. If it's NULL, we have a new definition.
15958 
15959     // Otherwise, PrevDecl is not a tag, but was found with tag
15960     // lookup.  This is only actually possible in C++, where a few
15961     // things like templates still live in the tag namespace.
15962     } else {
15963       // Use a better diagnostic if an elaborated-type-specifier
15964       // found the wrong kind of type on the first
15965       // (non-redeclaration) lookup.
15966       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15967           !Previous.isForRedeclaration()) {
15968         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15969         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15970                                                        << Kind;
15971         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15972         Invalid = true;
15973 
15974       // Otherwise, only diagnose if the declaration is in scope.
15975       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15976                                 SS.isNotEmpty() || isMemberSpecialization)) {
15977         // do nothing
15978 
15979       // Diagnose implicit declarations introduced by elaborated types.
15980       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15981         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15982         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15983         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15984         Invalid = true;
15985 
15986       // Otherwise it's a declaration.  Call out a particularly common
15987       // case here.
15988       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15989         unsigned Kind = 0;
15990         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15991         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15992           << Name << Kind << TND->getUnderlyingType();
15993         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15994         Invalid = true;
15995 
15996       // Otherwise, diagnose.
15997       } else {
15998         // The tag name clashes with something else in the target scope,
15999         // issue an error and recover by making this tag be anonymous.
16000         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16001         notePreviousDefinition(PrevDecl, NameLoc);
16002         Name = nullptr;
16003         Invalid = true;
16004       }
16005 
16006       // The existing declaration isn't relevant to us; we're in a
16007       // new scope, so clear out the previous declaration.
16008       Previous.clear();
16009     }
16010   }
16011 
16012 CreateNewDecl:
16013 
16014   TagDecl *PrevDecl = nullptr;
16015   if (Previous.isSingleResult())
16016     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16017 
16018   // If there is an identifier, use the location of the identifier as the
16019   // location of the decl, otherwise use the location of the struct/union
16020   // keyword.
16021   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16022 
16023   // Otherwise, create a new declaration. If there is a previous
16024   // declaration of the same entity, the two will be linked via
16025   // PrevDecl.
16026   TagDecl *New;
16027 
16028   if (Kind == TTK_Enum) {
16029     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16030     // enum X { A, B, C } D;    D should chain to X.
16031     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16032                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16033                            ScopedEnumUsesClassTag, IsFixed);
16034 
16035     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16036       StdAlignValT = cast<EnumDecl>(New);
16037 
16038     // If this is an undefined enum, warn.
16039     if (TUK != TUK_Definition && !Invalid) {
16040       TagDecl *Def;
16041       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16042         // C++0x: 7.2p2: opaque-enum-declaration.
16043         // Conflicts are diagnosed above. Do nothing.
16044       }
16045       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16046         Diag(Loc, diag::ext_forward_ref_enum_def)
16047           << New;
16048         Diag(Def->getLocation(), diag::note_previous_definition);
16049       } else {
16050         unsigned DiagID = diag::ext_forward_ref_enum;
16051         if (getLangOpts().MSVCCompat)
16052           DiagID = diag::ext_ms_forward_ref_enum;
16053         else if (getLangOpts().CPlusPlus)
16054           DiagID = diag::err_forward_ref_enum;
16055         Diag(Loc, DiagID);
16056       }
16057     }
16058 
16059     if (EnumUnderlying) {
16060       EnumDecl *ED = cast<EnumDecl>(New);
16061       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16062         ED->setIntegerTypeSourceInfo(TI);
16063       else
16064         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16065       ED->setPromotionType(ED->getIntegerType());
16066       assert(ED->isComplete() && "enum with type should be complete");
16067     }
16068   } else {
16069     // struct/union/class
16070 
16071     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16072     // struct X { int A; } D;    D should chain to X.
16073     if (getLangOpts().CPlusPlus) {
16074       // FIXME: Look for a way to use RecordDecl for simple structs.
16075       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16076                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16077 
16078       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16079         StdBadAlloc = cast<CXXRecordDecl>(New);
16080     } else
16081       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16082                                cast_or_null<RecordDecl>(PrevDecl));
16083   }
16084 
16085   // C++11 [dcl.type]p3:
16086   //   A type-specifier-seq shall not define a class or enumeration [...].
16087   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16088       TUK == TUK_Definition) {
16089     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16090       << Context.getTagDeclType(New);
16091     Invalid = true;
16092   }
16093 
16094   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16095       DC->getDeclKind() == Decl::Enum) {
16096     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16097       << Context.getTagDeclType(New);
16098     Invalid = true;
16099   }
16100 
16101   // Maybe add qualifier info.
16102   if (SS.isNotEmpty()) {
16103     if (SS.isSet()) {
16104       // If this is either a declaration or a definition, check the
16105       // nested-name-specifier against the current context.
16106       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16107           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16108                                        isMemberSpecialization))
16109         Invalid = true;
16110 
16111       New->setQualifierInfo(SS.getWithLocInContext(Context));
16112       if (TemplateParameterLists.size() > 0) {
16113         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16114       }
16115     }
16116     else
16117       Invalid = true;
16118   }
16119 
16120   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16121     // Add alignment attributes if necessary; these attributes are checked when
16122     // the ASTContext lays out the structure.
16123     //
16124     // It is important for implementing the correct semantics that this
16125     // happen here (in ActOnTag). The #pragma pack stack is
16126     // maintained as a result of parser callbacks which can occur at
16127     // many points during the parsing of a struct declaration (because
16128     // the #pragma tokens are effectively skipped over during the
16129     // parsing of the struct).
16130     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16131       AddAlignmentAttributesForRecord(RD);
16132       AddMsStructLayoutForRecord(RD);
16133     }
16134   }
16135 
16136   if (ModulePrivateLoc.isValid()) {
16137     if (isMemberSpecialization)
16138       Diag(New->getLocation(), diag::err_module_private_specialization)
16139         << 2
16140         << FixItHint::CreateRemoval(ModulePrivateLoc);
16141     // __module_private__ does not apply to local classes. However, we only
16142     // diagnose this as an error when the declaration specifiers are
16143     // freestanding. Here, we just ignore the __module_private__.
16144     else if (!SearchDC->isFunctionOrMethod())
16145       New->setModulePrivate();
16146   }
16147 
16148   // If this is a specialization of a member class (of a class template),
16149   // check the specialization.
16150   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16151     Invalid = true;
16152 
16153   // If we're declaring or defining a tag in function prototype scope in C,
16154   // note that this type can only be used within the function and add it to
16155   // the list of decls to inject into the function definition scope.
16156   if ((Name || Kind == TTK_Enum) &&
16157       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16158     if (getLangOpts().CPlusPlus) {
16159       // C++ [dcl.fct]p6:
16160       //   Types shall not be defined in return or parameter types.
16161       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16162         Diag(Loc, diag::err_type_defined_in_param_type)
16163             << Name;
16164         Invalid = true;
16165       }
16166     } else if (!PrevDecl) {
16167       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16168     }
16169   }
16170 
16171   if (Invalid)
16172     New->setInvalidDecl();
16173 
16174   // Set the lexical context. If the tag has a C++ scope specifier, the
16175   // lexical context will be different from the semantic context.
16176   New->setLexicalDeclContext(CurContext);
16177 
16178   // Mark this as a friend decl if applicable.
16179   // In Microsoft mode, a friend declaration also acts as a forward
16180   // declaration so we always pass true to setObjectOfFriendDecl to make
16181   // the tag name visible.
16182   if (TUK == TUK_Friend)
16183     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16184 
16185   // Set the access specifier.
16186   if (!Invalid && SearchDC->isRecord())
16187     SetMemberAccessSpecifier(New, PrevDecl, AS);
16188 
16189   if (PrevDecl)
16190     CheckRedeclarationModuleOwnership(New, PrevDecl);
16191 
16192   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16193     New->startDefinition();
16194 
16195   ProcessDeclAttributeList(S, New, Attrs);
16196   AddPragmaAttributes(S, New);
16197 
16198   // If this has an identifier, add it to the scope stack.
16199   if (TUK == TUK_Friend) {
16200     // We might be replacing an existing declaration in the lookup tables;
16201     // if so, borrow its access specifier.
16202     if (PrevDecl)
16203       New->setAccess(PrevDecl->getAccess());
16204 
16205     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16206     DC->makeDeclVisibleInContext(New);
16207     if (Name) // can be null along some error paths
16208       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16209         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16210   } else if (Name) {
16211     S = getNonFieldDeclScope(S);
16212     PushOnScopeChains(New, S, true);
16213   } else {
16214     CurContext->addDecl(New);
16215   }
16216 
16217   // If this is the C FILE type, notify the AST context.
16218   if (IdentifierInfo *II = New->getIdentifier())
16219     if (!New->isInvalidDecl() &&
16220         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16221         II->isStr("FILE"))
16222       Context.setFILEDecl(New);
16223 
16224   if (PrevDecl)
16225     mergeDeclAttributes(New, PrevDecl);
16226 
16227   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16228     inferGslOwnerPointerAttribute(CXXRD);
16229 
16230   // If there's a #pragma GCC visibility in scope, set the visibility of this
16231   // record.
16232   AddPushedVisibilityAttribute(New);
16233 
16234   if (isMemberSpecialization && !New->isInvalidDecl())
16235     CompleteMemberSpecialization(New, Previous);
16236 
16237   OwnedDecl = true;
16238   // In C++, don't return an invalid declaration. We can't recover well from
16239   // the cases where we make the type anonymous.
16240   if (Invalid && getLangOpts().CPlusPlus) {
16241     if (New->isBeingDefined())
16242       if (auto RD = dyn_cast<RecordDecl>(New))
16243         RD->completeDefinition();
16244     return nullptr;
16245   } else if (SkipBody && SkipBody->ShouldSkip) {
16246     return SkipBody->Previous;
16247   } else {
16248     return New;
16249   }
16250 }
16251 
16252 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16253   AdjustDeclIfTemplate(TagD);
16254   TagDecl *Tag = cast<TagDecl>(TagD);
16255 
16256   // Enter the tag context.
16257   PushDeclContext(S, Tag);
16258 
16259   ActOnDocumentableDecl(TagD);
16260 
16261   // If there's a #pragma GCC visibility in scope, set the visibility of this
16262   // record.
16263   AddPushedVisibilityAttribute(Tag);
16264 }
16265 
16266 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16267                                     SkipBodyInfo &SkipBody) {
16268   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16269     return false;
16270 
16271   // Make the previous decl visible.
16272   makeMergedDefinitionVisible(SkipBody.Previous);
16273   return true;
16274 }
16275 
16276 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16277   assert(isa<ObjCContainerDecl>(IDecl) &&
16278          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16279   DeclContext *OCD = cast<DeclContext>(IDecl);
16280   assert(OCD->getLexicalParent() == CurContext &&
16281       "The next DeclContext should be lexically contained in the current one.");
16282   CurContext = OCD;
16283   return IDecl;
16284 }
16285 
16286 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16287                                            SourceLocation FinalLoc,
16288                                            bool IsFinalSpelledSealed,
16289                                            SourceLocation LBraceLoc) {
16290   AdjustDeclIfTemplate(TagD);
16291   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16292 
16293   FieldCollector->StartClass();
16294 
16295   if (!Record->getIdentifier())
16296     return;
16297 
16298   if (FinalLoc.isValid())
16299     Record->addAttr(FinalAttr::Create(
16300         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16301         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16302 
16303   // C++ [class]p2:
16304   //   [...] The class-name is also inserted into the scope of the
16305   //   class itself; this is known as the injected-class-name. For
16306   //   purposes of access checking, the injected-class-name is treated
16307   //   as if it were a public member name.
16308   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16309       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16310       Record->getLocation(), Record->getIdentifier(),
16311       /*PrevDecl=*/nullptr,
16312       /*DelayTypeCreation=*/true);
16313   Context.getTypeDeclType(InjectedClassName, Record);
16314   InjectedClassName->setImplicit();
16315   InjectedClassName->setAccess(AS_public);
16316   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16317       InjectedClassName->setDescribedClassTemplate(Template);
16318   PushOnScopeChains(InjectedClassName, S);
16319   assert(InjectedClassName->isInjectedClassName() &&
16320          "Broken injected-class-name");
16321 }
16322 
16323 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16324                                     SourceRange BraceRange) {
16325   AdjustDeclIfTemplate(TagD);
16326   TagDecl *Tag = cast<TagDecl>(TagD);
16327   Tag->setBraceRange(BraceRange);
16328 
16329   // Make sure we "complete" the definition even it is invalid.
16330   if (Tag->isBeingDefined()) {
16331     assert(Tag->isInvalidDecl() && "We should already have completed it");
16332     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16333       RD->completeDefinition();
16334   }
16335 
16336   if (isa<CXXRecordDecl>(Tag)) {
16337     FieldCollector->FinishClass();
16338   }
16339 
16340   // Exit this scope of this tag's definition.
16341   PopDeclContext();
16342 
16343   if (getCurLexicalContext()->isObjCContainer() &&
16344       Tag->getDeclContext()->isFileContext())
16345     Tag->setTopLevelDeclInObjCContainer();
16346 
16347   // Notify the consumer that we've defined a tag.
16348   if (!Tag->isInvalidDecl())
16349     Consumer.HandleTagDeclDefinition(Tag);
16350 }
16351 
16352 void Sema::ActOnObjCContainerFinishDefinition() {
16353   // Exit this scope of this interface definition.
16354   PopDeclContext();
16355 }
16356 
16357 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16358   assert(DC == CurContext && "Mismatch of container contexts");
16359   OriginalLexicalContext = DC;
16360   ActOnObjCContainerFinishDefinition();
16361 }
16362 
16363 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16364   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16365   OriginalLexicalContext = nullptr;
16366 }
16367 
16368 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16369   AdjustDeclIfTemplate(TagD);
16370   TagDecl *Tag = cast<TagDecl>(TagD);
16371   Tag->setInvalidDecl();
16372 
16373   // Make sure we "complete" the definition even it is invalid.
16374   if (Tag->isBeingDefined()) {
16375     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16376       RD->completeDefinition();
16377   }
16378 
16379   // We're undoing ActOnTagStartDefinition here, not
16380   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16381   // the FieldCollector.
16382 
16383   PopDeclContext();
16384 }
16385 
16386 // Note that FieldName may be null for anonymous bitfields.
16387 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16388                                 IdentifierInfo *FieldName,
16389                                 QualType FieldTy, bool IsMsStruct,
16390                                 Expr *BitWidth, bool *ZeroWidth) {
16391   assert(BitWidth);
16392   if (BitWidth->containsErrors())
16393     return ExprError();
16394 
16395   // Default to true; that shouldn't confuse checks for emptiness
16396   if (ZeroWidth)
16397     *ZeroWidth = true;
16398 
16399   // C99 6.7.2.1p4 - verify the field type.
16400   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16401   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16402     // Handle incomplete and sizeless types with a specific error.
16403     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16404                                  diag::err_field_incomplete_or_sizeless))
16405       return ExprError();
16406     if (FieldName)
16407       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16408         << FieldName << FieldTy << BitWidth->getSourceRange();
16409     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16410       << FieldTy << BitWidth->getSourceRange();
16411   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16412                                              UPPC_BitFieldWidth))
16413     return ExprError();
16414 
16415   // If the bit-width is type- or value-dependent, don't try to check
16416   // it now.
16417   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16418     return BitWidth;
16419 
16420   llvm::APSInt Value;
16421   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16422   if (ICE.isInvalid())
16423     return ICE;
16424   BitWidth = ICE.get();
16425 
16426   if (Value != 0 && ZeroWidth)
16427     *ZeroWidth = false;
16428 
16429   // Zero-width bitfield is ok for anonymous field.
16430   if (Value == 0 && FieldName)
16431     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16432 
16433   if (Value.isSigned() && Value.isNegative()) {
16434     if (FieldName)
16435       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16436                << FieldName << Value.toString(10);
16437     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16438       << Value.toString(10);
16439   }
16440 
16441   if (!FieldTy->isDependentType()) {
16442     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16443     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16444     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16445 
16446     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16447     // ABI.
16448     bool CStdConstraintViolation =
16449         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16450     bool MSBitfieldViolation =
16451         Value.ugt(TypeStorageSize) &&
16452         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16453     if (CStdConstraintViolation || MSBitfieldViolation) {
16454       unsigned DiagWidth =
16455           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16456       if (FieldName)
16457         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16458                << FieldName << (unsigned)Value.getZExtValue()
16459                << !CStdConstraintViolation << DiagWidth;
16460 
16461       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16462              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16463              << DiagWidth;
16464     }
16465 
16466     // Warn on types where the user might conceivably expect to get all
16467     // specified bits as value bits: that's all integral types other than
16468     // 'bool'.
16469     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16470       if (FieldName)
16471         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16472             << FieldName << (unsigned)Value.getZExtValue()
16473             << (unsigned)TypeWidth;
16474       else
16475         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16476             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16477     }
16478   }
16479 
16480   return BitWidth;
16481 }
16482 
16483 /// ActOnField - Each field of a C struct/union is passed into this in order
16484 /// to create a FieldDecl object for it.
16485 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16486                        Declarator &D, Expr *BitfieldWidth) {
16487   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16488                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16489                                /*InitStyle=*/ICIS_NoInit, AS_public);
16490   return Res;
16491 }
16492 
16493 /// HandleField - Analyze a field of a C struct or a C++ data member.
16494 ///
16495 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16496                              SourceLocation DeclStart,
16497                              Declarator &D, Expr *BitWidth,
16498                              InClassInitStyle InitStyle,
16499                              AccessSpecifier AS) {
16500   if (D.isDecompositionDeclarator()) {
16501     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16502     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16503       << Decomp.getSourceRange();
16504     return nullptr;
16505   }
16506 
16507   IdentifierInfo *II = D.getIdentifier();
16508   SourceLocation Loc = DeclStart;
16509   if (II) Loc = D.getIdentifierLoc();
16510 
16511   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16512   QualType T = TInfo->getType();
16513   if (getLangOpts().CPlusPlus) {
16514     CheckExtraCXXDefaultArguments(D);
16515 
16516     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16517                                         UPPC_DataMemberType)) {
16518       D.setInvalidType();
16519       T = Context.IntTy;
16520       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16521     }
16522   }
16523 
16524   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16525 
16526   if (D.getDeclSpec().isInlineSpecified())
16527     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16528         << getLangOpts().CPlusPlus17;
16529   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16530     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16531          diag::err_invalid_thread)
16532       << DeclSpec::getSpecifierName(TSCS);
16533 
16534   // Check to see if this name was declared as a member previously
16535   NamedDecl *PrevDecl = nullptr;
16536   LookupResult Previous(*this, II, Loc, LookupMemberName,
16537                         ForVisibleRedeclaration);
16538   LookupName(Previous, S);
16539   switch (Previous.getResultKind()) {
16540     case LookupResult::Found:
16541     case LookupResult::FoundUnresolvedValue:
16542       PrevDecl = Previous.getAsSingle<NamedDecl>();
16543       break;
16544 
16545     case LookupResult::FoundOverloaded:
16546       PrevDecl = Previous.getRepresentativeDecl();
16547       break;
16548 
16549     case LookupResult::NotFound:
16550     case LookupResult::NotFoundInCurrentInstantiation:
16551     case LookupResult::Ambiguous:
16552       break;
16553   }
16554   Previous.suppressDiagnostics();
16555 
16556   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16557     // Maybe we will complain about the shadowed template parameter.
16558     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16559     // Just pretend that we didn't see the previous declaration.
16560     PrevDecl = nullptr;
16561   }
16562 
16563   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16564     PrevDecl = nullptr;
16565 
16566   bool Mutable
16567     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16568   SourceLocation TSSL = D.getBeginLoc();
16569   FieldDecl *NewFD
16570     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16571                      TSSL, AS, PrevDecl, &D);
16572 
16573   if (NewFD->isInvalidDecl())
16574     Record->setInvalidDecl();
16575 
16576   if (D.getDeclSpec().isModulePrivateSpecified())
16577     NewFD->setModulePrivate();
16578 
16579   if (NewFD->isInvalidDecl() && PrevDecl) {
16580     // Don't introduce NewFD into scope; there's already something
16581     // with the same name in the same scope.
16582   } else if (II) {
16583     PushOnScopeChains(NewFD, S);
16584   } else
16585     Record->addDecl(NewFD);
16586 
16587   return NewFD;
16588 }
16589 
16590 /// Build a new FieldDecl and check its well-formedness.
16591 ///
16592 /// This routine builds a new FieldDecl given the fields name, type,
16593 /// record, etc. \p PrevDecl should refer to any previous declaration
16594 /// with the same name and in the same scope as the field to be
16595 /// created.
16596 ///
16597 /// \returns a new FieldDecl.
16598 ///
16599 /// \todo The Declarator argument is a hack. It will be removed once
16600 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16601                                 TypeSourceInfo *TInfo,
16602                                 RecordDecl *Record, SourceLocation Loc,
16603                                 bool Mutable, Expr *BitWidth,
16604                                 InClassInitStyle InitStyle,
16605                                 SourceLocation TSSL,
16606                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16607                                 Declarator *D) {
16608   IdentifierInfo *II = Name.getAsIdentifierInfo();
16609   bool InvalidDecl = false;
16610   if (D) InvalidDecl = D->isInvalidType();
16611 
16612   // If we receive a broken type, recover by assuming 'int' and
16613   // marking this declaration as invalid.
16614   if (T.isNull() || T->containsErrors()) {
16615     InvalidDecl = true;
16616     T = Context.IntTy;
16617   }
16618 
16619   QualType EltTy = Context.getBaseElementType(T);
16620   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16621     if (RequireCompleteSizedType(Loc, EltTy,
16622                                  diag::err_field_incomplete_or_sizeless)) {
16623       // Fields of incomplete type force their record to be invalid.
16624       Record->setInvalidDecl();
16625       InvalidDecl = true;
16626     } else {
16627       NamedDecl *Def;
16628       EltTy->isIncompleteType(&Def);
16629       if (Def && Def->isInvalidDecl()) {
16630         Record->setInvalidDecl();
16631         InvalidDecl = true;
16632       }
16633     }
16634   }
16635 
16636   // TR 18037 does not allow fields to be declared with address space
16637   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16638       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16639     Diag(Loc, diag::err_field_with_address_space);
16640     Record->setInvalidDecl();
16641     InvalidDecl = true;
16642   }
16643 
16644   if (LangOpts.OpenCL) {
16645     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16646     // used as structure or union field: image, sampler, event or block types.
16647     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16648         T->isBlockPointerType()) {
16649       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16650       Record->setInvalidDecl();
16651       InvalidDecl = true;
16652     }
16653     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16654     if (BitWidth) {
16655       Diag(Loc, diag::err_opencl_bitfields);
16656       InvalidDecl = true;
16657     }
16658   }
16659 
16660   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16661   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16662       T.hasQualifiers()) {
16663     InvalidDecl = true;
16664     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16665   }
16666 
16667   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16668   // than a variably modified type.
16669   if (!InvalidDecl && T->isVariablyModifiedType()) {
16670     bool SizeIsNegative;
16671     llvm::APSInt Oversized;
16672 
16673     TypeSourceInfo *FixedTInfo =
16674       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16675                                                     SizeIsNegative,
16676                                                     Oversized);
16677     if (FixedTInfo) {
16678       Diag(Loc, diag::warn_illegal_constant_array_size);
16679       TInfo = FixedTInfo;
16680       T = FixedTInfo->getType();
16681     } else {
16682       if (SizeIsNegative)
16683         Diag(Loc, diag::err_typecheck_negative_array_size);
16684       else if (Oversized.getBoolValue())
16685         Diag(Loc, diag::err_array_too_large)
16686           << Oversized.toString(10);
16687       else
16688         Diag(Loc, diag::err_typecheck_field_variable_size);
16689       InvalidDecl = true;
16690     }
16691   }
16692 
16693   // Fields can not have abstract class types
16694   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16695                                              diag::err_abstract_type_in_decl,
16696                                              AbstractFieldType))
16697     InvalidDecl = true;
16698 
16699   bool ZeroWidth = false;
16700   if (InvalidDecl)
16701     BitWidth = nullptr;
16702   // If this is declared as a bit-field, check the bit-field.
16703   if (BitWidth) {
16704     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16705                               &ZeroWidth).get();
16706     if (!BitWidth) {
16707       InvalidDecl = true;
16708       BitWidth = nullptr;
16709       ZeroWidth = false;
16710     }
16711 
16712     // Only data members can have in-class initializers.
16713     if (BitWidth && !II && InitStyle) {
16714       Diag(Loc, diag::err_anon_bitfield_init);
16715       InvalidDecl = true;
16716       BitWidth = nullptr;
16717       ZeroWidth = false;
16718     }
16719   }
16720 
16721   // Check that 'mutable' is consistent with the type of the declaration.
16722   if (!InvalidDecl && Mutable) {
16723     unsigned DiagID = 0;
16724     if (T->isReferenceType())
16725       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16726                                         : diag::err_mutable_reference;
16727     else if (T.isConstQualified())
16728       DiagID = diag::err_mutable_const;
16729 
16730     if (DiagID) {
16731       SourceLocation ErrLoc = Loc;
16732       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16733         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16734       Diag(ErrLoc, DiagID);
16735       if (DiagID != diag::ext_mutable_reference) {
16736         Mutable = false;
16737         InvalidDecl = true;
16738       }
16739     }
16740   }
16741 
16742   // C++11 [class.union]p8 (DR1460):
16743   //   At most one variant member of a union may have a
16744   //   brace-or-equal-initializer.
16745   if (InitStyle != ICIS_NoInit)
16746     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16747 
16748   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16749                                        BitWidth, Mutable, InitStyle);
16750   if (InvalidDecl)
16751     NewFD->setInvalidDecl();
16752 
16753   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16754     Diag(Loc, diag::err_duplicate_member) << II;
16755     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16756     NewFD->setInvalidDecl();
16757   }
16758 
16759   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16760     if (Record->isUnion()) {
16761       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16762         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16763         if (RDecl->getDefinition()) {
16764           // C++ [class.union]p1: An object of a class with a non-trivial
16765           // constructor, a non-trivial copy constructor, a non-trivial
16766           // destructor, or a non-trivial copy assignment operator
16767           // cannot be a member of a union, nor can an array of such
16768           // objects.
16769           if (CheckNontrivialField(NewFD))
16770             NewFD->setInvalidDecl();
16771         }
16772       }
16773 
16774       // C++ [class.union]p1: If a union contains a member of reference type,
16775       // the program is ill-formed, except when compiling with MSVC extensions
16776       // enabled.
16777       if (EltTy->isReferenceType()) {
16778         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16779                                     diag::ext_union_member_of_reference_type :
16780                                     diag::err_union_member_of_reference_type)
16781           << NewFD->getDeclName() << EltTy;
16782         if (!getLangOpts().MicrosoftExt)
16783           NewFD->setInvalidDecl();
16784       }
16785     }
16786   }
16787 
16788   // FIXME: We need to pass in the attributes given an AST
16789   // representation, not a parser representation.
16790   if (D) {
16791     // FIXME: The current scope is almost... but not entirely... correct here.
16792     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16793 
16794     if (NewFD->hasAttrs())
16795       CheckAlignasUnderalignment(NewFD);
16796   }
16797 
16798   // In auto-retain/release, infer strong retension for fields of
16799   // retainable type.
16800   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16801     NewFD->setInvalidDecl();
16802 
16803   if (T.isObjCGCWeak())
16804     Diag(Loc, diag::warn_attribute_weak_on_field);
16805 
16806   NewFD->setAccess(AS);
16807   return NewFD;
16808 }
16809 
16810 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16811   assert(FD);
16812   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16813 
16814   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16815     return false;
16816 
16817   QualType EltTy = Context.getBaseElementType(FD->getType());
16818   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16819     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16820     if (RDecl->getDefinition()) {
16821       // We check for copy constructors before constructors
16822       // because otherwise we'll never get complaints about
16823       // copy constructors.
16824 
16825       CXXSpecialMember member = CXXInvalid;
16826       // We're required to check for any non-trivial constructors. Since the
16827       // implicit default constructor is suppressed if there are any
16828       // user-declared constructors, we just need to check that there is a
16829       // trivial default constructor and a trivial copy constructor. (We don't
16830       // worry about move constructors here, since this is a C++98 check.)
16831       if (RDecl->hasNonTrivialCopyConstructor())
16832         member = CXXCopyConstructor;
16833       else if (!RDecl->hasTrivialDefaultConstructor())
16834         member = CXXDefaultConstructor;
16835       else if (RDecl->hasNonTrivialCopyAssignment())
16836         member = CXXCopyAssignment;
16837       else if (RDecl->hasNonTrivialDestructor())
16838         member = CXXDestructor;
16839 
16840       if (member != CXXInvalid) {
16841         if (!getLangOpts().CPlusPlus11 &&
16842             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16843           // Objective-C++ ARC: it is an error to have a non-trivial field of
16844           // a union. However, system headers in Objective-C programs
16845           // occasionally have Objective-C lifetime objects within unions,
16846           // and rather than cause the program to fail, we make those
16847           // members unavailable.
16848           SourceLocation Loc = FD->getLocation();
16849           if (getSourceManager().isInSystemHeader(Loc)) {
16850             if (!FD->hasAttr<UnavailableAttr>())
16851               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16852                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16853             return false;
16854           }
16855         }
16856 
16857         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16858                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16859                diag::err_illegal_union_or_anon_struct_member)
16860           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16861         DiagnoseNontrivial(RDecl, member);
16862         return !getLangOpts().CPlusPlus11;
16863       }
16864     }
16865   }
16866 
16867   return false;
16868 }
16869 
16870 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16871 ///  AST enum value.
16872 static ObjCIvarDecl::AccessControl
16873 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16874   switch (ivarVisibility) {
16875   default: llvm_unreachable("Unknown visitibility kind");
16876   case tok::objc_private: return ObjCIvarDecl::Private;
16877   case tok::objc_public: return ObjCIvarDecl::Public;
16878   case tok::objc_protected: return ObjCIvarDecl::Protected;
16879   case tok::objc_package: return ObjCIvarDecl::Package;
16880   }
16881 }
16882 
16883 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16884 /// in order to create an IvarDecl object for it.
16885 Decl *Sema::ActOnIvar(Scope *S,
16886                                 SourceLocation DeclStart,
16887                                 Declarator &D, Expr *BitfieldWidth,
16888                                 tok::ObjCKeywordKind Visibility) {
16889 
16890   IdentifierInfo *II = D.getIdentifier();
16891   Expr *BitWidth = (Expr*)BitfieldWidth;
16892   SourceLocation Loc = DeclStart;
16893   if (II) Loc = D.getIdentifierLoc();
16894 
16895   // FIXME: Unnamed fields can be handled in various different ways, for
16896   // example, unnamed unions inject all members into the struct namespace!
16897 
16898   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16899   QualType T = TInfo->getType();
16900 
16901   if (BitWidth) {
16902     // 6.7.2.1p3, 6.7.2.1p4
16903     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16904     if (!BitWidth)
16905       D.setInvalidType();
16906   } else {
16907     // Not a bitfield.
16908 
16909     // validate II.
16910 
16911   }
16912   if (T->isReferenceType()) {
16913     Diag(Loc, diag::err_ivar_reference_type);
16914     D.setInvalidType();
16915   }
16916   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16917   // than a variably modified type.
16918   else if (T->isVariablyModifiedType()) {
16919     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16920     D.setInvalidType();
16921   }
16922 
16923   // Get the visibility (access control) for this ivar.
16924   ObjCIvarDecl::AccessControl ac =
16925     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16926                                         : ObjCIvarDecl::None;
16927   // Must set ivar's DeclContext to its enclosing interface.
16928   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16929   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16930     return nullptr;
16931   ObjCContainerDecl *EnclosingContext;
16932   if (ObjCImplementationDecl *IMPDecl =
16933       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16934     if (LangOpts.ObjCRuntime.isFragile()) {
16935     // Case of ivar declared in an implementation. Context is that of its class.
16936       EnclosingContext = IMPDecl->getClassInterface();
16937       assert(EnclosingContext && "Implementation has no class interface!");
16938     }
16939     else
16940       EnclosingContext = EnclosingDecl;
16941   } else {
16942     if (ObjCCategoryDecl *CDecl =
16943         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16944       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16945         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16946         return nullptr;
16947       }
16948     }
16949     EnclosingContext = EnclosingDecl;
16950   }
16951 
16952   // Construct the decl.
16953   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16954                                              DeclStart, Loc, II, T,
16955                                              TInfo, ac, (Expr *)BitfieldWidth);
16956 
16957   if (II) {
16958     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16959                                            ForVisibleRedeclaration);
16960     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16961         && !isa<TagDecl>(PrevDecl)) {
16962       Diag(Loc, diag::err_duplicate_member) << II;
16963       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16964       NewID->setInvalidDecl();
16965     }
16966   }
16967 
16968   // Process attributes attached to the ivar.
16969   ProcessDeclAttributes(S, NewID, D);
16970 
16971   if (D.isInvalidType())
16972     NewID->setInvalidDecl();
16973 
16974   // In ARC, infer 'retaining' for ivars of retainable type.
16975   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16976     NewID->setInvalidDecl();
16977 
16978   if (D.getDeclSpec().isModulePrivateSpecified())
16979     NewID->setModulePrivate();
16980 
16981   if (II) {
16982     // FIXME: When interfaces are DeclContexts, we'll need to add
16983     // these to the interface.
16984     S->AddDecl(NewID);
16985     IdResolver.AddDecl(NewID);
16986   }
16987 
16988   if (LangOpts.ObjCRuntime.isNonFragile() &&
16989       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16990     Diag(Loc, diag::warn_ivars_in_interface);
16991 
16992   return NewID;
16993 }
16994 
16995 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16996 /// class and class extensions. For every class \@interface and class
16997 /// extension \@interface, if the last ivar is a bitfield of any type,
16998 /// then add an implicit `char :0` ivar to the end of that interface.
16999 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17000                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17001   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17002     return;
17003 
17004   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17005   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17006 
17007   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17008     return;
17009   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17010   if (!ID) {
17011     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17012       if (!CD->IsClassExtension())
17013         return;
17014     }
17015     // No need to add this to end of @implementation.
17016     else
17017       return;
17018   }
17019   // All conditions are met. Add a new bitfield to the tail end of ivars.
17020   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17021   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17022 
17023   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17024                               DeclLoc, DeclLoc, nullptr,
17025                               Context.CharTy,
17026                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17027                                                                DeclLoc),
17028                               ObjCIvarDecl::Private, BW,
17029                               true);
17030   AllIvarDecls.push_back(Ivar);
17031 }
17032 
17033 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17034                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17035                        SourceLocation RBrac,
17036                        const ParsedAttributesView &Attrs) {
17037   assert(EnclosingDecl && "missing record or interface decl");
17038 
17039   // If this is an Objective-C @implementation or category and we have
17040   // new fields here we should reset the layout of the interface since
17041   // it will now change.
17042   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17043     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17044     switch (DC->getKind()) {
17045     default: break;
17046     case Decl::ObjCCategory:
17047       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17048       break;
17049     case Decl::ObjCImplementation:
17050       Context.
17051         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17052       break;
17053     }
17054   }
17055 
17056   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17057   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17058 
17059   // Start counting up the number of named members; make sure to include
17060   // members of anonymous structs and unions in the total.
17061   unsigned NumNamedMembers = 0;
17062   if (Record) {
17063     for (const auto *I : Record->decls()) {
17064       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17065         if (IFD->getDeclName())
17066           ++NumNamedMembers;
17067     }
17068   }
17069 
17070   // Verify that all the fields are okay.
17071   SmallVector<FieldDecl*, 32> RecFields;
17072 
17073   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17074        i != end; ++i) {
17075     FieldDecl *FD = cast<FieldDecl>(*i);
17076 
17077     // Get the type for the field.
17078     const Type *FDTy = FD->getType().getTypePtr();
17079 
17080     if (!FD->isAnonymousStructOrUnion()) {
17081       // Remember all fields written by the user.
17082       RecFields.push_back(FD);
17083     }
17084 
17085     // If the field is already invalid for some reason, don't emit more
17086     // diagnostics about it.
17087     if (FD->isInvalidDecl()) {
17088       EnclosingDecl->setInvalidDecl();
17089       continue;
17090     }
17091 
17092     // C99 6.7.2.1p2:
17093     //   A structure or union shall not contain a member with
17094     //   incomplete or function type (hence, a structure shall not
17095     //   contain an instance of itself, but may contain a pointer to
17096     //   an instance of itself), except that the last member of a
17097     //   structure with more than one named member may have incomplete
17098     //   array type; such a structure (and any union containing,
17099     //   possibly recursively, a member that is such a structure)
17100     //   shall not be a member of a structure or an element of an
17101     //   array.
17102     bool IsLastField = (i + 1 == Fields.end());
17103     if (FDTy->isFunctionType()) {
17104       // Field declared as a function.
17105       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17106         << FD->getDeclName();
17107       FD->setInvalidDecl();
17108       EnclosingDecl->setInvalidDecl();
17109       continue;
17110     } else if (FDTy->isIncompleteArrayType() &&
17111                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17112       if (Record) {
17113         // Flexible array member.
17114         // Microsoft and g++ is more permissive regarding flexible array.
17115         // It will accept flexible array in union and also
17116         // as the sole element of a struct/class.
17117         unsigned DiagID = 0;
17118         if (!Record->isUnion() && !IsLastField) {
17119           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17120             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17121           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17122           FD->setInvalidDecl();
17123           EnclosingDecl->setInvalidDecl();
17124           continue;
17125         } else if (Record->isUnion())
17126           DiagID = getLangOpts().MicrosoftExt
17127                        ? diag::ext_flexible_array_union_ms
17128                        : getLangOpts().CPlusPlus
17129                              ? diag::ext_flexible_array_union_gnu
17130                              : diag::err_flexible_array_union;
17131         else if (NumNamedMembers < 1)
17132           DiagID = getLangOpts().MicrosoftExt
17133                        ? diag::ext_flexible_array_empty_aggregate_ms
17134                        : getLangOpts().CPlusPlus
17135                              ? diag::ext_flexible_array_empty_aggregate_gnu
17136                              : diag::err_flexible_array_empty_aggregate;
17137 
17138         if (DiagID)
17139           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17140                                           << Record->getTagKind();
17141         // While the layout of types that contain virtual bases is not specified
17142         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17143         // virtual bases after the derived members.  This would make a flexible
17144         // array member declared at the end of an object not adjacent to the end
17145         // of the type.
17146         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17147           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17148               << FD->getDeclName() << Record->getTagKind();
17149         if (!getLangOpts().C99)
17150           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17151             << FD->getDeclName() << Record->getTagKind();
17152 
17153         // If the element type has a non-trivial destructor, we would not
17154         // implicitly destroy the elements, so disallow it for now.
17155         //
17156         // FIXME: GCC allows this. We should probably either implicitly delete
17157         // the destructor of the containing class, or just allow this.
17158         QualType BaseElem = Context.getBaseElementType(FD->getType());
17159         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17160           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17161             << FD->getDeclName() << FD->getType();
17162           FD->setInvalidDecl();
17163           EnclosingDecl->setInvalidDecl();
17164           continue;
17165         }
17166         // Okay, we have a legal flexible array member at the end of the struct.
17167         Record->setHasFlexibleArrayMember(true);
17168       } else {
17169         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17170         // unless they are followed by another ivar. That check is done
17171         // elsewhere, after synthesized ivars are known.
17172       }
17173     } else if (!FDTy->isDependentType() &&
17174                RequireCompleteSizedType(
17175                    FD->getLocation(), FD->getType(),
17176                    diag::err_field_incomplete_or_sizeless)) {
17177       // Incomplete type
17178       FD->setInvalidDecl();
17179       EnclosingDecl->setInvalidDecl();
17180       continue;
17181     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17182       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17183         // A type which contains a flexible array member is considered to be a
17184         // flexible array member.
17185         Record->setHasFlexibleArrayMember(true);
17186         if (!Record->isUnion()) {
17187           // If this is a struct/class and this is not the last element, reject
17188           // it.  Note that GCC supports variable sized arrays in the middle of
17189           // structures.
17190           if (!IsLastField)
17191             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17192               << FD->getDeclName() << FD->getType();
17193           else {
17194             // We support flexible arrays at the end of structs in
17195             // other structs as an extension.
17196             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17197               << FD->getDeclName();
17198           }
17199         }
17200       }
17201       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17202           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17203                                  diag::err_abstract_type_in_decl,
17204                                  AbstractIvarType)) {
17205         // Ivars can not have abstract class types
17206         FD->setInvalidDecl();
17207       }
17208       if (Record && FDTTy->getDecl()->hasObjectMember())
17209         Record->setHasObjectMember(true);
17210       if (Record && FDTTy->getDecl()->hasVolatileMember())
17211         Record->setHasVolatileMember(true);
17212     } else if (FDTy->isObjCObjectType()) {
17213       /// A field cannot be an Objective-c object
17214       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17215         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17216       QualType T = Context.getObjCObjectPointerType(FD->getType());
17217       FD->setType(T);
17218     } else if (Record && Record->isUnion() &&
17219                FD->getType().hasNonTrivialObjCLifetime() &&
17220                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17221                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17222                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17223                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17224       // For backward compatibility, fields of C unions declared in system
17225       // headers that have non-trivial ObjC ownership qualifications are marked
17226       // as unavailable unless the qualifier is explicit and __strong. This can
17227       // break ABI compatibility between programs compiled with ARC and MRR, but
17228       // is a better option than rejecting programs using those unions under
17229       // ARC.
17230       FD->addAttr(UnavailableAttr::CreateImplicit(
17231           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17232           FD->getLocation()));
17233     } else if (getLangOpts().ObjC &&
17234                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17235                !Record->hasObjectMember()) {
17236       if (FD->getType()->isObjCObjectPointerType() ||
17237           FD->getType().isObjCGCStrong())
17238         Record->setHasObjectMember(true);
17239       else if (Context.getAsArrayType(FD->getType())) {
17240         QualType BaseType = Context.getBaseElementType(FD->getType());
17241         if (BaseType->isRecordType() &&
17242             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17243           Record->setHasObjectMember(true);
17244         else if (BaseType->isObjCObjectPointerType() ||
17245                  BaseType.isObjCGCStrong())
17246                Record->setHasObjectMember(true);
17247       }
17248     }
17249 
17250     if (Record && !getLangOpts().CPlusPlus &&
17251         !shouldIgnoreForRecordTriviality(FD)) {
17252       QualType FT = FD->getType();
17253       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17254         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17255         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17256             Record->isUnion())
17257           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17258       }
17259       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17260       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17261         Record->setNonTrivialToPrimitiveCopy(true);
17262         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17263           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17264       }
17265       if (FT.isDestructedType()) {
17266         Record->setNonTrivialToPrimitiveDestroy(true);
17267         Record->setParamDestroyedInCallee(true);
17268         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17269           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17270       }
17271 
17272       if (const auto *RT = FT->getAs<RecordType>()) {
17273         if (RT->getDecl()->getArgPassingRestrictions() ==
17274             RecordDecl::APK_CanNeverPassInRegs)
17275           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17276       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17277         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17278     }
17279 
17280     if (Record && FD->getType().isVolatileQualified())
17281       Record->setHasVolatileMember(true);
17282     // Keep track of the number of named members.
17283     if (FD->getIdentifier())
17284       ++NumNamedMembers;
17285   }
17286 
17287   // Okay, we successfully defined 'Record'.
17288   if (Record) {
17289     bool Completed = false;
17290     if (CXXRecord) {
17291       if (!CXXRecord->isInvalidDecl()) {
17292         // Set access bits correctly on the directly-declared conversions.
17293         for (CXXRecordDecl::conversion_iterator
17294                I = CXXRecord->conversion_begin(),
17295                E = CXXRecord->conversion_end(); I != E; ++I)
17296           I.setAccess((*I)->getAccess());
17297       }
17298 
17299       // Add any implicitly-declared members to this class.
17300       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17301 
17302       if (!CXXRecord->isDependentType()) {
17303         if (!CXXRecord->isInvalidDecl()) {
17304           // If we have virtual base classes, we may end up finding multiple
17305           // final overriders for a given virtual function. Check for this
17306           // problem now.
17307           if (CXXRecord->getNumVBases()) {
17308             CXXFinalOverriderMap FinalOverriders;
17309             CXXRecord->getFinalOverriders(FinalOverriders);
17310 
17311             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17312                                              MEnd = FinalOverriders.end();
17313                  M != MEnd; ++M) {
17314               for (OverridingMethods::iterator SO = M->second.begin(),
17315                                             SOEnd = M->second.end();
17316                    SO != SOEnd; ++SO) {
17317                 assert(SO->second.size() > 0 &&
17318                        "Virtual function without overriding functions?");
17319                 if (SO->second.size() == 1)
17320                   continue;
17321 
17322                 // C++ [class.virtual]p2:
17323                 //   In a derived class, if a virtual member function of a base
17324                 //   class subobject has more than one final overrider the
17325                 //   program is ill-formed.
17326                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17327                   << (const NamedDecl *)M->first << Record;
17328                 Diag(M->first->getLocation(),
17329                      diag::note_overridden_virtual_function);
17330                 for (OverridingMethods::overriding_iterator
17331                           OM = SO->second.begin(),
17332                        OMEnd = SO->second.end();
17333                      OM != OMEnd; ++OM)
17334                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17335                     << (const NamedDecl *)M->first << OM->Method->getParent();
17336 
17337                 Record->setInvalidDecl();
17338               }
17339             }
17340             CXXRecord->completeDefinition(&FinalOverriders);
17341             Completed = true;
17342           }
17343         }
17344       }
17345     }
17346 
17347     if (!Completed)
17348       Record->completeDefinition();
17349 
17350     // Handle attributes before checking the layout.
17351     ProcessDeclAttributeList(S, Record, Attrs);
17352 
17353     // We may have deferred checking for a deleted destructor. Check now.
17354     if (CXXRecord) {
17355       auto *Dtor = CXXRecord->getDestructor();
17356       if (Dtor && Dtor->isImplicit() &&
17357           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17358         CXXRecord->setImplicitDestructorIsDeleted();
17359         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17360       }
17361     }
17362 
17363     if (Record->hasAttrs()) {
17364       CheckAlignasUnderalignment(Record);
17365 
17366       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17367         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17368                                            IA->getRange(), IA->getBestCase(),
17369                                            IA->getInheritanceModel());
17370     }
17371 
17372     // Check if the structure/union declaration is a type that can have zero
17373     // size in C. For C this is a language extension, for C++ it may cause
17374     // compatibility problems.
17375     bool CheckForZeroSize;
17376     if (!getLangOpts().CPlusPlus) {
17377       CheckForZeroSize = true;
17378     } else {
17379       // For C++ filter out types that cannot be referenced in C code.
17380       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17381       CheckForZeroSize =
17382           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17383           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17384           CXXRecord->isCLike();
17385     }
17386     if (CheckForZeroSize) {
17387       bool ZeroSize = true;
17388       bool IsEmpty = true;
17389       unsigned NonBitFields = 0;
17390       for (RecordDecl::field_iterator I = Record->field_begin(),
17391                                       E = Record->field_end();
17392            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17393         IsEmpty = false;
17394         if (I->isUnnamedBitfield()) {
17395           if (!I->isZeroLengthBitField(Context))
17396             ZeroSize = false;
17397         } else {
17398           ++NonBitFields;
17399           QualType FieldType = I->getType();
17400           if (FieldType->isIncompleteType() ||
17401               !Context.getTypeSizeInChars(FieldType).isZero())
17402             ZeroSize = false;
17403         }
17404       }
17405 
17406       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17407       // allowed in C++, but warn if its declaration is inside
17408       // extern "C" block.
17409       if (ZeroSize) {
17410         Diag(RecLoc, getLangOpts().CPlusPlus ?
17411                          diag::warn_zero_size_struct_union_in_extern_c :
17412                          diag::warn_zero_size_struct_union_compat)
17413           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17414       }
17415 
17416       // Structs without named members are extension in C (C99 6.7.2.1p7),
17417       // but are accepted by GCC.
17418       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17419         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17420                                diag::ext_no_named_members_in_struct_union)
17421           << Record->isUnion();
17422       }
17423     }
17424   } else {
17425     ObjCIvarDecl **ClsFields =
17426       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17427     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17428       ID->setEndOfDefinitionLoc(RBrac);
17429       // Add ivar's to class's DeclContext.
17430       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17431         ClsFields[i]->setLexicalDeclContext(ID);
17432         ID->addDecl(ClsFields[i]);
17433       }
17434       // Must enforce the rule that ivars in the base classes may not be
17435       // duplicates.
17436       if (ID->getSuperClass())
17437         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17438     } else if (ObjCImplementationDecl *IMPDecl =
17439                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17440       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17441       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17442         // Ivar declared in @implementation never belongs to the implementation.
17443         // Only it is in implementation's lexical context.
17444         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17445       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17446       IMPDecl->setIvarLBraceLoc(LBrac);
17447       IMPDecl->setIvarRBraceLoc(RBrac);
17448     } else if (ObjCCategoryDecl *CDecl =
17449                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17450       // case of ivars in class extension; all other cases have been
17451       // reported as errors elsewhere.
17452       // FIXME. Class extension does not have a LocEnd field.
17453       // CDecl->setLocEnd(RBrac);
17454       // Add ivar's to class extension's DeclContext.
17455       // Diagnose redeclaration of private ivars.
17456       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17457       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17458         if (IDecl) {
17459           if (const ObjCIvarDecl *ClsIvar =
17460               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17461             Diag(ClsFields[i]->getLocation(),
17462                  diag::err_duplicate_ivar_declaration);
17463             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17464             continue;
17465           }
17466           for (const auto *Ext : IDecl->known_extensions()) {
17467             if (const ObjCIvarDecl *ClsExtIvar
17468                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17469               Diag(ClsFields[i]->getLocation(),
17470                    diag::err_duplicate_ivar_declaration);
17471               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17472               continue;
17473             }
17474           }
17475         }
17476         ClsFields[i]->setLexicalDeclContext(CDecl);
17477         CDecl->addDecl(ClsFields[i]);
17478       }
17479       CDecl->setIvarLBraceLoc(LBrac);
17480       CDecl->setIvarRBraceLoc(RBrac);
17481     }
17482   }
17483 }
17484 
17485 /// Determine whether the given integral value is representable within
17486 /// the given type T.
17487 static bool isRepresentableIntegerValue(ASTContext &Context,
17488                                         llvm::APSInt &Value,
17489                                         QualType T) {
17490   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17491          "Integral type required!");
17492   unsigned BitWidth = Context.getIntWidth(T);
17493 
17494   if (Value.isUnsigned() || Value.isNonNegative()) {
17495     if (T->isSignedIntegerOrEnumerationType())
17496       --BitWidth;
17497     return Value.getActiveBits() <= BitWidth;
17498   }
17499   return Value.getMinSignedBits() <= BitWidth;
17500 }
17501 
17502 // Given an integral type, return the next larger integral type
17503 // (or a NULL type of no such type exists).
17504 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17505   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17506   // enum checking below.
17507   assert((T->isIntegralType(Context) ||
17508          T->isEnumeralType()) && "Integral type required!");
17509   const unsigned NumTypes = 4;
17510   QualType SignedIntegralTypes[NumTypes] = {
17511     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17512   };
17513   QualType UnsignedIntegralTypes[NumTypes] = {
17514     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17515     Context.UnsignedLongLongTy
17516   };
17517 
17518   unsigned BitWidth = Context.getTypeSize(T);
17519   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17520                                                         : UnsignedIntegralTypes;
17521   for (unsigned I = 0; I != NumTypes; ++I)
17522     if (Context.getTypeSize(Types[I]) > BitWidth)
17523       return Types[I];
17524 
17525   return QualType();
17526 }
17527 
17528 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17529                                           EnumConstantDecl *LastEnumConst,
17530                                           SourceLocation IdLoc,
17531                                           IdentifierInfo *Id,
17532                                           Expr *Val) {
17533   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17534   llvm::APSInt EnumVal(IntWidth);
17535   QualType EltTy;
17536 
17537   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17538     Val = nullptr;
17539 
17540   if (Val)
17541     Val = DefaultLvalueConversion(Val).get();
17542 
17543   if (Val) {
17544     if (Enum->isDependentType() || Val->isTypeDependent())
17545       EltTy = Context.DependentTy;
17546     else {
17547       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17548         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17549         // constant-expression in the enumerator-definition shall be a converted
17550         // constant expression of the underlying type.
17551         EltTy = Enum->getIntegerType();
17552         ExprResult Converted =
17553           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17554                                            CCEK_Enumerator);
17555         if (Converted.isInvalid())
17556           Val = nullptr;
17557         else
17558           Val = Converted.get();
17559       } else if (!Val->isValueDependent() &&
17560                  !(Val = VerifyIntegerConstantExpression(Val,
17561                                                          &EnumVal).get())) {
17562         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17563       } else {
17564         if (Enum->isComplete()) {
17565           EltTy = Enum->getIntegerType();
17566 
17567           // In Obj-C and Microsoft mode, require the enumeration value to be
17568           // representable in the underlying type of the enumeration. In C++11,
17569           // we perform a non-narrowing conversion as part of converted constant
17570           // expression checking.
17571           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17572             if (Context.getTargetInfo()
17573                     .getTriple()
17574                     .isWindowsMSVCEnvironment()) {
17575               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17576             } else {
17577               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17578             }
17579           }
17580 
17581           // Cast to the underlying type.
17582           Val = ImpCastExprToType(Val, EltTy,
17583                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17584                                                          : CK_IntegralCast)
17585                     .get();
17586         } else if (getLangOpts().CPlusPlus) {
17587           // C++11 [dcl.enum]p5:
17588           //   If the underlying type is not fixed, the type of each enumerator
17589           //   is the type of its initializing value:
17590           //     - If an initializer is specified for an enumerator, the
17591           //       initializing value has the same type as the expression.
17592           EltTy = Val->getType();
17593         } else {
17594           // C99 6.7.2.2p2:
17595           //   The expression that defines the value of an enumeration constant
17596           //   shall be an integer constant expression that has a value
17597           //   representable as an int.
17598 
17599           // Complain if the value is not representable in an int.
17600           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17601             Diag(IdLoc, diag::ext_enum_value_not_int)
17602               << EnumVal.toString(10) << Val->getSourceRange()
17603               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17604           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17605             // Force the type of the expression to 'int'.
17606             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17607           }
17608           EltTy = Val->getType();
17609         }
17610       }
17611     }
17612   }
17613 
17614   if (!Val) {
17615     if (Enum->isDependentType())
17616       EltTy = Context.DependentTy;
17617     else if (!LastEnumConst) {
17618       // C++0x [dcl.enum]p5:
17619       //   If the underlying type is not fixed, the type of each enumerator
17620       //   is the type of its initializing value:
17621       //     - If no initializer is specified for the first enumerator, the
17622       //       initializing value has an unspecified integral type.
17623       //
17624       // GCC uses 'int' for its unspecified integral type, as does
17625       // C99 6.7.2.2p3.
17626       if (Enum->isFixed()) {
17627         EltTy = Enum->getIntegerType();
17628       }
17629       else {
17630         EltTy = Context.IntTy;
17631       }
17632     } else {
17633       // Assign the last value + 1.
17634       EnumVal = LastEnumConst->getInitVal();
17635       ++EnumVal;
17636       EltTy = LastEnumConst->getType();
17637 
17638       // Check for overflow on increment.
17639       if (EnumVal < LastEnumConst->getInitVal()) {
17640         // C++0x [dcl.enum]p5:
17641         //   If the underlying type is not fixed, the type of each enumerator
17642         //   is the type of its initializing value:
17643         //
17644         //     - Otherwise the type of the initializing value is the same as
17645         //       the type of the initializing value of the preceding enumerator
17646         //       unless the incremented value is not representable in that type,
17647         //       in which case the type is an unspecified integral type
17648         //       sufficient to contain the incremented value. If no such type
17649         //       exists, the program is ill-formed.
17650         QualType T = getNextLargerIntegralType(Context, EltTy);
17651         if (T.isNull() || Enum->isFixed()) {
17652           // There is no integral type larger enough to represent this
17653           // value. Complain, then allow the value to wrap around.
17654           EnumVal = LastEnumConst->getInitVal();
17655           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17656           ++EnumVal;
17657           if (Enum->isFixed())
17658             // When the underlying type is fixed, this is ill-formed.
17659             Diag(IdLoc, diag::err_enumerator_wrapped)
17660               << EnumVal.toString(10)
17661               << EltTy;
17662           else
17663             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17664               << EnumVal.toString(10);
17665         } else {
17666           EltTy = T;
17667         }
17668 
17669         // Retrieve the last enumerator's value, extent that type to the
17670         // type that is supposed to be large enough to represent the incremented
17671         // value, then increment.
17672         EnumVal = LastEnumConst->getInitVal();
17673         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17674         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17675         ++EnumVal;
17676 
17677         // If we're not in C++, diagnose the overflow of enumerator values,
17678         // which in C99 means that the enumerator value is not representable in
17679         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17680         // permits enumerator values that are representable in some larger
17681         // integral type.
17682         if (!getLangOpts().CPlusPlus && !T.isNull())
17683           Diag(IdLoc, diag::warn_enum_value_overflow);
17684       } else if (!getLangOpts().CPlusPlus &&
17685                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17686         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17687         Diag(IdLoc, diag::ext_enum_value_not_int)
17688           << EnumVal.toString(10) << 1;
17689       }
17690     }
17691   }
17692 
17693   if (!EltTy->isDependentType()) {
17694     // Make the enumerator value match the signedness and size of the
17695     // enumerator's type.
17696     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17697     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17698   }
17699 
17700   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17701                                   Val, EnumVal);
17702 }
17703 
17704 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17705                                                 SourceLocation IILoc) {
17706   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17707       !getLangOpts().CPlusPlus)
17708     return SkipBodyInfo();
17709 
17710   // We have an anonymous enum definition. Look up the first enumerator to
17711   // determine if we should merge the definition with an existing one and
17712   // skip the body.
17713   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17714                                          forRedeclarationInCurContext());
17715   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17716   if (!PrevECD)
17717     return SkipBodyInfo();
17718 
17719   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17720   NamedDecl *Hidden;
17721   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17722     SkipBodyInfo Skip;
17723     Skip.Previous = Hidden;
17724     return Skip;
17725   }
17726 
17727   return SkipBodyInfo();
17728 }
17729 
17730 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17731                               SourceLocation IdLoc, IdentifierInfo *Id,
17732                               const ParsedAttributesView &Attrs,
17733                               SourceLocation EqualLoc, Expr *Val) {
17734   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17735   EnumConstantDecl *LastEnumConst =
17736     cast_or_null<EnumConstantDecl>(lastEnumConst);
17737 
17738   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17739   // we find one that is.
17740   S = getNonFieldDeclScope(S);
17741 
17742   // Verify that there isn't already something declared with this name in this
17743   // scope.
17744   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17745   LookupName(R, S);
17746   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17747 
17748   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17749     // Maybe we will complain about the shadowed template parameter.
17750     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17751     // Just pretend that we didn't see the previous declaration.
17752     PrevDecl = nullptr;
17753   }
17754 
17755   // C++ [class.mem]p15:
17756   // If T is the name of a class, then each of the following shall have a name
17757   // different from T:
17758   // - every enumerator of every member of class T that is an unscoped
17759   // enumerated type
17760   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17761     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17762                             DeclarationNameInfo(Id, IdLoc));
17763 
17764   EnumConstantDecl *New =
17765     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17766   if (!New)
17767     return nullptr;
17768 
17769   if (PrevDecl) {
17770     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17771       // Check for other kinds of shadowing not already handled.
17772       CheckShadow(New, PrevDecl, R);
17773     }
17774 
17775     // When in C++, we may get a TagDecl with the same name; in this case the
17776     // enum constant will 'hide' the tag.
17777     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17778            "Received TagDecl when not in C++!");
17779     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17780       if (isa<EnumConstantDecl>(PrevDecl))
17781         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17782       else
17783         Diag(IdLoc, diag::err_redefinition) << Id;
17784       notePreviousDefinition(PrevDecl, IdLoc);
17785       return nullptr;
17786     }
17787   }
17788 
17789   // Process attributes.
17790   ProcessDeclAttributeList(S, New, Attrs);
17791   AddPragmaAttributes(S, New);
17792 
17793   // Register this decl in the current scope stack.
17794   New->setAccess(TheEnumDecl->getAccess());
17795   PushOnScopeChains(New, S);
17796 
17797   ActOnDocumentableDecl(New);
17798 
17799   return New;
17800 }
17801 
17802 // Returns true when the enum initial expression does not trigger the
17803 // duplicate enum warning.  A few common cases are exempted as follows:
17804 // Element2 = Element1
17805 // Element2 = Element1 + 1
17806 // Element2 = Element1 - 1
17807 // Where Element2 and Element1 are from the same enum.
17808 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17809   Expr *InitExpr = ECD->getInitExpr();
17810   if (!InitExpr)
17811     return true;
17812   InitExpr = InitExpr->IgnoreImpCasts();
17813 
17814   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17815     if (!BO->isAdditiveOp())
17816       return true;
17817     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17818     if (!IL)
17819       return true;
17820     if (IL->getValue() != 1)
17821       return true;
17822 
17823     InitExpr = BO->getLHS();
17824   }
17825 
17826   // This checks if the elements are from the same enum.
17827   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17828   if (!DRE)
17829     return true;
17830 
17831   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17832   if (!EnumConstant)
17833     return true;
17834 
17835   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17836       Enum)
17837     return true;
17838 
17839   return false;
17840 }
17841 
17842 // Emits a warning when an element is implicitly set a value that
17843 // a previous element has already been set to.
17844 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17845                                         EnumDecl *Enum, QualType EnumType) {
17846   // Avoid anonymous enums
17847   if (!Enum->getIdentifier())
17848     return;
17849 
17850   // Only check for small enums.
17851   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17852     return;
17853 
17854   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17855     return;
17856 
17857   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17858   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17859 
17860   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17861 
17862   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17863   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17864 
17865   // Use int64_t as a key to avoid needing special handling for map keys.
17866   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17867     llvm::APSInt Val = D->getInitVal();
17868     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17869   };
17870 
17871   DuplicatesVector DupVector;
17872   ValueToVectorMap EnumMap;
17873 
17874   // Populate the EnumMap with all values represented by enum constants without
17875   // an initializer.
17876   for (auto *Element : Elements) {
17877     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17878 
17879     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17880     // this constant.  Skip this enum since it may be ill-formed.
17881     if (!ECD) {
17882       return;
17883     }
17884 
17885     // Constants with initalizers are handled in the next loop.
17886     if (ECD->getInitExpr())
17887       continue;
17888 
17889     // Duplicate values are handled in the next loop.
17890     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17891   }
17892 
17893   if (EnumMap.size() == 0)
17894     return;
17895 
17896   // Create vectors for any values that has duplicates.
17897   for (auto *Element : Elements) {
17898     // The last loop returned if any constant was null.
17899     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17900     if (!ValidDuplicateEnum(ECD, Enum))
17901       continue;
17902 
17903     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17904     if (Iter == EnumMap.end())
17905       continue;
17906 
17907     DeclOrVector& Entry = Iter->second;
17908     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17909       // Ensure constants are different.
17910       if (D == ECD)
17911         continue;
17912 
17913       // Create new vector and push values onto it.
17914       auto Vec = std::make_unique<ECDVector>();
17915       Vec->push_back(D);
17916       Vec->push_back(ECD);
17917 
17918       // Update entry to point to the duplicates vector.
17919       Entry = Vec.get();
17920 
17921       // Store the vector somewhere we can consult later for quick emission of
17922       // diagnostics.
17923       DupVector.emplace_back(std::move(Vec));
17924       continue;
17925     }
17926 
17927     ECDVector *Vec = Entry.get<ECDVector*>();
17928     // Make sure constants are not added more than once.
17929     if (*Vec->begin() == ECD)
17930       continue;
17931 
17932     Vec->push_back(ECD);
17933   }
17934 
17935   // Emit diagnostics.
17936   for (const auto &Vec : DupVector) {
17937     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17938 
17939     // Emit warning for one enum constant.
17940     auto *FirstECD = Vec->front();
17941     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17942       << FirstECD << FirstECD->getInitVal().toString(10)
17943       << FirstECD->getSourceRange();
17944 
17945     // Emit one note for each of the remaining enum constants with
17946     // the same value.
17947     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17948       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17949         << ECD << ECD->getInitVal().toString(10)
17950         << ECD->getSourceRange();
17951   }
17952 }
17953 
17954 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17955                              bool AllowMask) const {
17956   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17957   assert(ED->isCompleteDefinition() && "expected enum definition");
17958 
17959   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17960   llvm::APInt &FlagBits = R.first->second;
17961 
17962   if (R.second) {
17963     for (auto *E : ED->enumerators()) {
17964       const auto &EVal = E->getInitVal();
17965       // Only single-bit enumerators introduce new flag values.
17966       if (EVal.isPowerOf2())
17967         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17968     }
17969   }
17970 
17971   // A value is in a flag enum if either its bits are a subset of the enum's
17972   // flag bits (the first condition) or we are allowing masks and the same is
17973   // true of its complement (the second condition). When masks are allowed, we
17974   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17975   //
17976   // While it's true that any value could be used as a mask, the assumption is
17977   // that a mask will have all of the insignificant bits set. Anything else is
17978   // likely a logic error.
17979   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17980   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17981 }
17982 
17983 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17984                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17985                          const ParsedAttributesView &Attrs) {
17986   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17987   QualType EnumType = Context.getTypeDeclType(Enum);
17988 
17989   ProcessDeclAttributeList(S, Enum, Attrs);
17990 
17991   if (Enum->isDependentType()) {
17992     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17993       EnumConstantDecl *ECD =
17994         cast_or_null<EnumConstantDecl>(Elements[i]);
17995       if (!ECD) continue;
17996 
17997       ECD->setType(EnumType);
17998     }
17999 
18000     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18001     return;
18002   }
18003 
18004   // TODO: If the result value doesn't fit in an int, it must be a long or long
18005   // long value.  ISO C does not support this, but GCC does as an extension,
18006   // emit a warning.
18007   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18008   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18009   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18010 
18011   // Verify that all the values are okay, compute the size of the values, and
18012   // reverse the list.
18013   unsigned NumNegativeBits = 0;
18014   unsigned NumPositiveBits = 0;
18015 
18016   // Keep track of whether all elements have type int.
18017   bool AllElementsInt = true;
18018 
18019   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18020     EnumConstantDecl *ECD =
18021       cast_or_null<EnumConstantDecl>(Elements[i]);
18022     if (!ECD) continue;  // Already issued a diagnostic.
18023 
18024     const llvm::APSInt &InitVal = ECD->getInitVal();
18025 
18026     // Keep track of the size of positive and negative values.
18027     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18028       NumPositiveBits = std::max(NumPositiveBits,
18029                                  (unsigned)InitVal.getActiveBits());
18030     else
18031       NumNegativeBits = std::max(NumNegativeBits,
18032                                  (unsigned)InitVal.getMinSignedBits());
18033 
18034     // Keep track of whether every enum element has type int (very common).
18035     if (AllElementsInt)
18036       AllElementsInt = ECD->getType() == Context.IntTy;
18037   }
18038 
18039   // Figure out the type that should be used for this enum.
18040   QualType BestType;
18041   unsigned BestWidth;
18042 
18043   // C++0x N3000 [conv.prom]p3:
18044   //   An rvalue of an unscoped enumeration type whose underlying
18045   //   type is not fixed can be converted to an rvalue of the first
18046   //   of the following types that can represent all the values of
18047   //   the enumeration: int, unsigned int, long int, unsigned long
18048   //   int, long long int, or unsigned long long int.
18049   // C99 6.4.4.3p2:
18050   //   An identifier declared as an enumeration constant has type int.
18051   // The C99 rule is modified by a gcc extension
18052   QualType BestPromotionType;
18053 
18054   bool Packed = Enum->hasAttr<PackedAttr>();
18055   // -fshort-enums is the equivalent to specifying the packed attribute on all
18056   // enum definitions.
18057   if (LangOpts.ShortEnums)
18058     Packed = true;
18059 
18060   // If the enum already has a type because it is fixed or dictated by the
18061   // target, promote that type instead of analyzing the enumerators.
18062   if (Enum->isComplete()) {
18063     BestType = Enum->getIntegerType();
18064     if (BestType->isPromotableIntegerType())
18065       BestPromotionType = Context.getPromotedIntegerType(BestType);
18066     else
18067       BestPromotionType = BestType;
18068 
18069     BestWidth = Context.getIntWidth(BestType);
18070   }
18071   else if (NumNegativeBits) {
18072     // If there is a negative value, figure out the smallest integer type (of
18073     // int/long/longlong) that fits.
18074     // If it's packed, check also if it fits a char or a short.
18075     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18076       BestType = Context.SignedCharTy;
18077       BestWidth = CharWidth;
18078     } else if (Packed && NumNegativeBits <= ShortWidth &&
18079                NumPositiveBits < ShortWidth) {
18080       BestType = Context.ShortTy;
18081       BestWidth = ShortWidth;
18082     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18083       BestType = Context.IntTy;
18084       BestWidth = IntWidth;
18085     } else {
18086       BestWidth = Context.getTargetInfo().getLongWidth();
18087 
18088       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18089         BestType = Context.LongTy;
18090       } else {
18091         BestWidth = Context.getTargetInfo().getLongLongWidth();
18092 
18093         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18094           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18095         BestType = Context.LongLongTy;
18096       }
18097     }
18098     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18099   } else {
18100     // If there is no negative value, figure out the smallest type that fits
18101     // all of the enumerator values.
18102     // If it's packed, check also if it fits a char or a short.
18103     if (Packed && NumPositiveBits <= CharWidth) {
18104       BestType = Context.UnsignedCharTy;
18105       BestPromotionType = Context.IntTy;
18106       BestWidth = CharWidth;
18107     } else if (Packed && NumPositiveBits <= ShortWidth) {
18108       BestType = Context.UnsignedShortTy;
18109       BestPromotionType = Context.IntTy;
18110       BestWidth = ShortWidth;
18111     } else if (NumPositiveBits <= IntWidth) {
18112       BestType = Context.UnsignedIntTy;
18113       BestWidth = IntWidth;
18114       BestPromotionType
18115         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18116                            ? Context.UnsignedIntTy : Context.IntTy;
18117     } else if (NumPositiveBits <=
18118                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18119       BestType = Context.UnsignedLongTy;
18120       BestPromotionType
18121         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18122                            ? Context.UnsignedLongTy : Context.LongTy;
18123     } else {
18124       BestWidth = Context.getTargetInfo().getLongLongWidth();
18125       assert(NumPositiveBits <= BestWidth &&
18126              "How could an initializer get larger than ULL?");
18127       BestType = Context.UnsignedLongLongTy;
18128       BestPromotionType
18129         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18130                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18131     }
18132   }
18133 
18134   // Loop over all of the enumerator constants, changing their types to match
18135   // the type of the enum if needed.
18136   for (auto *D : Elements) {
18137     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18138     if (!ECD) continue;  // Already issued a diagnostic.
18139 
18140     // Standard C says the enumerators have int type, but we allow, as an
18141     // extension, the enumerators to be larger than int size.  If each
18142     // enumerator value fits in an int, type it as an int, otherwise type it the
18143     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18144     // that X has type 'int', not 'unsigned'.
18145 
18146     // Determine whether the value fits into an int.
18147     llvm::APSInt InitVal = ECD->getInitVal();
18148 
18149     // If it fits into an integer type, force it.  Otherwise force it to match
18150     // the enum decl type.
18151     QualType NewTy;
18152     unsigned NewWidth;
18153     bool NewSign;
18154     if (!getLangOpts().CPlusPlus &&
18155         !Enum->isFixed() &&
18156         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18157       NewTy = Context.IntTy;
18158       NewWidth = IntWidth;
18159       NewSign = true;
18160     } else if (ECD->getType() == BestType) {
18161       // Already the right type!
18162       if (getLangOpts().CPlusPlus)
18163         // C++ [dcl.enum]p4: Following the closing brace of an
18164         // enum-specifier, each enumerator has the type of its
18165         // enumeration.
18166         ECD->setType(EnumType);
18167       continue;
18168     } else {
18169       NewTy = BestType;
18170       NewWidth = BestWidth;
18171       NewSign = BestType->isSignedIntegerOrEnumerationType();
18172     }
18173 
18174     // Adjust the APSInt value.
18175     InitVal = InitVal.extOrTrunc(NewWidth);
18176     InitVal.setIsSigned(NewSign);
18177     ECD->setInitVal(InitVal);
18178 
18179     // Adjust the Expr initializer and type.
18180     if (ECD->getInitExpr() &&
18181         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18182       ECD->setInitExpr(ImplicitCastExpr::Create(
18183           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18184           /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18185     if (getLangOpts().CPlusPlus)
18186       // C++ [dcl.enum]p4: Following the closing brace of an
18187       // enum-specifier, each enumerator has the type of its
18188       // enumeration.
18189       ECD->setType(EnumType);
18190     else
18191       ECD->setType(NewTy);
18192   }
18193 
18194   Enum->completeDefinition(BestType, BestPromotionType,
18195                            NumPositiveBits, NumNegativeBits);
18196 
18197   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18198 
18199   if (Enum->isClosedFlag()) {
18200     for (Decl *D : Elements) {
18201       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18202       if (!ECD) continue;  // Already issued a diagnostic.
18203 
18204       llvm::APSInt InitVal = ECD->getInitVal();
18205       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18206           !IsValueInFlagEnum(Enum, InitVal, true))
18207         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18208           << ECD << Enum;
18209     }
18210   }
18211 
18212   // Now that the enum type is defined, ensure it's not been underaligned.
18213   if (Enum->hasAttrs())
18214     CheckAlignasUnderalignment(Enum);
18215 }
18216 
18217 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18218                                   SourceLocation StartLoc,
18219                                   SourceLocation EndLoc) {
18220   StringLiteral *AsmString = cast<StringLiteral>(expr);
18221 
18222   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18223                                                    AsmString, StartLoc,
18224                                                    EndLoc);
18225   CurContext->addDecl(New);
18226   return New;
18227 }
18228 
18229 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18230                                       IdentifierInfo* AliasName,
18231                                       SourceLocation PragmaLoc,
18232                                       SourceLocation NameLoc,
18233                                       SourceLocation AliasNameLoc) {
18234   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18235                                          LookupOrdinaryName);
18236   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18237                            AttributeCommonInfo::AS_Pragma);
18238   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18239       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18240 
18241   // If a declaration that:
18242   // 1) declares a function or a variable
18243   // 2) has external linkage
18244   // already exists, add a label attribute to it.
18245   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18246     if (isDeclExternC(PrevDecl))
18247       PrevDecl->addAttr(Attr);
18248     else
18249       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18250           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18251   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18252   } else
18253     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18254 }
18255 
18256 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18257                              SourceLocation PragmaLoc,
18258                              SourceLocation NameLoc) {
18259   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18260 
18261   if (PrevDecl) {
18262     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18263   } else {
18264     (void)WeakUndeclaredIdentifiers.insert(
18265       std::pair<IdentifierInfo*,WeakInfo>
18266         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18267   }
18268 }
18269 
18270 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18271                                 IdentifierInfo* AliasName,
18272                                 SourceLocation PragmaLoc,
18273                                 SourceLocation NameLoc,
18274                                 SourceLocation AliasNameLoc) {
18275   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18276                                     LookupOrdinaryName);
18277   WeakInfo W = WeakInfo(Name, NameLoc);
18278 
18279   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18280     if (!PrevDecl->hasAttr<AliasAttr>())
18281       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18282         DeclApplyPragmaWeak(TUScope, ND, W);
18283   } else {
18284     (void)WeakUndeclaredIdentifiers.insert(
18285       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18286   }
18287 }
18288 
18289 Decl *Sema::getObjCDeclContext() const {
18290   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18291 }
18292 
18293 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18294                                                      bool Final) {
18295   // SYCL functions can be template, so we check if they have appropriate
18296   // attribute prior to checking if it is a template.
18297   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18298     return FunctionEmissionStatus::Emitted;
18299 
18300   // Templates are emitted when they're instantiated.
18301   if (FD->isDependentContext())
18302     return FunctionEmissionStatus::TemplateDiscarded;
18303 
18304   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18305   if (LangOpts.OpenMPIsDevice) {
18306     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18307         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18308     if (DevTy.hasValue()) {
18309       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18310         OMPES = FunctionEmissionStatus::OMPDiscarded;
18311       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18312                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18313         OMPES = FunctionEmissionStatus::Emitted;
18314       }
18315     }
18316   } else if (LangOpts.OpenMP) {
18317     // In OpenMP 4.5 all the functions are host functions.
18318     if (LangOpts.OpenMP <= 45) {
18319       OMPES = FunctionEmissionStatus::Emitted;
18320     } else {
18321       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18322           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18323       // In OpenMP 5.0 or above, DevTy may be changed later by
18324       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18325       // having no value does not imply host. The emission status will be
18326       // checked again at the end of compilation unit.
18327       if (DevTy.hasValue()) {
18328         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18329           OMPES = FunctionEmissionStatus::OMPDiscarded;
18330         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18331                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18332           OMPES = FunctionEmissionStatus::Emitted;
18333       } else if (Final)
18334         OMPES = FunctionEmissionStatus::Emitted;
18335     }
18336   }
18337   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18338       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18339     return OMPES;
18340 
18341   if (LangOpts.CUDA) {
18342     // When compiling for device, host functions are never emitted.  Similarly,
18343     // when compiling for host, device and global functions are never emitted.
18344     // (Technically, we do emit a host-side stub for global functions, but this
18345     // doesn't count for our purposes here.)
18346     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18347     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18348       return FunctionEmissionStatus::CUDADiscarded;
18349     if (!LangOpts.CUDAIsDevice &&
18350         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18351       return FunctionEmissionStatus::CUDADiscarded;
18352 
18353     // Check whether this function is externally visible -- if so, it's
18354     // known-emitted.
18355     //
18356     // We have to check the GVA linkage of the function's *definition* -- if we
18357     // only have a declaration, we don't know whether or not the function will
18358     // be emitted, because (say) the definition could include "inline".
18359     FunctionDecl *Def = FD->getDefinition();
18360 
18361     if (Def &&
18362         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18363         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18364       return FunctionEmissionStatus::Emitted;
18365   }
18366 
18367   // Otherwise, the function is known-emitted if it's in our set of
18368   // known-emitted functions.
18369   return FunctionEmissionStatus::Unknown;
18370 }
18371 
18372 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18373   // Host-side references to a __global__ function refer to the stub, so the
18374   // function itself is never emitted and therefore should not be marked.
18375   // If we have host fn calls kernel fn calls host+device, the HD function
18376   // does not get instantiated on the host. We model this by omitting at the
18377   // call to the kernel from the callgraph. This ensures that, when compiling
18378   // for host, only HD functions actually called from the host get marked as
18379   // known-emitted.
18380   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18381          IdentifyCUDATarget(Callee) == CFT_Global;
18382 }
18383