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 /// Looks up the declaration of "struct objc_super" and
2039 /// saves it for later use in building builtin declaration of
2040 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2041 /// pre-existing declaration exists no action takes place.
2042 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2043                                         IdentifierInfo *II) {
2044   if (!II->isStr("objc_msgSendSuper"))
2045     return;
2046   ASTContext &Context = ThisSema.Context;
2047 
2048   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2049                       SourceLocation(), Sema::LookupTagName);
2050   ThisSema.LookupName(Result, S);
2051   if (Result.getResultKind() == LookupResult::Found)
2052     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2053       Context.setObjCSuperType(Context.getTagDeclType(TD));
2054 }
2055 
2056 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2057                                ASTContext::GetBuiltinTypeError Error) {
2058   switch (Error) {
2059   case ASTContext::GE_None:
2060     return "";
2061   case ASTContext::GE_Missing_type:
2062     return BuiltinInfo.getHeaderName(ID);
2063   case ASTContext::GE_Missing_stdio:
2064     return "stdio.h";
2065   case ASTContext::GE_Missing_setjmp:
2066     return "setjmp.h";
2067   case ASTContext::GE_Missing_ucontext:
2068     return "ucontext.h";
2069   }
2070   llvm_unreachable("unhandled error kind");
2071 }
2072 
2073 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2074 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2075 /// if we're creating this built-in in anticipation of redeclaring the
2076 /// built-in.
2077 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2078                                      Scope *S, bool ForRedeclaration,
2079                                      SourceLocation Loc) {
2080   LookupPredefedObjCSuperType(*this, S, II);
2081 
2082   ASTContext::GetBuiltinTypeError Error;
2083   QualType R = Context.GetBuiltinType(ID, Error);
2084   if (Error) {
2085     if (!ForRedeclaration)
2086       return nullptr;
2087 
2088     // If we have a builtin without an associated type we should not emit a
2089     // warning when we were not able to find a type for it.
2090     if (Error == ASTContext::GE_Missing_type)
2091       return nullptr;
2092 
2093     // If we could not find a type for setjmp it is because the jmp_buf type was
2094     // not defined prior to the setjmp declaration.
2095     if (Error == ASTContext::GE_Missing_setjmp) {
2096       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2097           << Context.BuiltinInfo.getName(ID);
2098       return nullptr;
2099     }
2100 
2101     // Generally, we emit a warning that the declaration requires the
2102     // appropriate header.
2103     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2104         << getHeaderName(Context.BuiltinInfo, ID, Error)
2105         << Context.BuiltinInfo.getName(ID);
2106     return nullptr;
2107   }
2108 
2109   if (!ForRedeclaration &&
2110       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2111        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2112     Diag(Loc, diag::ext_implicit_lib_function_decl)
2113         << Context.BuiltinInfo.getName(ID) << R;
2114     if (Context.BuiltinInfo.getHeaderName(ID) &&
2115         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2116       Diag(Loc, diag::note_include_header_or_declare)
2117           << Context.BuiltinInfo.getHeaderName(ID)
2118           << Context.BuiltinInfo.getName(ID);
2119   }
2120 
2121   if (R.isNull())
2122     return nullptr;
2123 
2124   DeclContext *Parent = Context.getTranslationUnitDecl();
2125   if (getLangOpts().CPlusPlus) {
2126     LinkageSpecDecl *CLinkageDecl =
2127         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2128                                 LinkageSpecDecl::lang_c, false);
2129     CLinkageDecl->setImplicit();
2130     Parent->addDecl(CLinkageDecl);
2131     Parent = CLinkageDecl;
2132   }
2133 
2134   FunctionDecl *New = FunctionDecl::Create(Context,
2135                                            Parent,
2136                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2137                                            SC_Extern,
2138                                            false,
2139                                            R->isFunctionProtoType());
2140   New->setImplicit();
2141 
2142   // Create Decl objects for each parameter, adding them to the
2143   // FunctionDecl.
2144   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2145     SmallVector<ParmVarDecl*, 16> Params;
2146     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2147       ParmVarDecl *parm =
2148           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2149                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2150                               SC_None, nullptr);
2151       parm->setScopeInfo(0, i);
2152       Params.push_back(parm);
2153     }
2154     New->setParams(Params);
2155   }
2156 
2157   AddKnownFunctionAttributes(New);
2158   RegisterLocallyScopedExternCDecl(New, S);
2159 
2160   // TUScope is the translation-unit scope to insert this function into.
2161   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2162   // relate Scopes to DeclContexts, and probably eliminate CurContext
2163   // entirely, but we're not there yet.
2164   DeclContext *SavedContext = CurContext;
2165   CurContext = Parent;
2166   PushOnScopeChains(New, TUScope);
2167   CurContext = SavedContext;
2168   return New;
2169 }
2170 
2171 /// Typedef declarations don't have linkage, but they still denote the same
2172 /// entity if their types are the same.
2173 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2174 /// isSameEntity.
2175 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2176                                                      TypedefNameDecl *Decl,
2177                                                      LookupResult &Previous) {
2178   // This is only interesting when modules are enabled.
2179   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2180     return;
2181 
2182   // Empty sets are uninteresting.
2183   if (Previous.empty())
2184     return;
2185 
2186   LookupResult::Filter Filter = Previous.makeFilter();
2187   while (Filter.hasNext()) {
2188     NamedDecl *Old = Filter.next();
2189 
2190     // Non-hidden declarations are never ignored.
2191     if (S.isVisible(Old))
2192       continue;
2193 
2194     // Declarations of the same entity are not ignored, even if they have
2195     // different linkages.
2196     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2197       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2198                                 Decl->getUnderlyingType()))
2199         continue;
2200 
2201       // If both declarations give a tag declaration a typedef name for linkage
2202       // purposes, then they declare the same entity.
2203       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2204           Decl->getAnonDeclWithTypedefName())
2205         continue;
2206     }
2207 
2208     Filter.erase();
2209   }
2210 
2211   Filter.done();
2212 }
2213 
2214 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2215   QualType OldType;
2216   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2217     OldType = OldTypedef->getUnderlyingType();
2218   else
2219     OldType = Context.getTypeDeclType(Old);
2220   QualType NewType = New->getUnderlyingType();
2221 
2222   if (NewType->isVariablyModifiedType()) {
2223     // Must not redefine a typedef with a variably-modified type.
2224     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2225     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2226       << Kind << NewType;
2227     if (Old->getLocation().isValid())
2228       notePreviousDefinition(Old, New->getLocation());
2229     New->setInvalidDecl();
2230     return true;
2231   }
2232 
2233   if (OldType != NewType &&
2234       !OldType->isDependentType() &&
2235       !NewType->isDependentType() &&
2236       !Context.hasSameType(OldType, NewType)) {
2237     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2238     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2239       << Kind << NewType << OldType;
2240     if (Old->getLocation().isValid())
2241       notePreviousDefinition(Old, New->getLocation());
2242     New->setInvalidDecl();
2243     return true;
2244   }
2245   return false;
2246 }
2247 
2248 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2249 /// same name and scope as a previous declaration 'Old'.  Figure out
2250 /// how to resolve this situation, merging decls or emitting
2251 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2252 ///
2253 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2254                                 LookupResult &OldDecls) {
2255   // If the new decl is known invalid already, don't bother doing any
2256   // merging checks.
2257   if (New->isInvalidDecl()) return;
2258 
2259   // Allow multiple definitions for ObjC built-in typedefs.
2260   // FIXME: Verify the underlying types are equivalent!
2261   if (getLangOpts().ObjC) {
2262     const IdentifierInfo *TypeID = New->getIdentifier();
2263     switch (TypeID->getLength()) {
2264     default: break;
2265     case 2:
2266       {
2267         if (!TypeID->isStr("id"))
2268           break;
2269         QualType T = New->getUnderlyingType();
2270         if (!T->isPointerType())
2271           break;
2272         if (!T->isVoidPointerType()) {
2273           QualType PT = T->castAs<PointerType>()->getPointeeType();
2274           if (!PT->isStructureType())
2275             break;
2276         }
2277         Context.setObjCIdRedefinitionType(T);
2278         // Install the built-in type for 'id', ignoring the current definition.
2279         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2280         return;
2281       }
2282     case 5:
2283       if (!TypeID->isStr("Class"))
2284         break;
2285       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2286       // Install the built-in type for 'Class', ignoring the current definition.
2287       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2288       return;
2289     case 3:
2290       if (!TypeID->isStr("SEL"))
2291         break;
2292       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2293       // Install the built-in type for 'SEL', ignoring the current definition.
2294       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2295       return;
2296     }
2297     // Fall through - the typedef name was not a builtin type.
2298   }
2299 
2300   // Verify the old decl was also a type.
2301   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2302   if (!Old) {
2303     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2304       << New->getDeclName();
2305 
2306     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2307     if (OldD->getLocation().isValid())
2308       notePreviousDefinition(OldD, New->getLocation());
2309 
2310     return New->setInvalidDecl();
2311   }
2312 
2313   // If the old declaration is invalid, just give up here.
2314   if (Old->isInvalidDecl())
2315     return New->setInvalidDecl();
2316 
2317   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2318     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2319     auto *NewTag = New->getAnonDeclWithTypedefName();
2320     NamedDecl *Hidden = nullptr;
2321     if (OldTag && NewTag &&
2322         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2323         !hasVisibleDefinition(OldTag, &Hidden)) {
2324       // There is a definition of this tag, but it is not visible. Use it
2325       // instead of our tag.
2326       New->setTypeForDecl(OldTD->getTypeForDecl());
2327       if (OldTD->isModed())
2328         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2329                                     OldTD->getUnderlyingType());
2330       else
2331         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2332 
2333       // Make the old tag definition visible.
2334       makeMergedDefinitionVisible(Hidden);
2335 
2336       // If this was an unscoped enumeration, yank all of its enumerators
2337       // out of the scope.
2338       if (isa<EnumDecl>(NewTag)) {
2339         Scope *EnumScope = getNonFieldDeclScope(S);
2340         for (auto *D : NewTag->decls()) {
2341           auto *ED = cast<EnumConstantDecl>(D);
2342           assert(EnumScope->isDeclScope(ED));
2343           EnumScope->RemoveDecl(ED);
2344           IdResolver.RemoveDecl(ED);
2345           ED->getLexicalDeclContext()->removeDecl(ED);
2346         }
2347       }
2348     }
2349   }
2350 
2351   // If the typedef types are not identical, reject them in all languages and
2352   // with any extensions enabled.
2353   if (isIncompatibleTypedef(Old, New))
2354     return;
2355 
2356   // The types match.  Link up the redeclaration chain and merge attributes if
2357   // the old declaration was a typedef.
2358   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2359     New->setPreviousDecl(Typedef);
2360     mergeDeclAttributes(New, Old);
2361   }
2362 
2363   if (getLangOpts().MicrosoftExt)
2364     return;
2365 
2366   if (getLangOpts().CPlusPlus) {
2367     // C++ [dcl.typedef]p2:
2368     //   In a given non-class scope, a typedef specifier can be used to
2369     //   redefine the name of any type declared in that scope to refer
2370     //   to the type to which it already refers.
2371     if (!isa<CXXRecordDecl>(CurContext))
2372       return;
2373 
2374     // C++0x [dcl.typedef]p4:
2375     //   In a given class scope, a typedef specifier can be used to redefine
2376     //   any class-name declared in that scope that is not also a typedef-name
2377     //   to refer to the type to which it already refers.
2378     //
2379     // This wording came in via DR424, which was a correction to the
2380     // wording in DR56, which accidentally banned code like:
2381     //
2382     //   struct S {
2383     //     typedef struct A { } A;
2384     //   };
2385     //
2386     // in the C++03 standard. We implement the C++0x semantics, which
2387     // allow the above but disallow
2388     //
2389     //   struct S {
2390     //     typedef int I;
2391     //     typedef int I;
2392     //   };
2393     //
2394     // since that was the intent of DR56.
2395     if (!isa<TypedefNameDecl>(Old))
2396       return;
2397 
2398     Diag(New->getLocation(), diag::err_redefinition)
2399       << New->getDeclName();
2400     notePreviousDefinition(Old, New->getLocation());
2401     return New->setInvalidDecl();
2402   }
2403 
2404   // Modules always permit redefinition of typedefs, as does C11.
2405   if (getLangOpts().Modules || getLangOpts().C11)
2406     return;
2407 
2408   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2409   // is normally mapped to an error, but can be controlled with
2410   // -Wtypedef-redefinition.  If either the original or the redefinition is
2411   // in a system header, don't emit this for compatibility with GCC.
2412   if (getDiagnostics().getSuppressSystemWarnings() &&
2413       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2414       (Old->isImplicit() ||
2415        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2416        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2417     return;
2418 
2419   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2420     << New->getDeclName();
2421   notePreviousDefinition(Old, New->getLocation());
2422 }
2423 
2424 /// DeclhasAttr - returns true if decl Declaration already has the target
2425 /// attribute.
2426 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2427   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2428   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2429   for (const auto *i : D->attrs())
2430     if (i->getKind() == A->getKind()) {
2431       if (Ann) {
2432         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2433           return true;
2434         continue;
2435       }
2436       // FIXME: Don't hardcode this check
2437       if (OA && isa<OwnershipAttr>(i))
2438         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2439       return true;
2440     }
2441 
2442   return false;
2443 }
2444 
2445 static bool isAttributeTargetADefinition(Decl *D) {
2446   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2447     return VD->isThisDeclarationADefinition();
2448   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2449     return TD->isCompleteDefinition() || TD->isBeingDefined();
2450   return true;
2451 }
2452 
2453 /// Merge alignment attributes from \p Old to \p New, taking into account the
2454 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2455 ///
2456 /// \return \c true if any attributes were added to \p New.
2457 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2458   // Look for alignas attributes on Old, and pick out whichever attribute
2459   // specifies the strictest alignment requirement.
2460   AlignedAttr *OldAlignasAttr = nullptr;
2461   AlignedAttr *OldStrictestAlignAttr = nullptr;
2462   unsigned OldAlign = 0;
2463   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2464     // FIXME: We have no way of representing inherited dependent alignments
2465     // in a case like:
2466     //   template<int A, int B> struct alignas(A) X;
2467     //   template<int A, int B> struct alignas(B) X {};
2468     // For now, we just ignore any alignas attributes which are not on the
2469     // definition in such a case.
2470     if (I->isAlignmentDependent())
2471       return false;
2472 
2473     if (I->isAlignas())
2474       OldAlignasAttr = I;
2475 
2476     unsigned Align = I->getAlignment(S.Context);
2477     if (Align > OldAlign) {
2478       OldAlign = Align;
2479       OldStrictestAlignAttr = I;
2480     }
2481   }
2482 
2483   // Look for alignas attributes on New.
2484   AlignedAttr *NewAlignasAttr = nullptr;
2485   unsigned NewAlign = 0;
2486   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2487     if (I->isAlignmentDependent())
2488       return false;
2489 
2490     if (I->isAlignas())
2491       NewAlignasAttr = I;
2492 
2493     unsigned Align = I->getAlignment(S.Context);
2494     if (Align > NewAlign)
2495       NewAlign = Align;
2496   }
2497 
2498   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2499     // Both declarations have 'alignas' attributes. We require them to match.
2500     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2501     // fall short. (If two declarations both have alignas, they must both match
2502     // every definition, and so must match each other if there is a definition.)
2503 
2504     // If either declaration only contains 'alignas(0)' specifiers, then it
2505     // specifies the natural alignment for the type.
2506     if (OldAlign == 0 || NewAlign == 0) {
2507       QualType Ty;
2508       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2509         Ty = VD->getType();
2510       else
2511         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2512 
2513       if (OldAlign == 0)
2514         OldAlign = S.Context.getTypeAlign(Ty);
2515       if (NewAlign == 0)
2516         NewAlign = S.Context.getTypeAlign(Ty);
2517     }
2518 
2519     if (OldAlign != NewAlign) {
2520       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2521         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2522         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2523       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2524     }
2525   }
2526 
2527   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2528     // C++11 [dcl.align]p6:
2529     //   if any declaration of an entity has an alignment-specifier,
2530     //   every defining declaration of that entity shall specify an
2531     //   equivalent alignment.
2532     // C11 6.7.5/7:
2533     //   If the definition of an object does not have an alignment
2534     //   specifier, any other declaration of that object shall also
2535     //   have no alignment specifier.
2536     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2537       << OldAlignasAttr;
2538     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2539       << OldAlignasAttr;
2540   }
2541 
2542   bool AnyAdded = false;
2543 
2544   // Ensure we have an attribute representing the strictest alignment.
2545   if (OldAlign > NewAlign) {
2546     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2547     Clone->setInherited(true);
2548     New->addAttr(Clone);
2549     AnyAdded = true;
2550   }
2551 
2552   // Ensure we have an alignas attribute if the old declaration had one.
2553   if (OldAlignasAttr && !NewAlignasAttr &&
2554       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2555     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2556     Clone->setInherited(true);
2557     New->addAttr(Clone);
2558     AnyAdded = true;
2559   }
2560 
2561   return AnyAdded;
2562 }
2563 
2564 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2565                                const InheritableAttr *Attr,
2566                                Sema::AvailabilityMergeKind AMK) {
2567   // This function copies an attribute Attr from a previous declaration to the
2568   // new declaration D if the new declaration doesn't itself have that attribute
2569   // yet or if that attribute allows duplicates.
2570   // If you're adding a new attribute that requires logic different from
2571   // "use explicit attribute on decl if present, else use attribute from
2572   // previous decl", for example if the attribute needs to be consistent
2573   // between redeclarations, you need to call a custom merge function here.
2574   InheritableAttr *NewAttr = nullptr;
2575   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2576     NewAttr = S.mergeAvailabilityAttr(
2577         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2578         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2579         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2580         AA->getPriority());
2581   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2582     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2583   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2584     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2585   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2586     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2587   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2588     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2589   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2590     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2591                                 FA->getFirstArg());
2592   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2593     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2594   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2595     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2596   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2597     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2598                                        IA->getInheritanceModel());
2599   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2600     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2601                                       &S.Context.Idents.get(AA->getSpelling()));
2602   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2603            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2604             isa<CUDAGlobalAttr>(Attr))) {
2605     // CUDA target attributes are part of function signature for
2606     // overloading purposes and must not be merged.
2607     return false;
2608   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2609     NewAttr = S.mergeMinSizeAttr(D, *MA);
2610   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2611     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2612   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2613     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2614   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2615     NewAttr = S.mergeCommonAttr(D, *CommonA);
2616   else if (isa<AlignedAttr>(Attr))
2617     // AlignedAttrs are handled separately, because we need to handle all
2618     // such attributes on a declaration at the same time.
2619     NewAttr = nullptr;
2620   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2621            (AMK == Sema::AMK_Override ||
2622             AMK == Sema::AMK_ProtocolImplementation))
2623     NewAttr = nullptr;
2624   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2625     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2626   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2627     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2628   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2629     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2630   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2631     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2632   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2633     NewAttr = S.mergeImportNameAttr(D, *INA);
2634   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2635     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2636 
2637   if (NewAttr) {
2638     NewAttr->setInherited(true);
2639     D->addAttr(NewAttr);
2640     if (isa<MSInheritanceAttr>(NewAttr))
2641       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2642     return true;
2643   }
2644 
2645   return false;
2646 }
2647 
2648 static const NamedDecl *getDefinition(const Decl *D) {
2649   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2650     return TD->getDefinition();
2651   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2652     const VarDecl *Def = VD->getDefinition();
2653     if (Def)
2654       return Def;
2655     return VD->getActingDefinition();
2656   }
2657   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2658     return FD->getDefinition();
2659   return nullptr;
2660 }
2661 
2662 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2663   for (const auto *Attribute : D->attrs())
2664     if (Attribute->getKind() == Kind)
2665       return true;
2666   return false;
2667 }
2668 
2669 /// checkNewAttributesAfterDef - If we already have a definition, check that
2670 /// there are no new attributes in this declaration.
2671 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2672   if (!New->hasAttrs())
2673     return;
2674 
2675   const NamedDecl *Def = getDefinition(Old);
2676   if (!Def || Def == New)
2677     return;
2678 
2679   AttrVec &NewAttributes = New->getAttrs();
2680   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2681     const Attr *NewAttribute = NewAttributes[I];
2682 
2683     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2684       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2685         Sema::SkipBodyInfo SkipBody;
2686         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2687 
2688         // If we're skipping this definition, drop the "alias" attribute.
2689         if (SkipBody.ShouldSkip) {
2690           NewAttributes.erase(NewAttributes.begin() + I);
2691           --E;
2692           continue;
2693         }
2694       } else {
2695         VarDecl *VD = cast<VarDecl>(New);
2696         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2697                                 VarDecl::TentativeDefinition
2698                             ? diag::err_alias_after_tentative
2699                             : diag::err_redefinition;
2700         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2701         if (Diag == diag::err_redefinition)
2702           S.notePreviousDefinition(Def, VD->getLocation());
2703         else
2704           S.Diag(Def->getLocation(), diag::note_previous_definition);
2705         VD->setInvalidDecl();
2706       }
2707       ++I;
2708       continue;
2709     }
2710 
2711     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2712       // Tentative definitions are only interesting for the alias check above.
2713       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2714         ++I;
2715         continue;
2716       }
2717     }
2718 
2719     if (hasAttribute(Def, NewAttribute->getKind())) {
2720       ++I;
2721       continue; // regular attr merging will take care of validating this.
2722     }
2723 
2724     if (isa<C11NoReturnAttr>(NewAttribute)) {
2725       // C's _Noreturn is allowed to be added to a function after it is defined.
2726       ++I;
2727       continue;
2728     } else if (isa<UuidAttr>(NewAttribute)) {
2729       // msvc will allow a subsequent definition to add an uuid to a class
2730       ++I;
2731       continue;
2732     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2733       if (AA->isAlignas()) {
2734         // C++11 [dcl.align]p6:
2735         //   if any declaration of an entity has an alignment-specifier,
2736         //   every defining declaration of that entity shall specify an
2737         //   equivalent alignment.
2738         // C11 6.7.5/7:
2739         //   If the definition of an object does not have an alignment
2740         //   specifier, any other declaration of that object shall also
2741         //   have no alignment specifier.
2742         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2743           << AA;
2744         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2745           << AA;
2746         NewAttributes.erase(NewAttributes.begin() + I);
2747         --E;
2748         continue;
2749       }
2750     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2751       // If there is a C definition followed by a redeclaration with this
2752       // attribute then there are two different definitions. In C++, prefer the
2753       // standard diagnostics.
2754       if (!S.getLangOpts().CPlusPlus) {
2755         S.Diag(NewAttribute->getLocation(),
2756                diag::err_loader_uninitialized_redeclaration);
2757         S.Diag(Def->getLocation(), diag::note_previous_definition);
2758         NewAttributes.erase(NewAttributes.begin() + I);
2759         --E;
2760         continue;
2761       }
2762     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2763                cast<VarDecl>(New)->isInline() &&
2764                !cast<VarDecl>(New)->isInlineSpecified()) {
2765       // Don't warn about applying selectany to implicitly inline variables.
2766       // Older compilers and language modes would require the use of selectany
2767       // to make such variables inline, and it would have no effect if we
2768       // honored it.
2769       ++I;
2770       continue;
2771     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2772       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2773       // declarations after defintions.
2774       ++I;
2775       continue;
2776     }
2777 
2778     S.Diag(NewAttribute->getLocation(),
2779            diag::warn_attribute_precede_definition);
2780     S.Diag(Def->getLocation(), diag::note_previous_definition);
2781     NewAttributes.erase(NewAttributes.begin() + I);
2782     --E;
2783   }
2784 }
2785 
2786 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2787                                      const ConstInitAttr *CIAttr,
2788                                      bool AttrBeforeInit) {
2789   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2790 
2791   // Figure out a good way to write this specifier on the old declaration.
2792   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2793   // enough of the attribute list spelling information to extract that without
2794   // heroics.
2795   std::string SuitableSpelling;
2796   if (S.getLangOpts().CPlusPlus20)
2797     SuitableSpelling = std::string(
2798         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2799   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2800     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2801         InsertLoc, {tok::l_square, tok::l_square,
2802                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2803                     S.PP.getIdentifierInfo("require_constant_initialization"),
2804                     tok::r_square, tok::r_square}));
2805   if (SuitableSpelling.empty())
2806     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2807         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2808                     S.PP.getIdentifierInfo("require_constant_initialization"),
2809                     tok::r_paren, tok::r_paren}));
2810   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2811     SuitableSpelling = "constinit";
2812   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2813     SuitableSpelling = "[[clang::require_constant_initialization]]";
2814   if (SuitableSpelling.empty())
2815     SuitableSpelling = "__attribute__((require_constant_initialization))";
2816   SuitableSpelling += " ";
2817 
2818   if (AttrBeforeInit) {
2819     // extern constinit int a;
2820     // int a = 0; // error (missing 'constinit'), accepted as extension
2821     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2822     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2823         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2824     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2825   } else {
2826     // int a = 0;
2827     // constinit extern int a; // error (missing 'constinit')
2828     S.Diag(CIAttr->getLocation(),
2829            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2830                                  : diag::warn_require_const_init_added_too_late)
2831         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2832     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2833         << CIAttr->isConstinit()
2834         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2835   }
2836 }
2837 
2838 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2839 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2840                                AvailabilityMergeKind AMK) {
2841   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2842     UsedAttr *NewAttr = OldAttr->clone(Context);
2843     NewAttr->setInherited(true);
2844     New->addAttr(NewAttr);
2845   }
2846 
2847   if (!Old->hasAttrs() && !New->hasAttrs())
2848     return;
2849 
2850   // [dcl.constinit]p1:
2851   //   If the [constinit] specifier is applied to any declaration of a
2852   //   variable, it shall be applied to the initializing declaration.
2853   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2854   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2855   if (bool(OldConstInit) != bool(NewConstInit)) {
2856     const auto *OldVD = cast<VarDecl>(Old);
2857     auto *NewVD = cast<VarDecl>(New);
2858 
2859     // Find the initializing declaration. Note that we might not have linked
2860     // the new declaration into the redeclaration chain yet.
2861     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2862     if (!InitDecl &&
2863         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2864       InitDecl = NewVD;
2865 
2866     if (InitDecl == NewVD) {
2867       // This is the initializing declaration. If it would inherit 'constinit',
2868       // that's ill-formed. (Note that we do not apply this to the attribute
2869       // form).
2870       if (OldConstInit && OldConstInit->isConstinit())
2871         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2872                                  /*AttrBeforeInit=*/true);
2873     } else if (NewConstInit) {
2874       // This is the first time we've been told that this declaration should
2875       // have a constant initializer. If we already saw the initializing
2876       // declaration, this is too late.
2877       if (InitDecl && InitDecl != NewVD) {
2878         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2879                                  /*AttrBeforeInit=*/false);
2880         NewVD->dropAttr<ConstInitAttr>();
2881       }
2882     }
2883   }
2884 
2885   // Attributes declared post-definition are currently ignored.
2886   checkNewAttributesAfterDef(*this, New, Old);
2887 
2888   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2889     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2890       if (!OldA->isEquivalent(NewA)) {
2891         // This redeclaration changes __asm__ label.
2892         Diag(New->getLocation(), diag::err_different_asm_label);
2893         Diag(OldA->getLocation(), diag::note_previous_declaration);
2894       }
2895     } else if (Old->isUsed()) {
2896       // This redeclaration adds an __asm__ label to a declaration that has
2897       // already been ODR-used.
2898       Diag(New->getLocation(), diag::err_late_asm_label_name)
2899         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2900     }
2901   }
2902 
2903   // Re-declaration cannot add abi_tag's.
2904   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2905     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2906       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2907         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2908                       NewTag) == OldAbiTagAttr->tags_end()) {
2909           Diag(NewAbiTagAttr->getLocation(),
2910                diag::err_new_abi_tag_on_redeclaration)
2911               << NewTag;
2912           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2913         }
2914       }
2915     } else {
2916       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2917       Diag(Old->getLocation(), diag::note_previous_declaration);
2918     }
2919   }
2920 
2921   // This redeclaration adds a section attribute.
2922   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2923     if (auto *VD = dyn_cast<VarDecl>(New)) {
2924       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2925         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2926         Diag(Old->getLocation(), diag::note_previous_declaration);
2927       }
2928     }
2929   }
2930 
2931   // Redeclaration adds code-seg attribute.
2932   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2933   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2934       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2935     Diag(New->getLocation(), diag::warn_mismatched_section)
2936          << 0 /*codeseg*/;
2937     Diag(Old->getLocation(), diag::note_previous_declaration);
2938   }
2939 
2940   if (!Old->hasAttrs())
2941     return;
2942 
2943   bool foundAny = New->hasAttrs();
2944 
2945   // Ensure that any moving of objects within the allocated map is done before
2946   // we process them.
2947   if (!foundAny) New->setAttrs(AttrVec());
2948 
2949   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2950     // Ignore deprecated/unavailable/availability attributes if requested.
2951     AvailabilityMergeKind LocalAMK = AMK_None;
2952     if (isa<DeprecatedAttr>(I) ||
2953         isa<UnavailableAttr>(I) ||
2954         isa<AvailabilityAttr>(I)) {
2955       switch (AMK) {
2956       case AMK_None:
2957         continue;
2958 
2959       case AMK_Redeclaration:
2960       case AMK_Override:
2961       case AMK_ProtocolImplementation:
2962         LocalAMK = AMK;
2963         break;
2964       }
2965     }
2966 
2967     // Already handled.
2968     if (isa<UsedAttr>(I))
2969       continue;
2970 
2971     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2972       foundAny = true;
2973   }
2974 
2975   if (mergeAlignedAttrs(*this, New, Old))
2976     foundAny = true;
2977 
2978   if (!foundAny) New->dropAttrs();
2979 }
2980 
2981 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2982 /// to the new one.
2983 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2984                                      const ParmVarDecl *oldDecl,
2985                                      Sema &S) {
2986   // C++11 [dcl.attr.depend]p2:
2987   //   The first declaration of a function shall specify the
2988   //   carries_dependency attribute for its declarator-id if any declaration
2989   //   of the function specifies the carries_dependency attribute.
2990   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2991   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2992     S.Diag(CDA->getLocation(),
2993            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2994     // Find the first declaration of the parameter.
2995     // FIXME: Should we build redeclaration chains for function parameters?
2996     const FunctionDecl *FirstFD =
2997       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2998     const ParmVarDecl *FirstVD =
2999       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3000     S.Diag(FirstVD->getLocation(),
3001            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3002   }
3003 
3004   if (!oldDecl->hasAttrs())
3005     return;
3006 
3007   bool foundAny = newDecl->hasAttrs();
3008 
3009   // Ensure that any moving of objects within the allocated map is
3010   // done before we process them.
3011   if (!foundAny) newDecl->setAttrs(AttrVec());
3012 
3013   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3014     if (!DeclHasAttr(newDecl, I)) {
3015       InheritableAttr *newAttr =
3016         cast<InheritableParamAttr>(I->clone(S.Context));
3017       newAttr->setInherited(true);
3018       newDecl->addAttr(newAttr);
3019       foundAny = true;
3020     }
3021   }
3022 
3023   if (!foundAny) newDecl->dropAttrs();
3024 }
3025 
3026 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3027                                 const ParmVarDecl *OldParam,
3028                                 Sema &S) {
3029   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3030     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3031       if (*Oldnullability != *Newnullability) {
3032         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3033           << DiagNullabilityKind(
3034                *Newnullability,
3035                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3036                 != 0))
3037           << DiagNullabilityKind(
3038                *Oldnullability,
3039                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3040                 != 0));
3041         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3042       }
3043     } else {
3044       QualType NewT = NewParam->getType();
3045       NewT = S.Context.getAttributedType(
3046                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3047                          NewT, NewT);
3048       NewParam->setType(NewT);
3049     }
3050   }
3051 }
3052 
3053 namespace {
3054 
3055 /// Used in MergeFunctionDecl to keep track of function parameters in
3056 /// C.
3057 struct GNUCompatibleParamWarning {
3058   ParmVarDecl *OldParm;
3059   ParmVarDecl *NewParm;
3060   QualType PromotedType;
3061 };
3062 
3063 } // end anonymous namespace
3064 
3065 // Determine whether the previous declaration was a definition, implicit
3066 // declaration, or a declaration.
3067 template <typename T>
3068 static std::pair<diag::kind, SourceLocation>
3069 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3070   diag::kind PrevDiag;
3071   SourceLocation OldLocation = Old->getLocation();
3072   if (Old->isThisDeclarationADefinition())
3073     PrevDiag = diag::note_previous_definition;
3074   else if (Old->isImplicit()) {
3075     PrevDiag = diag::note_previous_implicit_declaration;
3076     if (OldLocation.isInvalid())
3077       OldLocation = New->getLocation();
3078   } else
3079     PrevDiag = diag::note_previous_declaration;
3080   return std::make_pair(PrevDiag, OldLocation);
3081 }
3082 
3083 /// canRedefineFunction - checks if a function can be redefined. Currently,
3084 /// only extern inline functions can be redefined, and even then only in
3085 /// GNU89 mode.
3086 static bool canRedefineFunction(const FunctionDecl *FD,
3087                                 const LangOptions& LangOpts) {
3088   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3089           !LangOpts.CPlusPlus &&
3090           FD->isInlineSpecified() &&
3091           FD->getStorageClass() == SC_Extern);
3092 }
3093 
3094 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3095   const AttributedType *AT = T->getAs<AttributedType>();
3096   while (AT && !AT->isCallingConv())
3097     AT = AT->getModifiedType()->getAs<AttributedType>();
3098   return AT;
3099 }
3100 
3101 template <typename T>
3102 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3103   const DeclContext *DC = Old->getDeclContext();
3104   if (DC->isRecord())
3105     return false;
3106 
3107   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3108   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3109     return true;
3110   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3111     return true;
3112   return false;
3113 }
3114 
3115 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3116 static bool isExternC(VarTemplateDecl *) { return false; }
3117 
3118 /// Check whether a redeclaration of an entity introduced by a
3119 /// using-declaration is valid, given that we know it's not an overload
3120 /// (nor a hidden tag declaration).
3121 template<typename ExpectedDecl>
3122 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3123                                    ExpectedDecl *New) {
3124   // C++11 [basic.scope.declarative]p4:
3125   //   Given a set of declarations in a single declarative region, each of
3126   //   which specifies the same unqualified name,
3127   //   -- they shall all refer to the same entity, or all refer to functions
3128   //      and function templates; or
3129   //   -- exactly one declaration shall declare a class name or enumeration
3130   //      name that is not a typedef name and the other declarations shall all
3131   //      refer to the same variable or enumerator, or all refer to functions
3132   //      and function templates; in this case the class name or enumeration
3133   //      name is hidden (3.3.10).
3134 
3135   // C++11 [namespace.udecl]p14:
3136   //   If a function declaration in namespace scope or block scope has the
3137   //   same name and the same parameter-type-list as a function introduced
3138   //   by a using-declaration, and the declarations do not declare the same
3139   //   function, the program is ill-formed.
3140 
3141   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3142   if (Old &&
3143       !Old->getDeclContext()->getRedeclContext()->Equals(
3144           New->getDeclContext()->getRedeclContext()) &&
3145       !(isExternC(Old) && isExternC(New)))
3146     Old = nullptr;
3147 
3148   if (!Old) {
3149     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3150     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3151     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3152     return true;
3153   }
3154   return false;
3155 }
3156 
3157 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3158                                             const FunctionDecl *B) {
3159   assert(A->getNumParams() == B->getNumParams());
3160 
3161   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3162     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3163     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3164     if (AttrA == AttrB)
3165       return true;
3166     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3167            AttrA->isDynamic() == AttrB->isDynamic();
3168   };
3169 
3170   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3171 }
3172 
3173 /// If necessary, adjust the semantic declaration context for a qualified
3174 /// declaration to name the correct inline namespace within the qualifier.
3175 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3176                                                DeclaratorDecl *OldD) {
3177   // The only case where we need to update the DeclContext is when
3178   // redeclaration lookup for a qualified name finds a declaration
3179   // in an inline namespace within the context named by the qualifier:
3180   //
3181   //   inline namespace N { int f(); }
3182   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3183   //
3184   // For unqualified declarations, the semantic context *can* change
3185   // along the redeclaration chain (for local extern declarations,
3186   // extern "C" declarations, and friend declarations in particular).
3187   if (!NewD->getQualifier())
3188     return;
3189 
3190   // NewD is probably already in the right context.
3191   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3192   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3193   if (NamedDC->Equals(SemaDC))
3194     return;
3195 
3196   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3197           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3198          "unexpected context for redeclaration");
3199 
3200   auto *LexDC = NewD->getLexicalDeclContext();
3201   auto FixSemaDC = [=](NamedDecl *D) {
3202     if (!D)
3203       return;
3204     D->setDeclContext(SemaDC);
3205     D->setLexicalDeclContext(LexDC);
3206   };
3207 
3208   FixSemaDC(NewD);
3209   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3210     FixSemaDC(FD->getDescribedFunctionTemplate());
3211   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3212     FixSemaDC(VD->getDescribedVarTemplate());
3213 }
3214 
3215 /// MergeFunctionDecl - We just parsed a function 'New' from
3216 /// declarator D which has the same name and scope as a previous
3217 /// declaration 'Old'.  Figure out how to resolve this situation,
3218 /// merging decls or emitting diagnostics as appropriate.
3219 ///
3220 /// In C++, New and Old must be declarations that are not
3221 /// overloaded. Use IsOverload to determine whether New and Old are
3222 /// overloaded, and to select the Old declaration that New should be
3223 /// merged with.
3224 ///
3225 /// Returns true if there was an error, false otherwise.
3226 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3227                              Scope *S, bool MergeTypeWithOld) {
3228   // Verify the old decl was also a function.
3229   FunctionDecl *Old = OldD->getAsFunction();
3230   if (!Old) {
3231     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3232       if (New->getFriendObjectKind()) {
3233         Diag(New->getLocation(), diag::err_using_decl_friend);
3234         Diag(Shadow->getTargetDecl()->getLocation(),
3235              diag::note_using_decl_target);
3236         Diag(Shadow->getUsingDecl()->getLocation(),
3237              diag::note_using_decl) << 0;
3238         return true;
3239       }
3240 
3241       // Check whether the two declarations might declare the same function.
3242       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3243         return true;
3244       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3245     } else {
3246       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3247         << New->getDeclName();
3248       notePreviousDefinition(OldD, New->getLocation());
3249       return true;
3250     }
3251   }
3252 
3253   // If the old declaration is invalid, just give up here.
3254   if (Old->isInvalidDecl())
3255     return true;
3256 
3257   // Disallow redeclaration of some builtins.
3258   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3259     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3260     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3261         << Old << Old->getType();
3262     return true;
3263   }
3264 
3265   diag::kind PrevDiag;
3266   SourceLocation OldLocation;
3267   std::tie(PrevDiag, OldLocation) =
3268       getNoteDiagForInvalidRedeclaration(Old, New);
3269 
3270   // Don't complain about this if we're in GNU89 mode and the old function
3271   // is an extern inline function.
3272   // Don't complain about specializations. They are not supposed to have
3273   // storage classes.
3274   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3275       New->getStorageClass() == SC_Static &&
3276       Old->hasExternalFormalLinkage() &&
3277       !New->getTemplateSpecializationInfo() &&
3278       !canRedefineFunction(Old, getLangOpts())) {
3279     if (getLangOpts().MicrosoftExt) {
3280       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3281       Diag(OldLocation, PrevDiag);
3282     } else {
3283       Diag(New->getLocation(), diag::err_static_non_static) << New;
3284       Diag(OldLocation, PrevDiag);
3285       return true;
3286     }
3287   }
3288 
3289   if (New->hasAttr<InternalLinkageAttr>() &&
3290       !Old->hasAttr<InternalLinkageAttr>()) {
3291     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3292         << New->getDeclName();
3293     notePreviousDefinition(Old, New->getLocation());
3294     New->dropAttr<InternalLinkageAttr>();
3295   }
3296 
3297   if (CheckRedeclarationModuleOwnership(New, Old))
3298     return true;
3299 
3300   if (!getLangOpts().CPlusPlus) {
3301     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3302     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3303       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3304         << New << OldOvl;
3305 
3306       // Try our best to find a decl that actually has the overloadable
3307       // attribute for the note. In most cases (e.g. programs with only one
3308       // broken declaration/definition), this won't matter.
3309       //
3310       // FIXME: We could do this if we juggled some extra state in
3311       // OverloadableAttr, rather than just removing it.
3312       const Decl *DiagOld = Old;
3313       if (OldOvl) {
3314         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3315           const auto *A = D->getAttr<OverloadableAttr>();
3316           return A && !A->isImplicit();
3317         });
3318         // If we've implicitly added *all* of the overloadable attrs to this
3319         // chain, emitting a "previous redecl" note is pointless.
3320         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3321       }
3322 
3323       if (DiagOld)
3324         Diag(DiagOld->getLocation(),
3325              diag::note_attribute_overloadable_prev_overload)
3326           << OldOvl;
3327 
3328       if (OldOvl)
3329         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3330       else
3331         New->dropAttr<OverloadableAttr>();
3332     }
3333   }
3334 
3335   // If a function is first declared with a calling convention, but is later
3336   // declared or defined without one, all following decls assume the calling
3337   // convention of the first.
3338   //
3339   // It's OK if a function is first declared without a calling convention,
3340   // but is later declared or defined with the default calling convention.
3341   //
3342   // To test if either decl has an explicit calling convention, we look for
3343   // AttributedType sugar nodes on the type as written.  If they are missing or
3344   // were canonicalized away, we assume the calling convention was implicit.
3345   //
3346   // Note also that we DO NOT return at this point, because we still have
3347   // other tests to run.
3348   QualType OldQType = Context.getCanonicalType(Old->getType());
3349   QualType NewQType = Context.getCanonicalType(New->getType());
3350   const FunctionType *OldType = cast<FunctionType>(OldQType);
3351   const FunctionType *NewType = cast<FunctionType>(NewQType);
3352   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3353   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3354   bool RequiresAdjustment = false;
3355 
3356   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3357     FunctionDecl *First = Old->getFirstDecl();
3358     const FunctionType *FT =
3359         First->getType().getCanonicalType()->castAs<FunctionType>();
3360     FunctionType::ExtInfo FI = FT->getExtInfo();
3361     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3362     if (!NewCCExplicit) {
3363       // Inherit the CC from the previous declaration if it was specified
3364       // there but not here.
3365       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3366       RequiresAdjustment = true;
3367     } else if (New->getBuiltinID()) {
3368       // Calling Conventions on a Builtin aren't really useful and setting a
3369       // default calling convention and cdecl'ing some builtin redeclarations is
3370       // common, so warn and ignore the calling convention on the redeclaration.
3371       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3372           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3373           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3374       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3375       RequiresAdjustment = true;
3376     } else {
3377       // Calling conventions aren't compatible, so complain.
3378       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3379       Diag(New->getLocation(), diag::err_cconv_change)
3380         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3381         << !FirstCCExplicit
3382         << (!FirstCCExplicit ? "" :
3383             FunctionType::getNameForCallConv(FI.getCC()));
3384 
3385       // Put the note on the first decl, since it is the one that matters.
3386       Diag(First->getLocation(), diag::note_previous_declaration);
3387       return true;
3388     }
3389   }
3390 
3391   // FIXME: diagnose the other way around?
3392   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3393     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3394     RequiresAdjustment = true;
3395   }
3396 
3397   // Merge regparm attribute.
3398   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3399       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3400     if (NewTypeInfo.getHasRegParm()) {
3401       Diag(New->getLocation(), diag::err_regparm_mismatch)
3402         << NewType->getRegParmType()
3403         << OldType->getRegParmType();
3404       Diag(OldLocation, diag::note_previous_declaration);
3405       return true;
3406     }
3407 
3408     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3409     RequiresAdjustment = true;
3410   }
3411 
3412   // Merge ns_returns_retained attribute.
3413   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3414     if (NewTypeInfo.getProducesResult()) {
3415       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3416           << "'ns_returns_retained'";
3417       Diag(OldLocation, diag::note_previous_declaration);
3418       return true;
3419     }
3420 
3421     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3422     RequiresAdjustment = true;
3423   }
3424 
3425   if (OldTypeInfo.getNoCallerSavedRegs() !=
3426       NewTypeInfo.getNoCallerSavedRegs()) {
3427     if (NewTypeInfo.getNoCallerSavedRegs()) {
3428       AnyX86NoCallerSavedRegistersAttr *Attr =
3429         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3430       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3431       Diag(OldLocation, diag::note_previous_declaration);
3432       return true;
3433     }
3434 
3435     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3436     RequiresAdjustment = true;
3437   }
3438 
3439   if (RequiresAdjustment) {
3440     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3441     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3442     New->setType(QualType(AdjustedType, 0));
3443     NewQType = Context.getCanonicalType(New->getType());
3444   }
3445 
3446   // If this redeclaration makes the function inline, we may need to add it to
3447   // UndefinedButUsed.
3448   if (!Old->isInlined() && New->isInlined() &&
3449       !New->hasAttr<GNUInlineAttr>() &&
3450       !getLangOpts().GNUInline &&
3451       Old->isUsed(false) &&
3452       !Old->isDefined() && !New->isThisDeclarationADefinition())
3453     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3454                                            SourceLocation()));
3455 
3456   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3457   // about it.
3458   if (New->hasAttr<GNUInlineAttr>() &&
3459       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3460     UndefinedButUsed.erase(Old->getCanonicalDecl());
3461   }
3462 
3463   // If pass_object_size params don't match up perfectly, this isn't a valid
3464   // redeclaration.
3465   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3466       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3467     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3468         << New->getDeclName();
3469     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3470     return true;
3471   }
3472 
3473   if (getLangOpts().CPlusPlus) {
3474     // C++1z [over.load]p2
3475     //   Certain function declarations cannot be overloaded:
3476     //     -- Function declarations that differ only in the return type,
3477     //        the exception specification, or both cannot be overloaded.
3478 
3479     // Check the exception specifications match. This may recompute the type of
3480     // both Old and New if it resolved exception specifications, so grab the
3481     // types again after this. Because this updates the type, we do this before
3482     // any of the other checks below, which may update the "de facto" NewQType
3483     // but do not necessarily update the type of New.
3484     if (CheckEquivalentExceptionSpec(Old, New))
3485       return true;
3486     OldQType = Context.getCanonicalType(Old->getType());
3487     NewQType = Context.getCanonicalType(New->getType());
3488 
3489     // Go back to the type source info to compare the declared return types,
3490     // per C++1y [dcl.type.auto]p13:
3491     //   Redeclarations or specializations of a function or function template
3492     //   with a declared return type that uses a placeholder type shall also
3493     //   use that placeholder, not a deduced type.
3494     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3495     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3496     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3497         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3498                                        OldDeclaredReturnType)) {
3499       QualType ResQT;
3500       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3501           OldDeclaredReturnType->isObjCObjectPointerType())
3502         // FIXME: This does the wrong thing for a deduced return type.
3503         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3504       if (ResQT.isNull()) {
3505         if (New->isCXXClassMember() && New->isOutOfLine())
3506           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3507               << New << New->getReturnTypeSourceRange();
3508         else
3509           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3510               << New->getReturnTypeSourceRange();
3511         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3512                                     << Old->getReturnTypeSourceRange();
3513         return true;
3514       }
3515       else
3516         NewQType = ResQT;
3517     }
3518 
3519     QualType OldReturnType = OldType->getReturnType();
3520     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3521     if (OldReturnType != NewReturnType) {
3522       // If this function has a deduced return type and has already been
3523       // defined, copy the deduced value from the old declaration.
3524       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3525       if (OldAT && OldAT->isDeduced()) {
3526         New->setType(
3527             SubstAutoType(New->getType(),
3528                           OldAT->isDependentType() ? Context.DependentTy
3529                                                    : OldAT->getDeducedType()));
3530         NewQType = Context.getCanonicalType(
3531             SubstAutoType(NewQType,
3532                           OldAT->isDependentType() ? Context.DependentTy
3533                                                    : OldAT->getDeducedType()));
3534       }
3535     }
3536 
3537     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3538     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3539     if (OldMethod && NewMethod) {
3540       // Preserve triviality.
3541       NewMethod->setTrivial(OldMethod->isTrivial());
3542 
3543       // MSVC allows explicit template specialization at class scope:
3544       // 2 CXXMethodDecls referring to the same function will be injected.
3545       // We don't want a redeclaration error.
3546       bool IsClassScopeExplicitSpecialization =
3547                               OldMethod->isFunctionTemplateSpecialization() &&
3548                               NewMethod->isFunctionTemplateSpecialization();
3549       bool isFriend = NewMethod->getFriendObjectKind();
3550 
3551       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3552           !IsClassScopeExplicitSpecialization) {
3553         //    -- Member function declarations with the same name and the
3554         //       same parameter types cannot be overloaded if any of them
3555         //       is a static member function declaration.
3556         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3557           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3558           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3559           return true;
3560         }
3561 
3562         // C++ [class.mem]p1:
3563         //   [...] A member shall not be declared twice in the
3564         //   member-specification, except that a nested class or member
3565         //   class template can be declared and then later defined.
3566         if (!inTemplateInstantiation()) {
3567           unsigned NewDiag;
3568           if (isa<CXXConstructorDecl>(OldMethod))
3569             NewDiag = diag::err_constructor_redeclared;
3570           else if (isa<CXXDestructorDecl>(NewMethod))
3571             NewDiag = diag::err_destructor_redeclared;
3572           else if (isa<CXXConversionDecl>(NewMethod))
3573             NewDiag = diag::err_conv_function_redeclared;
3574           else
3575             NewDiag = diag::err_member_redeclared;
3576 
3577           Diag(New->getLocation(), NewDiag);
3578         } else {
3579           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3580             << New << New->getType();
3581         }
3582         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3583         return true;
3584 
3585       // Complain if this is an explicit declaration of a special
3586       // member that was initially declared implicitly.
3587       //
3588       // As an exception, it's okay to befriend such methods in order
3589       // to permit the implicit constructor/destructor/operator calls.
3590       } else if (OldMethod->isImplicit()) {
3591         if (isFriend) {
3592           NewMethod->setImplicit();
3593         } else {
3594           Diag(NewMethod->getLocation(),
3595                diag::err_definition_of_implicitly_declared_member)
3596             << New << getSpecialMember(OldMethod);
3597           return true;
3598         }
3599       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3600         Diag(NewMethod->getLocation(),
3601              diag::err_definition_of_explicitly_defaulted_member)
3602           << getSpecialMember(OldMethod);
3603         return true;
3604       }
3605     }
3606 
3607     // C++11 [dcl.attr.noreturn]p1:
3608     //   The first declaration of a function shall specify the noreturn
3609     //   attribute if any declaration of that function specifies the noreturn
3610     //   attribute.
3611     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3612     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3613       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3614       Diag(Old->getFirstDecl()->getLocation(),
3615            diag::note_noreturn_missing_first_decl);
3616     }
3617 
3618     // C++11 [dcl.attr.depend]p2:
3619     //   The first declaration of a function shall specify the
3620     //   carries_dependency attribute for its declarator-id if any declaration
3621     //   of the function specifies the carries_dependency attribute.
3622     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3623     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3624       Diag(CDA->getLocation(),
3625            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3626       Diag(Old->getFirstDecl()->getLocation(),
3627            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3628     }
3629 
3630     // (C++98 8.3.5p3):
3631     //   All declarations for a function shall agree exactly in both the
3632     //   return type and the parameter-type-list.
3633     // We also want to respect all the extended bits except noreturn.
3634 
3635     // noreturn should now match unless the old type info didn't have it.
3636     QualType OldQTypeForComparison = OldQType;
3637     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3638       auto *OldType = OldQType->castAs<FunctionProtoType>();
3639       const FunctionType *OldTypeForComparison
3640         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3641       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3642       assert(OldQTypeForComparison.isCanonical());
3643     }
3644 
3645     if (haveIncompatibleLanguageLinkages(Old, New)) {
3646       // As a special case, retain the language linkage from previous
3647       // declarations of a friend function as an extension.
3648       //
3649       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3650       // and is useful because there's otherwise no way to specify language
3651       // linkage within class scope.
3652       //
3653       // Check cautiously as the friend object kind isn't yet complete.
3654       if (New->getFriendObjectKind() != Decl::FOK_None) {
3655         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3656         Diag(OldLocation, PrevDiag);
3657       } else {
3658         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3659         Diag(OldLocation, PrevDiag);
3660         return true;
3661       }
3662     }
3663 
3664     // If the function types are compatible, merge the declarations. Ignore the
3665     // exception specifier because it was already checked above in
3666     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3667     // about incompatible types under -fms-compatibility.
3668     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3669                                                          NewQType))
3670       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3671 
3672     // If the types are imprecise (due to dependent constructs in friends or
3673     // local extern declarations), it's OK if they differ. We'll check again
3674     // during instantiation.
3675     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3676       return false;
3677 
3678     // Fall through for conflicting redeclarations and redefinitions.
3679   }
3680 
3681   // C: Function types need to be compatible, not identical. This handles
3682   // duplicate function decls like "void f(int); void f(enum X);" properly.
3683   if (!getLangOpts().CPlusPlus &&
3684       Context.typesAreCompatible(OldQType, NewQType)) {
3685     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3686     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3687     const FunctionProtoType *OldProto = nullptr;
3688     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3689         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3690       // The old declaration provided a function prototype, but the
3691       // new declaration does not. Merge in the prototype.
3692       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3693       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3694       NewQType =
3695           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3696                                   OldProto->getExtProtoInfo());
3697       New->setType(NewQType);
3698       New->setHasInheritedPrototype();
3699 
3700       // Synthesize parameters with the same types.
3701       SmallVector<ParmVarDecl*, 16> Params;
3702       for (const auto &ParamType : OldProto->param_types()) {
3703         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3704                                                  SourceLocation(), nullptr,
3705                                                  ParamType, /*TInfo=*/nullptr,
3706                                                  SC_None, nullptr);
3707         Param->setScopeInfo(0, Params.size());
3708         Param->setImplicit();
3709         Params.push_back(Param);
3710       }
3711 
3712       New->setParams(Params);
3713     }
3714 
3715     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3716   }
3717 
3718   // Check if the function types are compatible when pointer size address
3719   // spaces are ignored.
3720   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3721     return false;
3722 
3723   // GNU C permits a K&R definition to follow a prototype declaration
3724   // if the declared types of the parameters in the K&R definition
3725   // match the types in the prototype declaration, even when the
3726   // promoted types of the parameters from the K&R definition differ
3727   // from the types in the prototype. GCC then keeps the types from
3728   // the prototype.
3729   //
3730   // If a variadic prototype is followed by a non-variadic K&R definition,
3731   // the K&R definition becomes variadic.  This is sort of an edge case, but
3732   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3733   // C99 6.9.1p8.
3734   if (!getLangOpts().CPlusPlus &&
3735       Old->hasPrototype() && !New->hasPrototype() &&
3736       New->getType()->getAs<FunctionProtoType>() &&
3737       Old->getNumParams() == New->getNumParams()) {
3738     SmallVector<QualType, 16> ArgTypes;
3739     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3740     const FunctionProtoType *OldProto
3741       = Old->getType()->getAs<FunctionProtoType>();
3742     const FunctionProtoType *NewProto
3743       = New->getType()->getAs<FunctionProtoType>();
3744 
3745     // Determine whether this is the GNU C extension.
3746     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3747                                                NewProto->getReturnType());
3748     bool LooseCompatible = !MergedReturn.isNull();
3749     for (unsigned Idx = 0, End = Old->getNumParams();
3750          LooseCompatible && Idx != End; ++Idx) {
3751       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3752       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3753       if (Context.typesAreCompatible(OldParm->getType(),
3754                                      NewProto->getParamType(Idx))) {
3755         ArgTypes.push_back(NewParm->getType());
3756       } else if (Context.typesAreCompatible(OldParm->getType(),
3757                                             NewParm->getType(),
3758                                             /*CompareUnqualified=*/true)) {
3759         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3760                                            NewProto->getParamType(Idx) };
3761         Warnings.push_back(Warn);
3762         ArgTypes.push_back(NewParm->getType());
3763       } else
3764         LooseCompatible = false;
3765     }
3766 
3767     if (LooseCompatible) {
3768       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3769         Diag(Warnings[Warn].NewParm->getLocation(),
3770              diag::ext_param_promoted_not_compatible_with_prototype)
3771           << Warnings[Warn].PromotedType
3772           << Warnings[Warn].OldParm->getType();
3773         if (Warnings[Warn].OldParm->getLocation().isValid())
3774           Diag(Warnings[Warn].OldParm->getLocation(),
3775                diag::note_previous_declaration);
3776       }
3777 
3778       if (MergeTypeWithOld)
3779         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3780                                              OldProto->getExtProtoInfo()));
3781       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3782     }
3783 
3784     // Fall through to diagnose conflicting types.
3785   }
3786 
3787   // A function that has already been declared has been redeclared or
3788   // defined with a different type; show an appropriate diagnostic.
3789 
3790   // If the previous declaration was an implicitly-generated builtin
3791   // declaration, then at the very least we should use a specialized note.
3792   unsigned BuiltinID;
3793   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3794     // If it's actually a library-defined builtin function like 'malloc'
3795     // or 'printf', just warn about the incompatible redeclaration.
3796     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3797       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3798       Diag(OldLocation, diag::note_previous_builtin_declaration)
3799         << Old << Old->getType();
3800 
3801       // If this is a global redeclaration, just forget hereafter
3802       // about the "builtin-ness" of the function.
3803       //
3804       // Doing this for local extern declarations is problematic.  If
3805       // the builtin declaration remains visible, a second invalid
3806       // local declaration will produce a hard error; if it doesn't
3807       // remain visible, a single bogus local redeclaration (which is
3808       // actually only a warning) could break all the downstream code.
3809       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3810         New->getIdentifier()->revertBuiltin();
3811 
3812       return false;
3813     }
3814 
3815     PrevDiag = diag::note_previous_builtin_declaration;
3816   }
3817 
3818   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3819   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3820   return true;
3821 }
3822 
3823 /// Completes the merge of two function declarations that are
3824 /// known to be compatible.
3825 ///
3826 /// This routine handles the merging of attributes and other
3827 /// properties of function declarations from the old declaration to
3828 /// the new declaration, once we know that New is in fact a
3829 /// redeclaration of Old.
3830 ///
3831 /// \returns false
3832 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3833                                         Scope *S, bool MergeTypeWithOld) {
3834   // Merge the attributes
3835   mergeDeclAttributes(New, Old);
3836 
3837   // Merge "pure" flag.
3838   if (Old->isPure())
3839     New->setPure();
3840 
3841   // Merge "used" flag.
3842   if (Old->getMostRecentDecl()->isUsed(false))
3843     New->setIsUsed();
3844 
3845   // Merge attributes from the parameters.  These can mismatch with K&R
3846   // declarations.
3847   if (New->getNumParams() == Old->getNumParams())
3848       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3849         ParmVarDecl *NewParam = New->getParamDecl(i);
3850         ParmVarDecl *OldParam = Old->getParamDecl(i);
3851         mergeParamDeclAttributes(NewParam, OldParam, *this);
3852         mergeParamDeclTypes(NewParam, OldParam, *this);
3853       }
3854 
3855   if (getLangOpts().CPlusPlus)
3856     return MergeCXXFunctionDecl(New, Old, S);
3857 
3858   // Merge the function types so the we get the composite types for the return
3859   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3860   // was visible.
3861   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3862   if (!Merged.isNull() && MergeTypeWithOld)
3863     New->setType(Merged);
3864 
3865   return false;
3866 }
3867 
3868 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3869                                 ObjCMethodDecl *oldMethod) {
3870   // Merge the attributes, including deprecated/unavailable
3871   AvailabilityMergeKind MergeKind =
3872     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3873       ? AMK_ProtocolImplementation
3874       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3875                                                        : AMK_Override;
3876 
3877   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3878 
3879   // Merge attributes from the parameters.
3880   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3881                                        oe = oldMethod->param_end();
3882   for (ObjCMethodDecl::param_iterator
3883          ni = newMethod->param_begin(), ne = newMethod->param_end();
3884        ni != ne && oi != oe; ++ni, ++oi)
3885     mergeParamDeclAttributes(*ni, *oi, *this);
3886 
3887   CheckObjCMethodOverride(newMethod, oldMethod);
3888 }
3889 
3890 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3891   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3892 
3893   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3894          ? diag::err_redefinition_different_type
3895          : diag::err_redeclaration_different_type)
3896     << New->getDeclName() << New->getType() << Old->getType();
3897 
3898   diag::kind PrevDiag;
3899   SourceLocation OldLocation;
3900   std::tie(PrevDiag, OldLocation)
3901     = getNoteDiagForInvalidRedeclaration(Old, New);
3902   S.Diag(OldLocation, PrevDiag);
3903   New->setInvalidDecl();
3904 }
3905 
3906 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3907 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3908 /// emitting diagnostics as appropriate.
3909 ///
3910 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3911 /// to here in AddInitializerToDecl. We can't check them before the initializer
3912 /// is attached.
3913 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3914                              bool MergeTypeWithOld) {
3915   if (New->isInvalidDecl() || Old->isInvalidDecl())
3916     return;
3917 
3918   QualType MergedT;
3919   if (getLangOpts().CPlusPlus) {
3920     if (New->getType()->isUndeducedType()) {
3921       // We don't know what the new type is until the initializer is attached.
3922       return;
3923     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3924       // These could still be something that needs exception specs checked.
3925       return MergeVarDeclExceptionSpecs(New, Old);
3926     }
3927     // C++ [basic.link]p10:
3928     //   [...] the types specified by all declarations referring to a given
3929     //   object or function shall be identical, except that declarations for an
3930     //   array object can specify array types that differ by the presence or
3931     //   absence of a major array bound (8.3.4).
3932     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3933       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3934       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3935 
3936       // We are merging a variable declaration New into Old. If it has an array
3937       // bound, and that bound differs from Old's bound, we should diagnose the
3938       // mismatch.
3939       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3940         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3941              PrevVD = PrevVD->getPreviousDecl()) {
3942           QualType PrevVDTy = PrevVD->getType();
3943           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3944             continue;
3945 
3946           if (!Context.hasSameType(New->getType(), PrevVDTy))
3947             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3948         }
3949       }
3950 
3951       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3952         if (Context.hasSameType(OldArray->getElementType(),
3953                                 NewArray->getElementType()))
3954           MergedT = New->getType();
3955       }
3956       // FIXME: Check visibility. New is hidden but has a complete type. If New
3957       // has no array bound, it should not inherit one from Old, if Old is not
3958       // visible.
3959       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3960         if (Context.hasSameType(OldArray->getElementType(),
3961                                 NewArray->getElementType()))
3962           MergedT = Old->getType();
3963       }
3964     }
3965     else if (New->getType()->isObjCObjectPointerType() &&
3966                Old->getType()->isObjCObjectPointerType()) {
3967       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3968                                               Old->getType());
3969     }
3970   } else {
3971     // C 6.2.7p2:
3972     //   All declarations that refer to the same object or function shall have
3973     //   compatible type.
3974     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3975   }
3976   if (MergedT.isNull()) {
3977     // It's OK if we couldn't merge types if either type is dependent, for a
3978     // block-scope variable. In other cases (static data members of class
3979     // templates, variable templates, ...), we require the types to be
3980     // equivalent.
3981     // FIXME: The C++ standard doesn't say anything about this.
3982     if ((New->getType()->isDependentType() ||
3983          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3984       // If the old type was dependent, we can't merge with it, so the new type
3985       // becomes dependent for now. We'll reproduce the original type when we
3986       // instantiate the TypeSourceInfo for the variable.
3987       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3988         New->setType(Context.DependentTy);
3989       return;
3990     }
3991     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3992   }
3993 
3994   // Don't actually update the type on the new declaration if the old
3995   // declaration was an extern declaration in a different scope.
3996   if (MergeTypeWithOld)
3997     New->setType(MergedT);
3998 }
3999 
4000 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4001                                   LookupResult &Previous) {
4002   // C11 6.2.7p4:
4003   //   For an identifier with internal or external linkage declared
4004   //   in a scope in which a prior declaration of that identifier is
4005   //   visible, if the prior declaration specifies internal or
4006   //   external linkage, the type of the identifier at the later
4007   //   declaration becomes the composite type.
4008   //
4009   // If the variable isn't visible, we do not merge with its type.
4010   if (Previous.isShadowed())
4011     return false;
4012 
4013   if (S.getLangOpts().CPlusPlus) {
4014     // C++11 [dcl.array]p3:
4015     //   If there is a preceding declaration of the entity in the same
4016     //   scope in which the bound was specified, an omitted array bound
4017     //   is taken to be the same as in that earlier declaration.
4018     return NewVD->isPreviousDeclInSameBlockScope() ||
4019            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4020             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4021   } else {
4022     // If the old declaration was function-local, don't merge with its
4023     // type unless we're in the same function.
4024     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4025            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4026   }
4027 }
4028 
4029 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4030 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4031 /// situation, merging decls or emitting diagnostics as appropriate.
4032 ///
4033 /// Tentative definition rules (C99 6.9.2p2) are checked by
4034 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4035 /// definitions here, since the initializer hasn't been attached.
4036 ///
4037 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4038   // If the new decl is already invalid, don't do any other checking.
4039   if (New->isInvalidDecl())
4040     return;
4041 
4042   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4043     return;
4044 
4045   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4046 
4047   // Verify the old decl was also a variable or variable template.
4048   VarDecl *Old = nullptr;
4049   VarTemplateDecl *OldTemplate = nullptr;
4050   if (Previous.isSingleResult()) {
4051     if (NewTemplate) {
4052       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4053       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4054 
4055       if (auto *Shadow =
4056               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4057         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4058           return New->setInvalidDecl();
4059     } else {
4060       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4061 
4062       if (auto *Shadow =
4063               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4064         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4065           return New->setInvalidDecl();
4066     }
4067   }
4068   if (!Old) {
4069     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4070         << New->getDeclName();
4071     notePreviousDefinition(Previous.getRepresentativeDecl(),
4072                            New->getLocation());
4073     return New->setInvalidDecl();
4074   }
4075 
4076   // Ensure the template parameters are compatible.
4077   if (NewTemplate &&
4078       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4079                                       OldTemplate->getTemplateParameters(),
4080                                       /*Complain=*/true, TPL_TemplateMatch))
4081     return New->setInvalidDecl();
4082 
4083   // C++ [class.mem]p1:
4084   //   A member shall not be declared twice in the member-specification [...]
4085   //
4086   // Here, we need only consider static data members.
4087   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4088     Diag(New->getLocation(), diag::err_duplicate_member)
4089       << New->getIdentifier();
4090     Diag(Old->getLocation(), diag::note_previous_declaration);
4091     New->setInvalidDecl();
4092   }
4093 
4094   mergeDeclAttributes(New, Old);
4095   // Warn if an already-declared variable is made a weak_import in a subsequent
4096   // declaration
4097   if (New->hasAttr<WeakImportAttr>() &&
4098       Old->getStorageClass() == SC_None &&
4099       !Old->hasAttr<WeakImportAttr>()) {
4100     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4101     notePreviousDefinition(Old, New->getLocation());
4102     // Remove weak_import attribute on new declaration.
4103     New->dropAttr<WeakImportAttr>();
4104   }
4105 
4106   if (New->hasAttr<InternalLinkageAttr>() &&
4107       !Old->hasAttr<InternalLinkageAttr>()) {
4108     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4109         << New->getDeclName();
4110     notePreviousDefinition(Old, New->getLocation());
4111     New->dropAttr<InternalLinkageAttr>();
4112   }
4113 
4114   // Merge the types.
4115   VarDecl *MostRecent = Old->getMostRecentDecl();
4116   if (MostRecent != Old) {
4117     MergeVarDeclTypes(New, MostRecent,
4118                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4119     if (New->isInvalidDecl())
4120       return;
4121   }
4122 
4123   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4124   if (New->isInvalidDecl())
4125     return;
4126 
4127   diag::kind PrevDiag;
4128   SourceLocation OldLocation;
4129   std::tie(PrevDiag, OldLocation) =
4130       getNoteDiagForInvalidRedeclaration(Old, New);
4131 
4132   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4133   if (New->getStorageClass() == SC_Static &&
4134       !New->isStaticDataMember() &&
4135       Old->hasExternalFormalLinkage()) {
4136     if (getLangOpts().MicrosoftExt) {
4137       Diag(New->getLocation(), diag::ext_static_non_static)
4138           << New->getDeclName();
4139       Diag(OldLocation, PrevDiag);
4140     } else {
4141       Diag(New->getLocation(), diag::err_static_non_static)
4142           << New->getDeclName();
4143       Diag(OldLocation, PrevDiag);
4144       return New->setInvalidDecl();
4145     }
4146   }
4147   // C99 6.2.2p4:
4148   //   For an identifier declared with the storage-class specifier
4149   //   extern in a scope in which a prior declaration of that
4150   //   identifier is visible,23) if the prior declaration specifies
4151   //   internal or external linkage, the linkage of the identifier at
4152   //   the later declaration is the same as the linkage specified at
4153   //   the prior declaration. If no prior declaration is visible, or
4154   //   if the prior declaration specifies no linkage, then the
4155   //   identifier has external linkage.
4156   if (New->hasExternalStorage() && Old->hasLinkage())
4157     /* Okay */;
4158   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4159            !New->isStaticDataMember() &&
4160            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4161     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4162     Diag(OldLocation, PrevDiag);
4163     return New->setInvalidDecl();
4164   }
4165 
4166   // Check if extern is followed by non-extern and vice-versa.
4167   if (New->hasExternalStorage() &&
4168       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4169     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4170     Diag(OldLocation, PrevDiag);
4171     return New->setInvalidDecl();
4172   }
4173   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4174       !New->hasExternalStorage()) {
4175     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4176     Diag(OldLocation, PrevDiag);
4177     return New->setInvalidDecl();
4178   }
4179 
4180   if (CheckRedeclarationModuleOwnership(New, Old))
4181     return;
4182 
4183   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4184 
4185   // FIXME: The test for external storage here seems wrong? We still
4186   // need to check for mismatches.
4187   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4188       // Don't complain about out-of-line definitions of static members.
4189       !(Old->getLexicalDeclContext()->isRecord() &&
4190         !New->getLexicalDeclContext()->isRecord())) {
4191     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4192     Diag(OldLocation, PrevDiag);
4193     return New->setInvalidDecl();
4194   }
4195 
4196   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4197     if (VarDecl *Def = Old->getDefinition()) {
4198       // C++1z [dcl.fcn.spec]p4:
4199       //   If the definition of a variable appears in a translation unit before
4200       //   its first declaration as inline, the program is ill-formed.
4201       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4202       Diag(Def->getLocation(), diag::note_previous_definition);
4203     }
4204   }
4205 
4206   // If this redeclaration makes the variable inline, we may need to add it to
4207   // UndefinedButUsed.
4208   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4209       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4210     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4211                                            SourceLocation()));
4212 
4213   if (New->getTLSKind() != Old->getTLSKind()) {
4214     if (!Old->getTLSKind()) {
4215       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4216       Diag(OldLocation, PrevDiag);
4217     } else if (!New->getTLSKind()) {
4218       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4219       Diag(OldLocation, PrevDiag);
4220     } else {
4221       // Do not allow redeclaration to change the variable between requiring
4222       // static and dynamic initialization.
4223       // FIXME: GCC allows this, but uses the TLS keyword on the first
4224       // declaration to determine the kind. Do we need to be compatible here?
4225       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4226         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4227       Diag(OldLocation, PrevDiag);
4228     }
4229   }
4230 
4231   // C++ doesn't have tentative definitions, so go right ahead and check here.
4232   if (getLangOpts().CPlusPlus &&
4233       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4234     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4235         Old->getCanonicalDecl()->isConstexpr()) {
4236       // This definition won't be a definition any more once it's been merged.
4237       Diag(New->getLocation(),
4238            diag::warn_deprecated_redundant_constexpr_static_def);
4239     } else if (VarDecl *Def = Old->getDefinition()) {
4240       if (checkVarDeclRedefinition(Def, New))
4241         return;
4242     }
4243   }
4244 
4245   if (haveIncompatibleLanguageLinkages(Old, New)) {
4246     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4247     Diag(OldLocation, PrevDiag);
4248     New->setInvalidDecl();
4249     return;
4250   }
4251 
4252   // Merge "used" flag.
4253   if (Old->getMostRecentDecl()->isUsed(false))
4254     New->setIsUsed();
4255 
4256   // Keep a chain of previous declarations.
4257   New->setPreviousDecl(Old);
4258   if (NewTemplate)
4259     NewTemplate->setPreviousDecl(OldTemplate);
4260   adjustDeclContextForDeclaratorDecl(New, Old);
4261 
4262   // Inherit access appropriately.
4263   New->setAccess(Old->getAccess());
4264   if (NewTemplate)
4265     NewTemplate->setAccess(New->getAccess());
4266 
4267   if (Old->isInline())
4268     New->setImplicitlyInline();
4269 }
4270 
4271 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4272   SourceManager &SrcMgr = getSourceManager();
4273   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4274   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4275   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4276   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4277   auto &HSI = PP.getHeaderSearchInfo();
4278   StringRef HdrFilename =
4279       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4280 
4281   auto noteFromModuleOrInclude = [&](Module *Mod,
4282                                      SourceLocation IncLoc) -> bool {
4283     // Redefinition errors with modules are common with non modular mapped
4284     // headers, example: a non-modular header H in module A that also gets
4285     // included directly in a TU. Pointing twice to the same header/definition
4286     // is confusing, try to get better diagnostics when modules is on.
4287     if (IncLoc.isValid()) {
4288       if (Mod) {
4289         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4290             << HdrFilename.str() << Mod->getFullModuleName();
4291         if (!Mod->DefinitionLoc.isInvalid())
4292           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4293               << Mod->getFullModuleName();
4294       } else {
4295         Diag(IncLoc, diag::note_redefinition_include_same_file)
4296             << HdrFilename.str();
4297       }
4298       return true;
4299     }
4300 
4301     return false;
4302   };
4303 
4304   // Is it the same file and same offset? Provide more information on why
4305   // this leads to a redefinition error.
4306   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4307     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4308     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4309     bool EmittedDiag =
4310         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4311     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4312 
4313     // If the header has no guards, emit a note suggesting one.
4314     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4315       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4316 
4317     if (EmittedDiag)
4318       return;
4319   }
4320 
4321   // Redefinition coming from different files or couldn't do better above.
4322   if (Old->getLocation().isValid())
4323     Diag(Old->getLocation(), diag::note_previous_definition);
4324 }
4325 
4326 /// We've just determined that \p Old and \p New both appear to be definitions
4327 /// of the same variable. Either diagnose or fix the problem.
4328 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4329   if (!hasVisibleDefinition(Old) &&
4330       (New->getFormalLinkage() == InternalLinkage ||
4331        New->isInline() ||
4332        New->getDescribedVarTemplate() ||
4333        New->getNumTemplateParameterLists() ||
4334        New->getDeclContext()->isDependentContext())) {
4335     // The previous definition is hidden, and multiple definitions are
4336     // permitted (in separate TUs). Demote this to a declaration.
4337     New->demoteThisDefinitionToDeclaration();
4338 
4339     // Make the canonical definition visible.
4340     if (auto *OldTD = Old->getDescribedVarTemplate())
4341       makeMergedDefinitionVisible(OldTD);
4342     makeMergedDefinitionVisible(Old);
4343     return false;
4344   } else {
4345     Diag(New->getLocation(), diag::err_redefinition) << New;
4346     notePreviousDefinition(Old, New->getLocation());
4347     New->setInvalidDecl();
4348     return true;
4349   }
4350 }
4351 
4352 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4353 /// no declarator (e.g. "struct foo;") is parsed.
4354 Decl *
4355 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4356                                  RecordDecl *&AnonRecord) {
4357   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4358                                     AnonRecord);
4359 }
4360 
4361 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4362 // disambiguate entities defined in different scopes.
4363 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4364 // compatibility.
4365 // We will pick our mangling number depending on which version of MSVC is being
4366 // targeted.
4367 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4368   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4369              ? S->getMSCurManglingNumber()
4370              : S->getMSLastManglingNumber();
4371 }
4372 
4373 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4374   if (!Context.getLangOpts().CPlusPlus)
4375     return;
4376 
4377   if (isa<CXXRecordDecl>(Tag->getParent())) {
4378     // If this tag is the direct child of a class, number it if
4379     // it is anonymous.
4380     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4381       return;
4382     MangleNumberingContext &MCtx =
4383         Context.getManglingNumberContext(Tag->getParent());
4384     Context.setManglingNumber(
4385         Tag, MCtx.getManglingNumber(
4386                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4387     return;
4388   }
4389 
4390   // If this tag isn't a direct child of a class, number it if it is local.
4391   MangleNumberingContext *MCtx;
4392   Decl *ManglingContextDecl;
4393   std::tie(MCtx, ManglingContextDecl) =
4394       getCurrentMangleNumberContext(Tag->getDeclContext());
4395   if (MCtx) {
4396     Context.setManglingNumber(
4397         Tag, MCtx->getManglingNumber(
4398                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4399   }
4400 }
4401 
4402 namespace {
4403 struct NonCLikeKind {
4404   enum {
4405     None,
4406     BaseClass,
4407     DefaultMemberInit,
4408     Lambda,
4409     Friend,
4410     OtherMember,
4411     Invalid,
4412   } Kind = None;
4413   SourceRange Range;
4414 
4415   explicit operator bool() { return Kind != None; }
4416 };
4417 }
4418 
4419 /// Determine whether a class is C-like, according to the rules of C++
4420 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4421 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4422   if (RD->isInvalidDecl())
4423     return {NonCLikeKind::Invalid, {}};
4424 
4425   // C++ [dcl.typedef]p9: [P1766R1]
4426   //   An unnamed class with a typedef name for linkage purposes shall not
4427   //
4428   //    -- have any base classes
4429   if (RD->getNumBases())
4430     return {NonCLikeKind::BaseClass,
4431             SourceRange(RD->bases_begin()->getBeginLoc(),
4432                         RD->bases_end()[-1].getEndLoc())};
4433   bool Invalid = false;
4434   for (Decl *D : RD->decls()) {
4435     // Don't complain about things we already diagnosed.
4436     if (D->isInvalidDecl()) {
4437       Invalid = true;
4438       continue;
4439     }
4440 
4441     //  -- have any [...] default member initializers
4442     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4443       if (FD->hasInClassInitializer()) {
4444         auto *Init = FD->getInClassInitializer();
4445         return {NonCLikeKind::DefaultMemberInit,
4446                 Init ? Init->getSourceRange() : D->getSourceRange()};
4447       }
4448       continue;
4449     }
4450 
4451     // FIXME: We don't allow friend declarations. This violates the wording of
4452     // P1766, but not the intent.
4453     if (isa<FriendDecl>(D))
4454       return {NonCLikeKind::Friend, D->getSourceRange()};
4455 
4456     //  -- declare any members other than non-static data members, member
4457     //     enumerations, or member classes,
4458     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4459         isa<EnumDecl>(D))
4460       continue;
4461     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4462     if (!MemberRD) {
4463       if (D->isImplicit())
4464         continue;
4465       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4466     }
4467 
4468     //  -- contain a lambda-expression,
4469     if (MemberRD->isLambda())
4470       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4471 
4472     //  and all member classes shall also satisfy these requirements
4473     //  (recursively).
4474     if (MemberRD->isThisDeclarationADefinition()) {
4475       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4476         return Kind;
4477     }
4478   }
4479 
4480   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4481 }
4482 
4483 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4484                                         TypedefNameDecl *NewTD) {
4485   if (TagFromDeclSpec->isInvalidDecl())
4486     return;
4487 
4488   // Do nothing if the tag already has a name for linkage purposes.
4489   if (TagFromDeclSpec->hasNameForLinkage())
4490     return;
4491 
4492   // A well-formed anonymous tag must always be a TUK_Definition.
4493   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4494 
4495   // The type must match the tag exactly;  no qualifiers allowed.
4496   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4497                            Context.getTagDeclType(TagFromDeclSpec))) {
4498     if (getLangOpts().CPlusPlus)
4499       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4500     return;
4501   }
4502 
4503   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4504   //   An unnamed class with a typedef name for linkage purposes shall [be
4505   //   C-like].
4506   //
4507   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4508   // shouldn't happen, but there are constructs that the language rule doesn't
4509   // disallow for which we can't reasonably avoid computing linkage early.
4510   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4511   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4512                              : NonCLikeKind();
4513   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4514   if (NonCLike || ChangesLinkage) {
4515     if (NonCLike.Kind == NonCLikeKind::Invalid)
4516       return;
4517 
4518     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4519     if (ChangesLinkage) {
4520       // If the linkage changes, we can't accept this as an extension.
4521       if (NonCLike.Kind == NonCLikeKind::None)
4522         DiagID = diag::err_typedef_changes_linkage;
4523       else
4524         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4525     }
4526 
4527     SourceLocation FixitLoc =
4528         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4529     llvm::SmallString<40> TextToInsert;
4530     TextToInsert += ' ';
4531     TextToInsert += NewTD->getIdentifier()->getName();
4532 
4533     Diag(FixitLoc, DiagID)
4534       << isa<TypeAliasDecl>(NewTD)
4535       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4536     if (NonCLike.Kind != NonCLikeKind::None) {
4537       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4538         << NonCLike.Kind - 1 << NonCLike.Range;
4539     }
4540     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4541       << NewTD << isa<TypeAliasDecl>(NewTD);
4542 
4543     if (ChangesLinkage)
4544       return;
4545   }
4546 
4547   // Otherwise, set this as the anon-decl typedef for the tag.
4548   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4549 }
4550 
4551 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4552   switch (T) {
4553   case DeclSpec::TST_class:
4554     return 0;
4555   case DeclSpec::TST_struct:
4556     return 1;
4557   case DeclSpec::TST_interface:
4558     return 2;
4559   case DeclSpec::TST_union:
4560     return 3;
4561   case DeclSpec::TST_enum:
4562     return 4;
4563   default:
4564     llvm_unreachable("unexpected type specifier");
4565   }
4566 }
4567 
4568 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4569 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4570 /// parameters to cope with template friend declarations.
4571 Decl *
4572 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4573                                  MultiTemplateParamsArg TemplateParams,
4574                                  bool IsExplicitInstantiation,
4575                                  RecordDecl *&AnonRecord) {
4576   Decl *TagD = nullptr;
4577   TagDecl *Tag = nullptr;
4578   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4579       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4580       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4581       DS.getTypeSpecType() == DeclSpec::TST_union ||
4582       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4583     TagD = DS.getRepAsDecl();
4584 
4585     if (!TagD) // We probably had an error
4586       return nullptr;
4587 
4588     // Note that the above type specs guarantee that the
4589     // type rep is a Decl, whereas in many of the others
4590     // it's a Type.
4591     if (isa<TagDecl>(TagD))
4592       Tag = cast<TagDecl>(TagD);
4593     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4594       Tag = CTD->getTemplatedDecl();
4595   }
4596 
4597   if (Tag) {
4598     handleTagNumbering(Tag, S);
4599     Tag->setFreeStanding();
4600     if (Tag->isInvalidDecl())
4601       return Tag;
4602   }
4603 
4604   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4605     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4606     // or incomplete types shall not be restrict-qualified."
4607     if (TypeQuals & DeclSpec::TQ_restrict)
4608       Diag(DS.getRestrictSpecLoc(),
4609            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4610            << DS.getSourceRange();
4611   }
4612 
4613   if (DS.isInlineSpecified())
4614     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4615         << getLangOpts().CPlusPlus17;
4616 
4617   if (DS.hasConstexprSpecifier()) {
4618     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4619     // and definitions of functions and variables.
4620     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4621     // the declaration of a function or function template
4622     if (Tag)
4623       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4624           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4625           << DS.getConstexprSpecifier();
4626     else
4627       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4628           << DS.getConstexprSpecifier();
4629     // Don't emit warnings after this error.
4630     return TagD;
4631   }
4632 
4633   DiagnoseFunctionSpecifiers(DS);
4634 
4635   if (DS.isFriendSpecified()) {
4636     // If we're dealing with a decl but not a TagDecl, assume that
4637     // whatever routines created it handled the friendship aspect.
4638     if (TagD && !Tag)
4639       return nullptr;
4640     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4641   }
4642 
4643   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4644   bool IsExplicitSpecialization =
4645     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4646   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4647       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4648       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4649     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4650     // nested-name-specifier unless it is an explicit instantiation
4651     // or an explicit specialization.
4652     //
4653     // FIXME: We allow class template partial specializations here too, per the
4654     // obvious intent of DR1819.
4655     //
4656     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4657     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4658         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4659     return nullptr;
4660   }
4661 
4662   // Track whether this decl-specifier declares anything.
4663   bool DeclaresAnything = true;
4664 
4665   // Handle anonymous struct definitions.
4666   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4667     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4668         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4669       if (getLangOpts().CPlusPlus ||
4670           Record->getDeclContext()->isRecord()) {
4671         // If CurContext is a DeclContext that can contain statements,
4672         // RecursiveASTVisitor won't visit the decls that
4673         // BuildAnonymousStructOrUnion() will put into CurContext.
4674         // Also store them here so that they can be part of the
4675         // DeclStmt that gets created in this case.
4676         // FIXME: Also return the IndirectFieldDecls created by
4677         // BuildAnonymousStructOr union, for the same reason?
4678         if (CurContext->isFunctionOrMethod())
4679           AnonRecord = Record;
4680         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4681                                            Context.getPrintingPolicy());
4682       }
4683 
4684       DeclaresAnything = false;
4685     }
4686   }
4687 
4688   // C11 6.7.2.1p2:
4689   //   A struct-declaration that does not declare an anonymous structure or
4690   //   anonymous union shall contain a struct-declarator-list.
4691   //
4692   // This rule also existed in C89 and C99; the grammar for struct-declaration
4693   // did not permit a struct-declaration without a struct-declarator-list.
4694   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4695       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4696     // Check for Microsoft C extension: anonymous struct/union member.
4697     // Handle 2 kinds of anonymous struct/union:
4698     //   struct STRUCT;
4699     //   union UNION;
4700     // and
4701     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4702     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4703     if ((Tag && Tag->getDeclName()) ||
4704         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4705       RecordDecl *Record = nullptr;
4706       if (Tag)
4707         Record = dyn_cast<RecordDecl>(Tag);
4708       else if (const RecordType *RT =
4709                    DS.getRepAsType().get()->getAsStructureType())
4710         Record = RT->getDecl();
4711       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4712         Record = UT->getDecl();
4713 
4714       if (Record && getLangOpts().MicrosoftExt) {
4715         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4716             << Record->isUnion() << DS.getSourceRange();
4717         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4718       }
4719 
4720       DeclaresAnything = false;
4721     }
4722   }
4723 
4724   // Skip all the checks below if we have a type error.
4725   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4726       (TagD && TagD->isInvalidDecl()))
4727     return TagD;
4728 
4729   if (getLangOpts().CPlusPlus &&
4730       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4731     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4732       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4733           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4734         DeclaresAnything = false;
4735 
4736   if (!DS.isMissingDeclaratorOk()) {
4737     // Customize diagnostic for a typedef missing a name.
4738     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4739       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4740           << DS.getSourceRange();
4741     else
4742       DeclaresAnything = false;
4743   }
4744 
4745   if (DS.isModulePrivateSpecified() &&
4746       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4747     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4748       << Tag->getTagKind()
4749       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4750 
4751   ActOnDocumentableDecl(TagD);
4752 
4753   // C 6.7/2:
4754   //   A declaration [...] shall declare at least a declarator [...], a tag,
4755   //   or the members of an enumeration.
4756   // C++ [dcl.dcl]p3:
4757   //   [If there are no declarators], and except for the declaration of an
4758   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4759   //   names into the program, or shall redeclare a name introduced by a
4760   //   previous declaration.
4761   if (!DeclaresAnything) {
4762     // In C, we allow this as a (popular) extension / bug. Don't bother
4763     // producing further diagnostics for redundant qualifiers after this.
4764     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4765                                ? diag::err_no_declarators
4766                                : diag::ext_no_declarators)
4767         << DS.getSourceRange();
4768     return TagD;
4769   }
4770 
4771   // C++ [dcl.stc]p1:
4772   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4773   //   init-declarator-list of the declaration shall not be empty.
4774   // C++ [dcl.fct.spec]p1:
4775   //   If a cv-qualifier appears in a decl-specifier-seq, the
4776   //   init-declarator-list of the declaration shall not be empty.
4777   //
4778   // Spurious qualifiers here appear to be valid in C.
4779   unsigned DiagID = diag::warn_standalone_specifier;
4780   if (getLangOpts().CPlusPlus)
4781     DiagID = diag::ext_standalone_specifier;
4782 
4783   // Note that a linkage-specification sets a storage class, but
4784   // 'extern "C" struct foo;' is actually valid and not theoretically
4785   // useless.
4786   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4787     if (SCS == DeclSpec::SCS_mutable)
4788       // Since mutable is not a viable storage class specifier in C, there is
4789       // no reason to treat it as an extension. Instead, diagnose as an error.
4790       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4791     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4792       Diag(DS.getStorageClassSpecLoc(), DiagID)
4793         << DeclSpec::getSpecifierName(SCS);
4794   }
4795 
4796   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4797     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4798       << DeclSpec::getSpecifierName(TSCS);
4799   if (DS.getTypeQualifiers()) {
4800     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4801       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4802     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4803       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4804     // Restrict is covered above.
4805     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4806       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4807     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4808       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4809   }
4810 
4811   // Warn about ignored type attributes, for example:
4812   // __attribute__((aligned)) struct A;
4813   // Attributes should be placed after tag to apply to type declaration.
4814   if (!DS.getAttributes().empty()) {
4815     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4816     if (TypeSpecType == DeclSpec::TST_class ||
4817         TypeSpecType == DeclSpec::TST_struct ||
4818         TypeSpecType == DeclSpec::TST_interface ||
4819         TypeSpecType == DeclSpec::TST_union ||
4820         TypeSpecType == DeclSpec::TST_enum) {
4821       for (const ParsedAttr &AL : DS.getAttributes())
4822         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4823             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4824     }
4825   }
4826 
4827   return TagD;
4828 }
4829 
4830 /// We are trying to inject an anonymous member into the given scope;
4831 /// check if there's an existing declaration that can't be overloaded.
4832 ///
4833 /// \return true if this is a forbidden redeclaration
4834 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4835                                          Scope *S,
4836                                          DeclContext *Owner,
4837                                          DeclarationName Name,
4838                                          SourceLocation NameLoc,
4839                                          bool IsUnion) {
4840   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4841                  Sema::ForVisibleRedeclaration);
4842   if (!SemaRef.LookupName(R, S)) return false;
4843 
4844   // Pick a representative declaration.
4845   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4846   assert(PrevDecl && "Expected a non-null Decl");
4847 
4848   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4849     return false;
4850 
4851   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4852     << IsUnion << Name;
4853   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4854 
4855   return true;
4856 }
4857 
4858 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4859 /// anonymous struct or union AnonRecord into the owning context Owner
4860 /// and scope S. This routine will be invoked just after we realize
4861 /// that an unnamed union or struct is actually an anonymous union or
4862 /// struct, e.g.,
4863 ///
4864 /// @code
4865 /// union {
4866 ///   int i;
4867 ///   float f;
4868 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4869 ///    // f into the surrounding scope.x
4870 /// @endcode
4871 ///
4872 /// This routine is recursive, injecting the names of nested anonymous
4873 /// structs/unions into the owning context and scope as well.
4874 static bool
4875 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4876                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4877                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4878   bool Invalid = false;
4879 
4880   // Look every FieldDecl and IndirectFieldDecl with a name.
4881   for (auto *D : AnonRecord->decls()) {
4882     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4883         cast<NamedDecl>(D)->getDeclName()) {
4884       ValueDecl *VD = cast<ValueDecl>(D);
4885       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4886                                        VD->getLocation(),
4887                                        AnonRecord->isUnion())) {
4888         // C++ [class.union]p2:
4889         //   The names of the members of an anonymous union shall be
4890         //   distinct from the names of any other entity in the
4891         //   scope in which the anonymous union is declared.
4892         Invalid = true;
4893       } else {
4894         // C++ [class.union]p2:
4895         //   For the purpose of name lookup, after the anonymous union
4896         //   definition, the members of the anonymous union are
4897         //   considered to have been defined in the scope in which the
4898         //   anonymous union is declared.
4899         unsigned OldChainingSize = Chaining.size();
4900         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4901           Chaining.append(IF->chain_begin(), IF->chain_end());
4902         else
4903           Chaining.push_back(VD);
4904 
4905         assert(Chaining.size() >= 2);
4906         NamedDecl **NamedChain =
4907           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4908         for (unsigned i = 0; i < Chaining.size(); i++)
4909           NamedChain[i] = Chaining[i];
4910 
4911         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4912             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4913             VD->getType(), {NamedChain, Chaining.size()});
4914 
4915         for (const auto *Attr : VD->attrs())
4916           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4917 
4918         IndirectField->setAccess(AS);
4919         IndirectField->setImplicit();
4920         SemaRef.PushOnScopeChains(IndirectField, S);
4921 
4922         // That includes picking up the appropriate access specifier.
4923         if (AS != AS_none) IndirectField->setAccess(AS);
4924 
4925         Chaining.resize(OldChainingSize);
4926       }
4927     }
4928   }
4929 
4930   return Invalid;
4931 }
4932 
4933 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4934 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4935 /// illegal input values are mapped to SC_None.
4936 static StorageClass
4937 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4938   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4939   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4940          "Parser allowed 'typedef' as storage class VarDecl.");
4941   switch (StorageClassSpec) {
4942   case DeclSpec::SCS_unspecified:    return SC_None;
4943   case DeclSpec::SCS_extern:
4944     if (DS.isExternInLinkageSpec())
4945       return SC_None;
4946     return SC_Extern;
4947   case DeclSpec::SCS_static:         return SC_Static;
4948   case DeclSpec::SCS_auto:           return SC_Auto;
4949   case DeclSpec::SCS_register:       return SC_Register;
4950   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4951     // Illegal SCSs map to None: error reporting is up to the caller.
4952   case DeclSpec::SCS_mutable:        // Fall through.
4953   case DeclSpec::SCS_typedef:        return SC_None;
4954   }
4955   llvm_unreachable("unknown storage class specifier");
4956 }
4957 
4958 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4959   assert(Record->hasInClassInitializer());
4960 
4961   for (const auto *I : Record->decls()) {
4962     const auto *FD = dyn_cast<FieldDecl>(I);
4963     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4964       FD = IFD->getAnonField();
4965     if (FD && FD->hasInClassInitializer())
4966       return FD->getLocation();
4967   }
4968 
4969   llvm_unreachable("couldn't find in-class initializer");
4970 }
4971 
4972 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4973                                       SourceLocation DefaultInitLoc) {
4974   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4975     return;
4976 
4977   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4978   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4979 }
4980 
4981 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4982                                       CXXRecordDecl *AnonUnion) {
4983   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4984     return;
4985 
4986   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4987 }
4988 
4989 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4990 /// anonymous structure or union. Anonymous unions are a C++ feature
4991 /// (C++ [class.union]) and a C11 feature; anonymous structures
4992 /// are a C11 feature and GNU C++ extension.
4993 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4994                                         AccessSpecifier AS,
4995                                         RecordDecl *Record,
4996                                         const PrintingPolicy &Policy) {
4997   DeclContext *Owner = Record->getDeclContext();
4998 
4999   // Diagnose whether this anonymous struct/union is an extension.
5000   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5001     Diag(Record->getLocation(), diag::ext_anonymous_union);
5002   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5003     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5004   else if (!Record->isUnion() && !getLangOpts().C11)
5005     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5006 
5007   // C and C++ require different kinds of checks for anonymous
5008   // structs/unions.
5009   bool Invalid = false;
5010   if (getLangOpts().CPlusPlus) {
5011     const char *PrevSpec = nullptr;
5012     if (Record->isUnion()) {
5013       // C++ [class.union]p6:
5014       // C++17 [class.union.anon]p2:
5015       //   Anonymous unions declared in a named namespace or in the
5016       //   global namespace shall be declared static.
5017       unsigned DiagID;
5018       DeclContext *OwnerScope = Owner->getRedeclContext();
5019       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5020           (OwnerScope->isTranslationUnit() ||
5021            (OwnerScope->isNamespace() &&
5022             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5023         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5024           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5025 
5026         // Recover by adding 'static'.
5027         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5028                                PrevSpec, DiagID, Policy);
5029       }
5030       // C++ [class.union]p6:
5031       //   A storage class is not allowed in a declaration of an
5032       //   anonymous union in a class scope.
5033       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5034                isa<RecordDecl>(Owner)) {
5035         Diag(DS.getStorageClassSpecLoc(),
5036              diag::err_anonymous_union_with_storage_spec)
5037           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5038 
5039         // Recover by removing the storage specifier.
5040         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5041                                SourceLocation(),
5042                                PrevSpec, DiagID, Context.getPrintingPolicy());
5043       }
5044     }
5045 
5046     // Ignore const/volatile/restrict qualifiers.
5047     if (DS.getTypeQualifiers()) {
5048       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5049         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5050           << Record->isUnion() << "const"
5051           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5052       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5053         Diag(DS.getVolatileSpecLoc(),
5054              diag::ext_anonymous_struct_union_qualified)
5055           << Record->isUnion() << "volatile"
5056           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5057       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5058         Diag(DS.getRestrictSpecLoc(),
5059              diag::ext_anonymous_struct_union_qualified)
5060           << Record->isUnion() << "restrict"
5061           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5062       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5063         Diag(DS.getAtomicSpecLoc(),
5064              diag::ext_anonymous_struct_union_qualified)
5065           << Record->isUnion() << "_Atomic"
5066           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5067       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5068         Diag(DS.getUnalignedSpecLoc(),
5069              diag::ext_anonymous_struct_union_qualified)
5070           << Record->isUnion() << "__unaligned"
5071           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5072 
5073       DS.ClearTypeQualifiers();
5074     }
5075 
5076     // C++ [class.union]p2:
5077     //   The member-specification of an anonymous union shall only
5078     //   define non-static data members. [Note: nested types and
5079     //   functions cannot be declared within an anonymous union. ]
5080     for (auto *Mem : Record->decls()) {
5081       // Ignore invalid declarations; we already diagnosed them.
5082       if (Mem->isInvalidDecl())
5083         continue;
5084 
5085       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5086         // C++ [class.union]p3:
5087         //   An anonymous union shall not have private or protected
5088         //   members (clause 11).
5089         assert(FD->getAccess() != AS_none);
5090         if (FD->getAccess() != AS_public) {
5091           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5092             << Record->isUnion() << (FD->getAccess() == AS_protected);
5093           Invalid = true;
5094         }
5095 
5096         // C++ [class.union]p1
5097         //   An object of a class with a non-trivial constructor, a non-trivial
5098         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5099         //   assignment operator cannot be a member of a union, nor can an
5100         //   array of such objects.
5101         if (CheckNontrivialField(FD))
5102           Invalid = true;
5103       } else if (Mem->isImplicit()) {
5104         // Any implicit members are fine.
5105       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5106         // This is a type that showed up in an
5107         // elaborated-type-specifier inside the anonymous struct or
5108         // union, but which actually declares a type outside of the
5109         // anonymous struct or union. It's okay.
5110       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5111         if (!MemRecord->isAnonymousStructOrUnion() &&
5112             MemRecord->getDeclName()) {
5113           // Visual C++ allows type definition in anonymous struct or union.
5114           if (getLangOpts().MicrosoftExt)
5115             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5116               << Record->isUnion();
5117           else {
5118             // This is a nested type declaration.
5119             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5120               << Record->isUnion();
5121             Invalid = true;
5122           }
5123         } else {
5124           // This is an anonymous type definition within another anonymous type.
5125           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5126           // not part of standard C++.
5127           Diag(MemRecord->getLocation(),
5128                diag::ext_anonymous_record_with_anonymous_type)
5129             << Record->isUnion();
5130         }
5131       } else if (isa<AccessSpecDecl>(Mem)) {
5132         // Any access specifier is fine.
5133       } else if (isa<StaticAssertDecl>(Mem)) {
5134         // In C++1z, static_assert declarations are also fine.
5135       } else {
5136         // We have something that isn't a non-static data
5137         // member. Complain about it.
5138         unsigned DK = diag::err_anonymous_record_bad_member;
5139         if (isa<TypeDecl>(Mem))
5140           DK = diag::err_anonymous_record_with_type;
5141         else if (isa<FunctionDecl>(Mem))
5142           DK = diag::err_anonymous_record_with_function;
5143         else if (isa<VarDecl>(Mem))
5144           DK = diag::err_anonymous_record_with_static;
5145 
5146         // Visual C++ allows type definition in anonymous struct or union.
5147         if (getLangOpts().MicrosoftExt &&
5148             DK == diag::err_anonymous_record_with_type)
5149           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5150             << Record->isUnion();
5151         else {
5152           Diag(Mem->getLocation(), DK) << Record->isUnion();
5153           Invalid = true;
5154         }
5155       }
5156     }
5157 
5158     // C++11 [class.union]p8 (DR1460):
5159     //   At most one variant member of a union may have a
5160     //   brace-or-equal-initializer.
5161     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5162         Owner->isRecord())
5163       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5164                                 cast<CXXRecordDecl>(Record));
5165   }
5166 
5167   if (!Record->isUnion() && !Owner->isRecord()) {
5168     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5169       << getLangOpts().CPlusPlus;
5170     Invalid = true;
5171   }
5172 
5173   // C++ [dcl.dcl]p3:
5174   //   [If there are no declarators], and except for the declaration of an
5175   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5176   //   names into the program
5177   // C++ [class.mem]p2:
5178   //   each such member-declaration shall either declare at least one member
5179   //   name of the class or declare at least one unnamed bit-field
5180   //
5181   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5182   if (getLangOpts().CPlusPlus && Record->field_empty())
5183     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5184 
5185   // Mock up a declarator.
5186   Declarator Dc(DS, DeclaratorContext::MemberContext);
5187   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5188   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5189 
5190   // Create a declaration for this anonymous struct/union.
5191   NamedDecl *Anon = nullptr;
5192   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5193     Anon = FieldDecl::Create(
5194         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5195         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5196         /*BitWidth=*/nullptr, /*Mutable=*/false,
5197         /*InitStyle=*/ICIS_NoInit);
5198     Anon->setAccess(AS);
5199     ProcessDeclAttributes(S, Anon, Dc);
5200 
5201     if (getLangOpts().CPlusPlus)
5202       FieldCollector->Add(cast<FieldDecl>(Anon));
5203   } else {
5204     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5205     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5206     if (SCSpec == DeclSpec::SCS_mutable) {
5207       // mutable can only appear on non-static class members, so it's always
5208       // an error here
5209       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5210       Invalid = true;
5211       SC = SC_None;
5212     }
5213 
5214     assert(DS.getAttributes().empty() && "No attribute expected");
5215     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5216                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5217                            Context.getTypeDeclType(Record), TInfo, SC);
5218 
5219     // Default-initialize the implicit variable. This initialization will be
5220     // trivial in almost all cases, except if a union member has an in-class
5221     // initializer:
5222     //   union { int n = 0; };
5223     ActOnUninitializedDecl(Anon);
5224   }
5225   Anon->setImplicit();
5226 
5227   // Mark this as an anonymous struct/union type.
5228   Record->setAnonymousStructOrUnion(true);
5229 
5230   // Add the anonymous struct/union object to the current
5231   // context. We'll be referencing this object when we refer to one of
5232   // its members.
5233   Owner->addDecl(Anon);
5234 
5235   // Inject the members of the anonymous struct/union into the owning
5236   // context and into the identifier resolver chain for name lookup
5237   // purposes.
5238   SmallVector<NamedDecl*, 2> Chain;
5239   Chain.push_back(Anon);
5240 
5241   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5242     Invalid = true;
5243 
5244   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5245     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5246       MangleNumberingContext *MCtx;
5247       Decl *ManglingContextDecl;
5248       std::tie(MCtx, ManglingContextDecl) =
5249           getCurrentMangleNumberContext(NewVD->getDeclContext());
5250       if (MCtx) {
5251         Context.setManglingNumber(
5252             NewVD, MCtx->getManglingNumber(
5253                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5254         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5255       }
5256     }
5257   }
5258 
5259   if (Invalid)
5260     Anon->setInvalidDecl();
5261 
5262   return Anon;
5263 }
5264 
5265 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5266 /// Microsoft C anonymous structure.
5267 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5268 /// Example:
5269 ///
5270 /// struct A { int a; };
5271 /// struct B { struct A; int b; };
5272 ///
5273 /// void foo() {
5274 ///   B var;
5275 ///   var.a = 3;
5276 /// }
5277 ///
5278 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5279                                            RecordDecl *Record) {
5280   assert(Record && "expected a record!");
5281 
5282   // Mock up a declarator.
5283   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5284   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5285   assert(TInfo && "couldn't build declarator info for anonymous struct");
5286 
5287   auto *ParentDecl = cast<RecordDecl>(CurContext);
5288   QualType RecTy = Context.getTypeDeclType(Record);
5289 
5290   // Create a declaration for this anonymous struct.
5291   NamedDecl *Anon =
5292       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5293                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5294                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5295                         /*InitStyle=*/ICIS_NoInit);
5296   Anon->setImplicit();
5297 
5298   // Add the anonymous struct object to the current context.
5299   CurContext->addDecl(Anon);
5300 
5301   // Inject the members of the anonymous struct into the current
5302   // context and into the identifier resolver chain for name lookup
5303   // purposes.
5304   SmallVector<NamedDecl*, 2> Chain;
5305   Chain.push_back(Anon);
5306 
5307   RecordDecl *RecordDef = Record->getDefinition();
5308   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5309                                diag::err_field_incomplete_or_sizeless) ||
5310       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5311                                           AS_none, Chain)) {
5312     Anon->setInvalidDecl();
5313     ParentDecl->setInvalidDecl();
5314   }
5315 
5316   return Anon;
5317 }
5318 
5319 /// GetNameForDeclarator - Determine the full declaration name for the
5320 /// given Declarator.
5321 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5322   return GetNameFromUnqualifiedId(D.getName());
5323 }
5324 
5325 /// Retrieves the declaration name from a parsed unqualified-id.
5326 DeclarationNameInfo
5327 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5328   DeclarationNameInfo NameInfo;
5329   NameInfo.setLoc(Name.StartLocation);
5330 
5331   switch (Name.getKind()) {
5332 
5333   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5334   case UnqualifiedIdKind::IK_Identifier:
5335     NameInfo.setName(Name.Identifier);
5336     return NameInfo;
5337 
5338   case UnqualifiedIdKind::IK_DeductionGuideName: {
5339     // C++ [temp.deduct.guide]p3:
5340     //   The simple-template-id shall name a class template specialization.
5341     //   The template-name shall be the same identifier as the template-name
5342     //   of the simple-template-id.
5343     // These together intend to imply that the template-name shall name a
5344     // class template.
5345     // FIXME: template<typename T> struct X {};
5346     //        template<typename T> using Y = X<T>;
5347     //        Y(int) -> Y<int>;
5348     //   satisfies these rules but does not name a class template.
5349     TemplateName TN = Name.TemplateName.get().get();
5350     auto *Template = TN.getAsTemplateDecl();
5351     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5352       Diag(Name.StartLocation,
5353            diag::err_deduction_guide_name_not_class_template)
5354         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5355       if (Template)
5356         Diag(Template->getLocation(), diag::note_template_decl_here);
5357       return DeclarationNameInfo();
5358     }
5359 
5360     NameInfo.setName(
5361         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5362     return NameInfo;
5363   }
5364 
5365   case UnqualifiedIdKind::IK_OperatorFunctionId:
5366     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5367                                            Name.OperatorFunctionId.Operator));
5368     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5369       = Name.OperatorFunctionId.SymbolLocations[0];
5370     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5371       = Name.EndLocation.getRawEncoding();
5372     return NameInfo;
5373 
5374   case UnqualifiedIdKind::IK_LiteralOperatorId:
5375     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5376                                                            Name.Identifier));
5377     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5378     return NameInfo;
5379 
5380   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5381     TypeSourceInfo *TInfo;
5382     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5383     if (Ty.isNull())
5384       return DeclarationNameInfo();
5385     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5386                                                Context.getCanonicalType(Ty)));
5387     NameInfo.setNamedTypeInfo(TInfo);
5388     return NameInfo;
5389   }
5390 
5391   case UnqualifiedIdKind::IK_ConstructorName: {
5392     TypeSourceInfo *TInfo;
5393     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5394     if (Ty.isNull())
5395       return DeclarationNameInfo();
5396     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5397                                               Context.getCanonicalType(Ty)));
5398     NameInfo.setNamedTypeInfo(TInfo);
5399     return NameInfo;
5400   }
5401 
5402   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5403     // In well-formed code, we can only have a constructor
5404     // template-id that refers to the current context, so go there
5405     // to find the actual type being constructed.
5406     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5407     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5408       return DeclarationNameInfo();
5409 
5410     // Determine the type of the class being constructed.
5411     QualType CurClassType = Context.getTypeDeclType(CurClass);
5412 
5413     // FIXME: Check two things: that the template-id names the same type as
5414     // CurClassType, and that the template-id does not occur when the name
5415     // was qualified.
5416 
5417     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5418                                     Context.getCanonicalType(CurClassType)));
5419     // FIXME: should we retrieve TypeSourceInfo?
5420     NameInfo.setNamedTypeInfo(nullptr);
5421     return NameInfo;
5422   }
5423 
5424   case UnqualifiedIdKind::IK_DestructorName: {
5425     TypeSourceInfo *TInfo;
5426     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5427     if (Ty.isNull())
5428       return DeclarationNameInfo();
5429     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5430                                               Context.getCanonicalType(Ty)));
5431     NameInfo.setNamedTypeInfo(TInfo);
5432     return NameInfo;
5433   }
5434 
5435   case UnqualifiedIdKind::IK_TemplateId: {
5436     TemplateName TName = Name.TemplateId->Template.get();
5437     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5438     return Context.getNameForTemplate(TName, TNameLoc);
5439   }
5440 
5441   } // switch (Name.getKind())
5442 
5443   llvm_unreachable("Unknown name kind");
5444 }
5445 
5446 static QualType getCoreType(QualType Ty) {
5447   do {
5448     if (Ty->isPointerType() || Ty->isReferenceType())
5449       Ty = Ty->getPointeeType();
5450     else if (Ty->isArrayType())
5451       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5452     else
5453       return Ty.withoutLocalFastQualifiers();
5454   } while (true);
5455 }
5456 
5457 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5458 /// and Definition have "nearly" matching parameters. This heuristic is
5459 /// used to improve diagnostics in the case where an out-of-line function
5460 /// definition doesn't match any declaration within the class or namespace.
5461 /// Also sets Params to the list of indices to the parameters that differ
5462 /// between the declaration and the definition. If hasSimilarParameters
5463 /// returns true and Params is empty, then all of the parameters match.
5464 static bool hasSimilarParameters(ASTContext &Context,
5465                                      FunctionDecl *Declaration,
5466                                      FunctionDecl *Definition,
5467                                      SmallVectorImpl<unsigned> &Params) {
5468   Params.clear();
5469   if (Declaration->param_size() != Definition->param_size())
5470     return false;
5471   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5472     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5473     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5474 
5475     // The parameter types are identical
5476     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5477       continue;
5478 
5479     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5480     QualType DefParamBaseTy = getCoreType(DefParamTy);
5481     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5482     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5483 
5484     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5485         (DeclTyName && DeclTyName == DefTyName))
5486       Params.push_back(Idx);
5487     else  // The two parameters aren't even close
5488       return false;
5489   }
5490 
5491   return true;
5492 }
5493 
5494 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5495 /// declarator needs to be rebuilt in the current instantiation.
5496 /// Any bits of declarator which appear before the name are valid for
5497 /// consideration here.  That's specifically the type in the decl spec
5498 /// and the base type in any member-pointer chunks.
5499 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5500                                                     DeclarationName Name) {
5501   // The types we specifically need to rebuild are:
5502   //   - typenames, typeofs, and decltypes
5503   //   - types which will become injected class names
5504   // Of course, we also need to rebuild any type referencing such a
5505   // type.  It's safest to just say "dependent", but we call out a
5506   // few cases here.
5507 
5508   DeclSpec &DS = D.getMutableDeclSpec();
5509   switch (DS.getTypeSpecType()) {
5510   case DeclSpec::TST_typename:
5511   case DeclSpec::TST_typeofType:
5512   case DeclSpec::TST_underlyingType:
5513   case DeclSpec::TST_atomic: {
5514     // Grab the type from the parser.
5515     TypeSourceInfo *TSI = nullptr;
5516     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5517     if (T.isNull() || !T->isDependentType()) break;
5518 
5519     // Make sure there's a type source info.  This isn't really much
5520     // of a waste; most dependent types should have type source info
5521     // attached already.
5522     if (!TSI)
5523       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5524 
5525     // Rebuild the type in the current instantiation.
5526     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5527     if (!TSI) return true;
5528 
5529     // Store the new type back in the decl spec.
5530     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5531     DS.UpdateTypeRep(LocType);
5532     break;
5533   }
5534 
5535   case DeclSpec::TST_decltype:
5536   case DeclSpec::TST_typeofExpr: {
5537     Expr *E = DS.getRepAsExpr();
5538     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5539     if (Result.isInvalid()) return true;
5540     DS.UpdateExprRep(Result.get());
5541     break;
5542   }
5543 
5544   default:
5545     // Nothing to do for these decl specs.
5546     break;
5547   }
5548 
5549   // It doesn't matter what order we do this in.
5550   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5551     DeclaratorChunk &Chunk = D.getTypeObject(I);
5552 
5553     // The only type information in the declarator which can come
5554     // before the declaration name is the base type of a member
5555     // pointer.
5556     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5557       continue;
5558 
5559     // Rebuild the scope specifier in-place.
5560     CXXScopeSpec &SS = Chunk.Mem.Scope();
5561     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5562       return true;
5563   }
5564 
5565   return false;
5566 }
5567 
5568 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5569   D.setFunctionDefinitionKind(FDK_Declaration);
5570   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5571 
5572   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5573       Dcl && Dcl->getDeclContext()->isFileContext())
5574     Dcl->setTopLevelDeclInObjCContainer();
5575 
5576   if (getLangOpts().OpenCL)
5577     setCurrentOpenCLExtensionForDecl(Dcl);
5578 
5579   return Dcl;
5580 }
5581 
5582 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5583 ///   If T is the name of a class, then each of the following shall have a
5584 ///   name different from T:
5585 ///     - every static data member of class T;
5586 ///     - every member function of class T
5587 ///     - every member of class T that is itself a type;
5588 /// \returns true if the declaration name violates these rules.
5589 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5590                                    DeclarationNameInfo NameInfo) {
5591   DeclarationName Name = NameInfo.getName();
5592 
5593   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5594   while (Record && Record->isAnonymousStructOrUnion())
5595     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5596   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5597     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5598     return true;
5599   }
5600 
5601   return false;
5602 }
5603 
5604 /// Diagnose a declaration whose declarator-id has the given
5605 /// nested-name-specifier.
5606 ///
5607 /// \param SS The nested-name-specifier of the declarator-id.
5608 ///
5609 /// \param DC The declaration context to which the nested-name-specifier
5610 /// resolves.
5611 ///
5612 /// \param Name The name of the entity being declared.
5613 ///
5614 /// \param Loc The location of the name of the entity being declared.
5615 ///
5616 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5617 /// we're declaring an explicit / partial specialization / instantiation.
5618 ///
5619 /// \returns true if we cannot safely recover from this error, false otherwise.
5620 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5621                                         DeclarationName Name,
5622                                         SourceLocation Loc, bool IsTemplateId) {
5623   DeclContext *Cur = CurContext;
5624   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5625     Cur = Cur->getParent();
5626 
5627   // If the user provided a superfluous scope specifier that refers back to the
5628   // class in which the entity is already declared, diagnose and ignore it.
5629   //
5630   // class X {
5631   //   void X::f();
5632   // };
5633   //
5634   // Note, it was once ill-formed to give redundant qualification in all
5635   // contexts, but that rule was removed by DR482.
5636   if (Cur->Equals(DC)) {
5637     if (Cur->isRecord()) {
5638       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5639                                       : diag::err_member_extra_qualification)
5640         << Name << FixItHint::CreateRemoval(SS.getRange());
5641       SS.clear();
5642     } else {
5643       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5644     }
5645     return false;
5646   }
5647 
5648   // Check whether the qualifying scope encloses the scope of the original
5649   // declaration. For a template-id, we perform the checks in
5650   // CheckTemplateSpecializationScope.
5651   if (!Cur->Encloses(DC) && !IsTemplateId) {
5652     if (Cur->isRecord())
5653       Diag(Loc, diag::err_member_qualification)
5654         << Name << SS.getRange();
5655     else if (isa<TranslationUnitDecl>(DC))
5656       Diag(Loc, diag::err_invalid_declarator_global_scope)
5657         << Name << SS.getRange();
5658     else if (isa<FunctionDecl>(Cur))
5659       Diag(Loc, diag::err_invalid_declarator_in_function)
5660         << Name << SS.getRange();
5661     else if (isa<BlockDecl>(Cur))
5662       Diag(Loc, diag::err_invalid_declarator_in_block)
5663         << Name << SS.getRange();
5664     else
5665       Diag(Loc, diag::err_invalid_declarator_scope)
5666       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5667 
5668     return true;
5669   }
5670 
5671   if (Cur->isRecord()) {
5672     // Cannot qualify members within a class.
5673     Diag(Loc, diag::err_member_qualification)
5674       << Name << SS.getRange();
5675     SS.clear();
5676 
5677     // C++ constructors and destructors with incorrect scopes can break
5678     // our AST invariants by having the wrong underlying types. If
5679     // that's the case, then drop this declaration entirely.
5680     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5681          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5682         !Context.hasSameType(Name.getCXXNameType(),
5683                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5684       return true;
5685 
5686     return false;
5687   }
5688 
5689   // C++11 [dcl.meaning]p1:
5690   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5691   //   not begin with a decltype-specifer"
5692   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5693   while (SpecLoc.getPrefix())
5694     SpecLoc = SpecLoc.getPrefix();
5695   if (dyn_cast_or_null<DecltypeType>(
5696         SpecLoc.getNestedNameSpecifier()->getAsType()))
5697     Diag(Loc, diag::err_decltype_in_declarator)
5698       << SpecLoc.getTypeLoc().getSourceRange();
5699 
5700   return false;
5701 }
5702 
5703 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5704                                   MultiTemplateParamsArg TemplateParamLists) {
5705   // TODO: consider using NameInfo for diagnostic.
5706   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5707   DeclarationName Name = NameInfo.getName();
5708 
5709   // All of these full declarators require an identifier.  If it doesn't have
5710   // one, the ParsedFreeStandingDeclSpec action should be used.
5711   if (D.isDecompositionDeclarator()) {
5712     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5713   } else if (!Name) {
5714     if (!D.isInvalidType())  // Reject this if we think it is valid.
5715       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5716           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5717     return nullptr;
5718   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5719     return nullptr;
5720 
5721   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5722   // we find one that is.
5723   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5724          (S->getFlags() & Scope::TemplateParamScope) != 0)
5725     S = S->getParent();
5726 
5727   DeclContext *DC = CurContext;
5728   if (D.getCXXScopeSpec().isInvalid())
5729     D.setInvalidType();
5730   else if (D.getCXXScopeSpec().isSet()) {
5731     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5732                                         UPPC_DeclarationQualifier))
5733       return nullptr;
5734 
5735     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5736     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5737     if (!DC || isa<EnumDecl>(DC)) {
5738       // If we could not compute the declaration context, it's because the
5739       // declaration context is dependent but does not refer to a class,
5740       // class template, or class template partial specialization. Complain
5741       // and return early, to avoid the coming semantic disaster.
5742       Diag(D.getIdentifierLoc(),
5743            diag::err_template_qualified_declarator_no_match)
5744         << D.getCXXScopeSpec().getScopeRep()
5745         << D.getCXXScopeSpec().getRange();
5746       return nullptr;
5747     }
5748     bool IsDependentContext = DC->isDependentContext();
5749 
5750     if (!IsDependentContext &&
5751         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5752       return nullptr;
5753 
5754     // If a class is incomplete, do not parse entities inside it.
5755     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5756       Diag(D.getIdentifierLoc(),
5757            diag::err_member_def_undefined_record)
5758         << Name << DC << D.getCXXScopeSpec().getRange();
5759       return nullptr;
5760     }
5761     if (!D.getDeclSpec().isFriendSpecified()) {
5762       if (diagnoseQualifiedDeclaration(
5763               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5764               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5765         if (DC->isRecord())
5766           return nullptr;
5767 
5768         D.setInvalidType();
5769       }
5770     }
5771 
5772     // Check whether we need to rebuild the type of the given
5773     // declaration in the current instantiation.
5774     if (EnteringContext && IsDependentContext &&
5775         TemplateParamLists.size() != 0) {
5776       ContextRAII SavedContext(*this, DC);
5777       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5778         D.setInvalidType();
5779     }
5780   }
5781 
5782   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5783   QualType R = TInfo->getType();
5784 
5785   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5786                                       UPPC_DeclarationType))
5787     D.setInvalidType();
5788 
5789   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5790                         forRedeclarationInCurContext());
5791 
5792   // See if this is a redefinition of a variable in the same scope.
5793   if (!D.getCXXScopeSpec().isSet()) {
5794     bool IsLinkageLookup = false;
5795     bool CreateBuiltins = false;
5796 
5797     // If the declaration we're planning to build will be a function
5798     // or object with linkage, then look for another declaration with
5799     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5800     //
5801     // If the declaration we're planning to build will be declared with
5802     // external linkage in the translation unit, create any builtin with
5803     // the same name.
5804     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5805       /* Do nothing*/;
5806     else if (CurContext->isFunctionOrMethod() &&
5807              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5808               R->isFunctionType())) {
5809       IsLinkageLookup = true;
5810       CreateBuiltins =
5811           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5812     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5813                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5814       CreateBuiltins = true;
5815 
5816     if (IsLinkageLookup) {
5817       Previous.clear(LookupRedeclarationWithLinkage);
5818       Previous.setRedeclarationKind(ForExternalRedeclaration);
5819     }
5820 
5821     LookupName(Previous, S, CreateBuiltins);
5822   } else { // Something like "int foo::x;"
5823     LookupQualifiedName(Previous, DC);
5824 
5825     // C++ [dcl.meaning]p1:
5826     //   When the declarator-id is qualified, the declaration shall refer to a
5827     //  previously declared member of the class or namespace to which the
5828     //  qualifier refers (or, in the case of a namespace, of an element of the
5829     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5830     //  thereof; [...]
5831     //
5832     // Note that we already checked the context above, and that we do not have
5833     // enough information to make sure that Previous contains the declaration
5834     // we want to match. For example, given:
5835     //
5836     //   class X {
5837     //     void f();
5838     //     void f(float);
5839     //   };
5840     //
5841     //   void X::f(int) { } // ill-formed
5842     //
5843     // In this case, Previous will point to the overload set
5844     // containing the two f's declared in X, but neither of them
5845     // matches.
5846 
5847     // C++ [dcl.meaning]p1:
5848     //   [...] the member shall not merely have been introduced by a
5849     //   using-declaration in the scope of the class or namespace nominated by
5850     //   the nested-name-specifier of the declarator-id.
5851     RemoveUsingDecls(Previous);
5852   }
5853 
5854   if (Previous.isSingleResult() &&
5855       Previous.getFoundDecl()->isTemplateParameter()) {
5856     // Maybe we will complain about the shadowed template parameter.
5857     if (!D.isInvalidType())
5858       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5859                                       Previous.getFoundDecl());
5860 
5861     // Just pretend that we didn't see the previous declaration.
5862     Previous.clear();
5863   }
5864 
5865   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5866     // Forget that the previous declaration is the injected-class-name.
5867     Previous.clear();
5868 
5869   // In C++, the previous declaration we find might be a tag type
5870   // (class or enum). In this case, the new declaration will hide the
5871   // tag type. Note that this applies to functions, function templates, and
5872   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5873   if (Previous.isSingleTagDecl() &&
5874       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5875       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5876     Previous.clear();
5877 
5878   // Check that there are no default arguments other than in the parameters
5879   // of a function declaration (C++ only).
5880   if (getLangOpts().CPlusPlus)
5881     CheckExtraCXXDefaultArguments(D);
5882 
5883   NamedDecl *New;
5884 
5885   bool AddToScope = true;
5886   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5887     if (TemplateParamLists.size()) {
5888       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5889       return nullptr;
5890     }
5891 
5892     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5893   } else if (R->isFunctionType()) {
5894     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5895                                   TemplateParamLists,
5896                                   AddToScope);
5897   } else {
5898     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5899                                   AddToScope);
5900   }
5901 
5902   if (!New)
5903     return nullptr;
5904 
5905   // If this has an identifier and is not a function template specialization,
5906   // add it to the scope stack.
5907   if (New->getDeclName() && AddToScope)
5908     PushOnScopeChains(New, S);
5909 
5910   if (isInOpenMPDeclareTargetContext())
5911     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5912 
5913   return New;
5914 }
5915 
5916 /// Helper method to turn variable array types into constant array
5917 /// types in certain situations which would otherwise be errors (for
5918 /// GCC compatibility).
5919 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5920                                                     ASTContext &Context,
5921                                                     bool &SizeIsNegative,
5922                                                     llvm::APSInt &Oversized) {
5923   // This method tries to turn a variable array into a constant
5924   // array even when the size isn't an ICE.  This is necessary
5925   // for compatibility with code that depends on gcc's buggy
5926   // constant expression folding, like struct {char x[(int)(char*)2];}
5927   SizeIsNegative = false;
5928   Oversized = 0;
5929 
5930   if (T->isDependentType())
5931     return QualType();
5932 
5933   QualifierCollector Qs;
5934   const Type *Ty = Qs.strip(T);
5935 
5936   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5937     QualType Pointee = PTy->getPointeeType();
5938     QualType FixedType =
5939         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5940                                             Oversized);
5941     if (FixedType.isNull()) return FixedType;
5942     FixedType = Context.getPointerType(FixedType);
5943     return Qs.apply(Context, FixedType);
5944   }
5945   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5946     QualType Inner = PTy->getInnerType();
5947     QualType FixedType =
5948         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5949                                             Oversized);
5950     if (FixedType.isNull()) return FixedType;
5951     FixedType = Context.getParenType(FixedType);
5952     return Qs.apply(Context, FixedType);
5953   }
5954 
5955   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5956   if (!VLATy)
5957     return QualType();
5958   // FIXME: We should probably handle this case
5959   if (VLATy->getElementType()->isVariablyModifiedType())
5960     return QualType();
5961 
5962   Expr::EvalResult Result;
5963   if (!VLATy->getSizeExpr() ||
5964       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5965     return QualType();
5966 
5967   llvm::APSInt Res = Result.Val.getInt();
5968 
5969   // Check whether the array size is negative.
5970   if (Res.isSigned() && Res.isNegative()) {
5971     SizeIsNegative = true;
5972     return QualType();
5973   }
5974 
5975   // Check whether the array is too large to be addressed.
5976   unsigned ActiveSizeBits
5977     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5978                                               Res);
5979   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5980     Oversized = Res;
5981     return QualType();
5982   }
5983 
5984   return Context.getConstantArrayType(
5985       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5986 }
5987 
5988 static void
5989 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5990   SrcTL = SrcTL.getUnqualifiedLoc();
5991   DstTL = DstTL.getUnqualifiedLoc();
5992   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5993     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5994     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5995                                       DstPTL.getPointeeLoc());
5996     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5997     return;
5998   }
5999   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6000     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6001     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6002                                       DstPTL.getInnerLoc());
6003     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6004     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6005     return;
6006   }
6007   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6008   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6009   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6010   TypeLoc DstElemTL = DstATL.getElementLoc();
6011   DstElemTL.initializeFullCopy(SrcElemTL);
6012   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6013   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6014   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6015 }
6016 
6017 /// Helper method to turn variable array types into constant array
6018 /// types in certain situations which would otherwise be errors (for
6019 /// GCC compatibility).
6020 static TypeSourceInfo*
6021 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6022                                               ASTContext &Context,
6023                                               bool &SizeIsNegative,
6024                                               llvm::APSInt &Oversized) {
6025   QualType FixedTy
6026     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6027                                           SizeIsNegative, Oversized);
6028   if (FixedTy.isNull())
6029     return nullptr;
6030   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6031   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6032                                     FixedTInfo->getTypeLoc());
6033   return FixedTInfo;
6034 }
6035 
6036 /// Register the given locally-scoped extern "C" declaration so
6037 /// that it can be found later for redeclarations. We include any extern "C"
6038 /// declaration that is not visible in the translation unit here, not just
6039 /// function-scope declarations.
6040 void
6041 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6042   if (!getLangOpts().CPlusPlus &&
6043       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6044     // Don't need to track declarations in the TU in C.
6045     return;
6046 
6047   // Note that we have a locally-scoped external with this name.
6048   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6049 }
6050 
6051 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6052   // FIXME: We can have multiple results via __attribute__((overloadable)).
6053   auto Result = Context.getExternCContextDecl()->lookup(Name);
6054   return Result.empty() ? nullptr : *Result.begin();
6055 }
6056 
6057 /// Diagnose function specifiers on a declaration of an identifier that
6058 /// does not identify a function.
6059 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6060   // FIXME: We should probably indicate the identifier in question to avoid
6061   // confusion for constructs like "virtual int a(), b;"
6062   if (DS.isVirtualSpecified())
6063     Diag(DS.getVirtualSpecLoc(),
6064          diag::err_virtual_non_function);
6065 
6066   if (DS.hasExplicitSpecifier())
6067     Diag(DS.getExplicitSpecLoc(),
6068          diag::err_explicit_non_function);
6069 
6070   if (DS.isNoreturnSpecified())
6071     Diag(DS.getNoreturnSpecLoc(),
6072          diag::err_noreturn_non_function);
6073 }
6074 
6075 NamedDecl*
6076 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6077                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6078   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6079   if (D.getCXXScopeSpec().isSet()) {
6080     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6081       << D.getCXXScopeSpec().getRange();
6082     D.setInvalidType();
6083     // Pretend we didn't see the scope specifier.
6084     DC = CurContext;
6085     Previous.clear();
6086   }
6087 
6088   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6089 
6090   if (D.getDeclSpec().isInlineSpecified())
6091     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6092         << getLangOpts().CPlusPlus17;
6093   if (D.getDeclSpec().hasConstexprSpecifier())
6094     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6095         << 1 << D.getDeclSpec().getConstexprSpecifier();
6096 
6097   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6098     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6099       Diag(D.getName().StartLocation,
6100            diag::err_deduction_guide_invalid_specifier)
6101           << "typedef";
6102     else
6103       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6104           << D.getName().getSourceRange();
6105     return nullptr;
6106   }
6107 
6108   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6109   if (!NewTD) return nullptr;
6110 
6111   // Handle attributes prior to checking for duplicates in MergeVarDecl
6112   ProcessDeclAttributes(S, NewTD, D);
6113 
6114   CheckTypedefForVariablyModifiedType(S, NewTD);
6115 
6116   bool Redeclaration = D.isRedeclaration();
6117   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6118   D.setRedeclaration(Redeclaration);
6119   return ND;
6120 }
6121 
6122 void
6123 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6124   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6125   // then it shall have block scope.
6126   // Note that variably modified types must be fixed before merging the decl so
6127   // that redeclarations will match.
6128   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6129   QualType T = TInfo->getType();
6130   if (T->isVariablyModifiedType()) {
6131     setFunctionHasBranchProtectedScope();
6132 
6133     if (S->getFnParent() == nullptr) {
6134       bool SizeIsNegative;
6135       llvm::APSInt Oversized;
6136       TypeSourceInfo *FixedTInfo =
6137         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6138                                                       SizeIsNegative,
6139                                                       Oversized);
6140       if (FixedTInfo) {
6141         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6142         NewTD->setTypeSourceInfo(FixedTInfo);
6143       } else {
6144         if (SizeIsNegative)
6145           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6146         else if (T->isVariableArrayType())
6147           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6148         else if (Oversized.getBoolValue())
6149           Diag(NewTD->getLocation(), diag::err_array_too_large)
6150             << Oversized.toString(10);
6151         else
6152           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6153         NewTD->setInvalidDecl();
6154       }
6155     }
6156   }
6157 }
6158 
6159 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6160 /// declares a typedef-name, either using the 'typedef' type specifier or via
6161 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6162 NamedDecl*
6163 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6164                            LookupResult &Previous, bool &Redeclaration) {
6165 
6166   // Find the shadowed declaration before filtering for scope.
6167   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6168 
6169   // Merge the decl with the existing one if appropriate. If the decl is
6170   // in an outer scope, it isn't the same thing.
6171   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6172                        /*AllowInlineNamespace*/false);
6173   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6174   if (!Previous.empty()) {
6175     Redeclaration = true;
6176     MergeTypedefNameDecl(S, NewTD, Previous);
6177   } else {
6178     inferGslPointerAttribute(NewTD);
6179   }
6180 
6181   if (ShadowedDecl && !Redeclaration)
6182     CheckShadow(NewTD, ShadowedDecl, Previous);
6183 
6184   // If this is the C FILE type, notify the AST context.
6185   if (IdentifierInfo *II = NewTD->getIdentifier())
6186     if (!NewTD->isInvalidDecl() &&
6187         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6188       if (II->isStr("FILE"))
6189         Context.setFILEDecl(NewTD);
6190       else if (II->isStr("jmp_buf"))
6191         Context.setjmp_bufDecl(NewTD);
6192       else if (II->isStr("sigjmp_buf"))
6193         Context.setsigjmp_bufDecl(NewTD);
6194       else if (II->isStr("ucontext_t"))
6195         Context.setucontext_tDecl(NewTD);
6196     }
6197 
6198   return NewTD;
6199 }
6200 
6201 /// Determines whether the given declaration is an out-of-scope
6202 /// previous declaration.
6203 ///
6204 /// This routine should be invoked when name lookup has found a
6205 /// previous declaration (PrevDecl) that is not in the scope where a
6206 /// new declaration by the same name is being introduced. If the new
6207 /// declaration occurs in a local scope, previous declarations with
6208 /// linkage may still be considered previous declarations (C99
6209 /// 6.2.2p4-5, C++ [basic.link]p6).
6210 ///
6211 /// \param PrevDecl the previous declaration found by name
6212 /// lookup
6213 ///
6214 /// \param DC the context in which the new declaration is being
6215 /// declared.
6216 ///
6217 /// \returns true if PrevDecl is an out-of-scope previous declaration
6218 /// for a new delcaration with the same name.
6219 static bool
6220 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6221                                 ASTContext &Context) {
6222   if (!PrevDecl)
6223     return false;
6224 
6225   if (!PrevDecl->hasLinkage())
6226     return false;
6227 
6228   if (Context.getLangOpts().CPlusPlus) {
6229     // C++ [basic.link]p6:
6230     //   If there is a visible declaration of an entity with linkage
6231     //   having the same name and type, ignoring entities declared
6232     //   outside the innermost enclosing namespace scope, the block
6233     //   scope declaration declares that same entity and receives the
6234     //   linkage of the previous declaration.
6235     DeclContext *OuterContext = DC->getRedeclContext();
6236     if (!OuterContext->isFunctionOrMethod())
6237       // This rule only applies to block-scope declarations.
6238       return false;
6239 
6240     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6241     if (PrevOuterContext->isRecord())
6242       // We found a member function: ignore it.
6243       return false;
6244 
6245     // Find the innermost enclosing namespace for the new and
6246     // previous declarations.
6247     OuterContext = OuterContext->getEnclosingNamespaceContext();
6248     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6249 
6250     // The previous declaration is in a different namespace, so it
6251     // isn't the same function.
6252     if (!OuterContext->Equals(PrevOuterContext))
6253       return false;
6254   }
6255 
6256   return true;
6257 }
6258 
6259 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6260   CXXScopeSpec &SS = D.getCXXScopeSpec();
6261   if (!SS.isSet()) return;
6262   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6263 }
6264 
6265 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6266   QualType type = decl->getType();
6267   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6268   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6269     // Various kinds of declaration aren't allowed to be __autoreleasing.
6270     unsigned kind = -1U;
6271     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6272       if (var->hasAttr<BlocksAttr>())
6273         kind = 0; // __block
6274       else if (!var->hasLocalStorage())
6275         kind = 1; // global
6276     } else if (isa<ObjCIvarDecl>(decl)) {
6277       kind = 3; // ivar
6278     } else if (isa<FieldDecl>(decl)) {
6279       kind = 2; // field
6280     }
6281 
6282     if (kind != -1U) {
6283       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6284         << kind;
6285     }
6286   } else if (lifetime == Qualifiers::OCL_None) {
6287     // Try to infer lifetime.
6288     if (!type->isObjCLifetimeType())
6289       return false;
6290 
6291     lifetime = type->getObjCARCImplicitLifetime();
6292     type = Context.getLifetimeQualifiedType(type, lifetime);
6293     decl->setType(type);
6294   }
6295 
6296   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6297     // Thread-local variables cannot have lifetime.
6298     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6299         var->getTLSKind()) {
6300       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6301         << var->getType();
6302       return true;
6303     }
6304   }
6305 
6306   return false;
6307 }
6308 
6309 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6310   if (Decl->getType().hasAddressSpace())
6311     return;
6312   if (Decl->getType()->isDependentType())
6313     return;
6314   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6315     QualType Type = Var->getType();
6316     if (Type->isSamplerT() || Type->isVoidType())
6317       return;
6318     LangAS ImplAS = LangAS::opencl_private;
6319     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6320         Var->hasGlobalStorage())
6321       ImplAS = LangAS::opencl_global;
6322     // If the original type from a decayed type is an array type and that array
6323     // type has no address space yet, deduce it now.
6324     if (auto DT = dyn_cast<DecayedType>(Type)) {
6325       auto OrigTy = DT->getOriginalType();
6326       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6327         // Add the address space to the original array type and then propagate
6328         // that to the element type through `getAsArrayType`.
6329         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6330         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6331         // Re-generate the decayed type.
6332         Type = Context.getDecayedType(OrigTy);
6333       }
6334     }
6335     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6336     // Apply any qualifiers (including address space) from the array type to
6337     // the element type. This implements C99 6.7.3p8: "If the specification of
6338     // an array type includes any type qualifiers, the element type is so
6339     // qualified, not the array type."
6340     if (Type->isArrayType())
6341       Type = QualType(Context.getAsArrayType(Type), 0);
6342     Decl->setType(Type);
6343   }
6344 }
6345 
6346 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6347   // Ensure that an auto decl is deduced otherwise the checks below might cache
6348   // the wrong linkage.
6349   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6350 
6351   // 'weak' only applies to declarations with external linkage.
6352   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6353     if (!ND.isExternallyVisible()) {
6354       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6355       ND.dropAttr<WeakAttr>();
6356     }
6357   }
6358   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6359     if (ND.isExternallyVisible()) {
6360       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6361       ND.dropAttr<WeakRefAttr>();
6362       ND.dropAttr<AliasAttr>();
6363     }
6364   }
6365 
6366   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6367     if (VD->hasInit()) {
6368       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6369         assert(VD->isThisDeclarationADefinition() &&
6370                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6371         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6372         VD->dropAttr<AliasAttr>();
6373       }
6374     }
6375   }
6376 
6377   // 'selectany' only applies to externally visible variable declarations.
6378   // It does not apply to functions.
6379   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6380     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6381       S.Diag(Attr->getLocation(),
6382              diag::err_attribute_selectany_non_extern_data);
6383       ND.dropAttr<SelectAnyAttr>();
6384     }
6385   }
6386 
6387   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6388     auto *VD = dyn_cast<VarDecl>(&ND);
6389     bool IsAnonymousNS = false;
6390     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6391     if (VD) {
6392       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6393       while (NS && !IsAnonymousNS) {
6394         IsAnonymousNS = NS->isAnonymousNamespace();
6395         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6396       }
6397     }
6398     // dll attributes require external linkage. Static locals may have external
6399     // linkage but still cannot be explicitly imported or exported.
6400     // In Microsoft mode, a variable defined in anonymous namespace must have
6401     // external linkage in order to be exported.
6402     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6403     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6404         (!AnonNSInMicrosoftMode &&
6405          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6406       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6407         << &ND << Attr;
6408       ND.setInvalidDecl();
6409     }
6410   }
6411 
6412   // Virtual functions cannot be marked as 'notail'.
6413   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6414     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6415       if (MD->isVirtual()) {
6416         S.Diag(ND.getLocation(),
6417                diag::err_invalid_attribute_on_virtual_function)
6418             << Attr;
6419         ND.dropAttr<NotTailCalledAttr>();
6420       }
6421 
6422   // Check the attributes on the function type, if any.
6423   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6424     // Don't declare this variable in the second operand of the for-statement;
6425     // GCC miscompiles that by ending its lifetime before evaluating the
6426     // third operand. See gcc.gnu.org/PR86769.
6427     AttributedTypeLoc ATL;
6428     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6429          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6430          TL = ATL.getModifiedLoc()) {
6431       // The [[lifetimebound]] attribute can be applied to the implicit object
6432       // parameter of a non-static member function (other than a ctor or dtor)
6433       // by applying it to the function type.
6434       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6435         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6436         if (!MD || MD->isStatic()) {
6437           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6438               << !MD << A->getRange();
6439         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6440           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6441               << isa<CXXDestructorDecl>(MD) << A->getRange();
6442         }
6443       }
6444     }
6445   }
6446 }
6447 
6448 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6449                                            NamedDecl *NewDecl,
6450                                            bool IsSpecialization,
6451                                            bool IsDefinition) {
6452   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6453     return;
6454 
6455   bool IsTemplate = false;
6456   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6457     OldDecl = OldTD->getTemplatedDecl();
6458     IsTemplate = true;
6459     if (!IsSpecialization)
6460       IsDefinition = false;
6461   }
6462   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6463     NewDecl = NewTD->getTemplatedDecl();
6464     IsTemplate = true;
6465   }
6466 
6467   if (!OldDecl || !NewDecl)
6468     return;
6469 
6470   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6471   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6472   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6473   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6474 
6475   // dllimport and dllexport are inheritable attributes so we have to exclude
6476   // inherited attribute instances.
6477   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6478                     (NewExportAttr && !NewExportAttr->isInherited());
6479 
6480   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6481   // the only exception being explicit specializations.
6482   // Implicitly generated declarations are also excluded for now because there
6483   // is no other way to switch these to use dllimport or dllexport.
6484   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6485 
6486   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6487     // Allow with a warning for free functions and global variables.
6488     bool JustWarn = false;
6489     if (!OldDecl->isCXXClassMember()) {
6490       auto *VD = dyn_cast<VarDecl>(OldDecl);
6491       if (VD && !VD->getDescribedVarTemplate())
6492         JustWarn = true;
6493       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6494       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6495         JustWarn = true;
6496     }
6497 
6498     // We cannot change a declaration that's been used because IR has already
6499     // been emitted. Dllimported functions will still work though (modulo
6500     // address equality) as they can use the thunk.
6501     if (OldDecl->isUsed())
6502       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6503         JustWarn = false;
6504 
6505     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6506                                : diag::err_attribute_dll_redeclaration;
6507     S.Diag(NewDecl->getLocation(), DiagID)
6508         << NewDecl
6509         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6510     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6511     if (!JustWarn) {
6512       NewDecl->setInvalidDecl();
6513       return;
6514     }
6515   }
6516 
6517   // A redeclaration is not allowed to drop a dllimport attribute, the only
6518   // exceptions being inline function definitions (except for function
6519   // templates), local extern declarations, qualified friend declarations or
6520   // special MSVC extension: in the last case, the declaration is treated as if
6521   // it were marked dllexport.
6522   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6523   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6524   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6525     // Ignore static data because out-of-line definitions are diagnosed
6526     // separately.
6527     IsStaticDataMember = VD->isStaticDataMember();
6528     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6529                    VarDecl::DeclarationOnly;
6530   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6531     IsInline = FD->isInlined();
6532     IsQualifiedFriend = FD->getQualifier() &&
6533                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6534   }
6535 
6536   if (OldImportAttr && !HasNewAttr &&
6537       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6538       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6539     if (IsMicrosoft && IsDefinition) {
6540       S.Diag(NewDecl->getLocation(),
6541              diag::warn_redeclaration_without_import_attribute)
6542           << NewDecl;
6543       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6544       NewDecl->dropAttr<DLLImportAttr>();
6545       NewDecl->addAttr(
6546           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6547     } else {
6548       S.Diag(NewDecl->getLocation(),
6549              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6550           << NewDecl << OldImportAttr;
6551       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6552       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6553       OldDecl->dropAttr<DLLImportAttr>();
6554       NewDecl->dropAttr<DLLImportAttr>();
6555     }
6556   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6557     // In MinGW, seeing a function declared inline drops the dllimport
6558     // attribute.
6559     OldDecl->dropAttr<DLLImportAttr>();
6560     NewDecl->dropAttr<DLLImportAttr>();
6561     S.Diag(NewDecl->getLocation(),
6562            diag::warn_dllimport_dropped_from_inline_function)
6563         << NewDecl << OldImportAttr;
6564   }
6565 
6566   // A specialization of a class template member function is processed here
6567   // since it's a redeclaration. If the parent class is dllexport, the
6568   // specialization inherits that attribute. This doesn't happen automatically
6569   // since the parent class isn't instantiated until later.
6570   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6571     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6572         !NewImportAttr && !NewExportAttr) {
6573       if (const DLLExportAttr *ParentExportAttr =
6574               MD->getParent()->getAttr<DLLExportAttr>()) {
6575         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6576         NewAttr->setInherited(true);
6577         NewDecl->addAttr(NewAttr);
6578       }
6579     }
6580   }
6581 }
6582 
6583 /// Given that we are within the definition of the given function,
6584 /// will that definition behave like C99's 'inline', where the
6585 /// definition is discarded except for optimization purposes?
6586 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6587   // Try to avoid calling GetGVALinkageForFunction.
6588 
6589   // All cases of this require the 'inline' keyword.
6590   if (!FD->isInlined()) return false;
6591 
6592   // This is only possible in C++ with the gnu_inline attribute.
6593   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6594     return false;
6595 
6596   // Okay, go ahead and call the relatively-more-expensive function.
6597   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6598 }
6599 
6600 /// Determine whether a variable is extern "C" prior to attaching
6601 /// an initializer. We can't just call isExternC() here, because that
6602 /// will also compute and cache whether the declaration is externally
6603 /// visible, which might change when we attach the initializer.
6604 ///
6605 /// This can only be used if the declaration is known to not be a
6606 /// redeclaration of an internal linkage declaration.
6607 ///
6608 /// For instance:
6609 ///
6610 ///   auto x = []{};
6611 ///
6612 /// Attaching the initializer here makes this declaration not externally
6613 /// visible, because its type has internal linkage.
6614 ///
6615 /// FIXME: This is a hack.
6616 template<typename T>
6617 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6618   if (S.getLangOpts().CPlusPlus) {
6619     // In C++, the overloadable attribute negates the effects of extern "C".
6620     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6621       return false;
6622 
6623     // So do CUDA's host/device attributes.
6624     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6625                                  D->template hasAttr<CUDAHostAttr>()))
6626       return false;
6627   }
6628   return D->isExternC();
6629 }
6630 
6631 static bool shouldConsiderLinkage(const VarDecl *VD) {
6632   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6633   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6634       isa<OMPDeclareMapperDecl>(DC))
6635     return VD->hasExternalStorage();
6636   if (DC->isFileContext())
6637     return true;
6638   if (DC->isRecord())
6639     return false;
6640   if (isa<RequiresExprBodyDecl>(DC))
6641     return false;
6642   llvm_unreachable("Unexpected context");
6643 }
6644 
6645 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6646   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6647   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6648       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6649     return true;
6650   if (DC->isRecord())
6651     return false;
6652   llvm_unreachable("Unexpected context");
6653 }
6654 
6655 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6656                           ParsedAttr::Kind Kind) {
6657   // Check decl attributes on the DeclSpec.
6658   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6659     return true;
6660 
6661   // Walk the declarator structure, checking decl attributes that were in a type
6662   // position to the decl itself.
6663   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6664     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6665       return true;
6666   }
6667 
6668   // Finally, check attributes on the decl itself.
6669   return PD.getAttributes().hasAttribute(Kind);
6670 }
6671 
6672 /// Adjust the \c DeclContext for a function or variable that might be a
6673 /// function-local external declaration.
6674 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6675   if (!DC->isFunctionOrMethod())
6676     return false;
6677 
6678   // If this is a local extern function or variable declared within a function
6679   // template, don't add it into the enclosing namespace scope until it is
6680   // instantiated; it might have a dependent type right now.
6681   if (DC->isDependentContext())
6682     return true;
6683 
6684   // C++11 [basic.link]p7:
6685   //   When a block scope declaration of an entity with linkage is not found to
6686   //   refer to some other declaration, then that entity is a member of the
6687   //   innermost enclosing namespace.
6688   //
6689   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6690   // semantically-enclosing namespace, not a lexically-enclosing one.
6691   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6692     DC = DC->getParent();
6693   return true;
6694 }
6695 
6696 /// Returns true if given declaration has external C language linkage.
6697 static bool isDeclExternC(const Decl *D) {
6698   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6699     return FD->isExternC();
6700   if (const auto *VD = dyn_cast<VarDecl>(D))
6701     return VD->isExternC();
6702 
6703   llvm_unreachable("Unknown type of decl!");
6704 }
6705 /// Returns true if there hasn't been any invalid type diagnosed.
6706 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6707                                 DeclContext *DC, QualType R) {
6708   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6709   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6710   // argument.
6711   if (R->isImageType() || R->isPipeType()) {
6712     Se.Diag(D.getIdentifierLoc(),
6713             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6714         << R;
6715     D.setInvalidType();
6716     return false;
6717   }
6718 
6719   // OpenCL v1.2 s6.9.r:
6720   // The event type cannot be used to declare a program scope variable.
6721   // OpenCL v2.0 s6.9.q:
6722   // The clk_event_t and reserve_id_t types cannot be declared in program
6723   // scope.
6724   if (NULL == S->getParent()) {
6725     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6726       Se.Diag(D.getIdentifierLoc(),
6727               diag::err_invalid_type_for_program_scope_var)
6728           << R;
6729       D.setInvalidType();
6730       return false;
6731     }
6732   }
6733 
6734   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6735   QualType NR = R;
6736   while (NR->isPointerType()) {
6737     if (NR->isFunctionPointerType()) {
6738       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6739       D.setInvalidType();
6740       return false;
6741     }
6742     NR = NR->getPointeeType();
6743   }
6744 
6745   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6746     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6747     // half array type (unless the cl_khr_fp16 extension is enabled).
6748     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6749       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6750       D.setInvalidType();
6751       return false;
6752     }
6753   }
6754 
6755   // OpenCL v1.2 s6.9.r:
6756   // The event type cannot be used with the __local, __constant and __global
6757   // address space qualifiers.
6758   if (R->isEventT()) {
6759     if (R.getAddressSpace() != LangAS::opencl_private) {
6760       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6761       D.setInvalidType();
6762       return false;
6763     }
6764   }
6765 
6766   // C++ for OpenCL does not allow the thread_local storage qualifier.
6767   // OpenCL C does not support thread_local either, and
6768   // also reject all other thread storage class specifiers.
6769   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6770   if (TSC != TSCS_unspecified) {
6771     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6772     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6773             diag::err_opencl_unknown_type_specifier)
6774         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6775         << DeclSpec::getSpecifierName(TSC) << 1;
6776     D.setInvalidType();
6777     return false;
6778   }
6779 
6780   if (R->isSamplerT()) {
6781     // OpenCL v1.2 s6.9.b p4:
6782     // The sampler type cannot be used with the __local and __global address
6783     // space qualifiers.
6784     if (R.getAddressSpace() == LangAS::opencl_local ||
6785         R.getAddressSpace() == LangAS::opencl_global) {
6786       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6787       D.setInvalidType();
6788     }
6789 
6790     // OpenCL v1.2 s6.12.14.1:
6791     // A global sampler must be declared with either the constant address
6792     // space qualifier or with the const qualifier.
6793     if (DC->isTranslationUnit() &&
6794         !(R.getAddressSpace() == LangAS::opencl_constant ||
6795           R.isConstQualified())) {
6796       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6797       D.setInvalidType();
6798     }
6799     if (D.isInvalidType())
6800       return false;
6801   }
6802   return true;
6803 }
6804 
6805 NamedDecl *Sema::ActOnVariableDeclarator(
6806     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6807     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6808     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6809   QualType R = TInfo->getType();
6810   DeclarationName Name = GetNameForDeclarator(D).getName();
6811 
6812   IdentifierInfo *II = Name.getAsIdentifierInfo();
6813 
6814   if (D.isDecompositionDeclarator()) {
6815     // Take the name of the first declarator as our name for diagnostic
6816     // purposes.
6817     auto &Decomp = D.getDecompositionDeclarator();
6818     if (!Decomp.bindings().empty()) {
6819       II = Decomp.bindings()[0].Name;
6820       Name = II;
6821     }
6822   } else if (!II) {
6823     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6824     return nullptr;
6825   }
6826 
6827 
6828   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6829   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6830 
6831   // dllimport globals without explicit storage class are treated as extern. We
6832   // have to change the storage class this early to get the right DeclContext.
6833   if (SC == SC_None && !DC->isRecord() &&
6834       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6835       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6836     SC = SC_Extern;
6837 
6838   DeclContext *OriginalDC = DC;
6839   bool IsLocalExternDecl = SC == SC_Extern &&
6840                            adjustContextForLocalExternDecl(DC);
6841 
6842   if (SCSpec == DeclSpec::SCS_mutable) {
6843     // mutable can only appear on non-static class members, so it's always
6844     // an error here
6845     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6846     D.setInvalidType();
6847     SC = SC_None;
6848   }
6849 
6850   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6851       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6852                               D.getDeclSpec().getStorageClassSpecLoc())) {
6853     // In C++11, the 'register' storage class specifier is deprecated.
6854     // Suppress the warning in system macros, it's used in macros in some
6855     // popular C system headers, such as in glibc's htonl() macro.
6856     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6857          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6858                                    : diag::warn_deprecated_register)
6859       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6860   }
6861 
6862   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6863 
6864   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6865     // C99 6.9p2: The storage-class specifiers auto and register shall not
6866     // appear in the declaration specifiers in an external declaration.
6867     // Global Register+Asm is a GNU extension we support.
6868     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6869       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6870       D.setInvalidType();
6871     }
6872   }
6873 
6874   bool IsMemberSpecialization = false;
6875   bool IsVariableTemplateSpecialization = false;
6876   bool IsPartialSpecialization = false;
6877   bool IsVariableTemplate = false;
6878   VarDecl *NewVD = nullptr;
6879   VarTemplateDecl *NewTemplate = nullptr;
6880   TemplateParameterList *TemplateParams = nullptr;
6881   if (!getLangOpts().CPlusPlus) {
6882     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6883                             II, R, TInfo, SC);
6884 
6885     if (R->getContainedDeducedType())
6886       ParsingInitForAutoVars.insert(NewVD);
6887 
6888     if (D.isInvalidType())
6889       NewVD->setInvalidDecl();
6890 
6891     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6892         NewVD->hasLocalStorage())
6893       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6894                             NTCUC_AutoVar, NTCUK_Destruct);
6895   } else {
6896     bool Invalid = false;
6897 
6898     if (DC->isRecord() && !CurContext->isRecord()) {
6899       // This is an out-of-line definition of a static data member.
6900       switch (SC) {
6901       case SC_None:
6902         break;
6903       case SC_Static:
6904         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6905              diag::err_static_out_of_line)
6906           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6907         break;
6908       case SC_Auto:
6909       case SC_Register:
6910       case SC_Extern:
6911         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6912         // to names of variables declared in a block or to function parameters.
6913         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6914         // of class members
6915 
6916         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6917              diag::err_storage_class_for_static_member)
6918           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6919         break;
6920       case SC_PrivateExtern:
6921         llvm_unreachable("C storage class in c++!");
6922       }
6923     }
6924 
6925     if (SC == SC_Static && CurContext->isRecord()) {
6926       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6927         // Walk up the enclosing DeclContexts to check for any that are
6928         // incompatible with static data members.
6929         const DeclContext *FunctionOrMethod = nullptr;
6930         const CXXRecordDecl *AnonStruct = nullptr;
6931         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6932           if (Ctxt->isFunctionOrMethod()) {
6933             FunctionOrMethod = Ctxt;
6934             break;
6935           }
6936           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6937           if (ParentDecl && !ParentDecl->getDeclName()) {
6938             AnonStruct = ParentDecl;
6939             break;
6940           }
6941         }
6942         if (FunctionOrMethod) {
6943           // C++ [class.static.data]p5: A local class shall not have static data
6944           // members.
6945           Diag(D.getIdentifierLoc(),
6946                diag::err_static_data_member_not_allowed_in_local_class)
6947             << Name << RD->getDeclName() << RD->getTagKind();
6948         } else if (AnonStruct) {
6949           // C++ [class.static.data]p4: Unnamed classes and classes contained
6950           // directly or indirectly within unnamed classes shall not contain
6951           // static data members.
6952           Diag(D.getIdentifierLoc(),
6953                diag::err_static_data_member_not_allowed_in_anon_struct)
6954             << Name << AnonStruct->getTagKind();
6955           Invalid = true;
6956         } else if (RD->isUnion()) {
6957           // C++98 [class.union]p1: If a union contains a static data member,
6958           // the program is ill-formed. C++11 drops this restriction.
6959           Diag(D.getIdentifierLoc(),
6960                getLangOpts().CPlusPlus11
6961                  ? diag::warn_cxx98_compat_static_data_member_in_union
6962                  : diag::ext_static_data_member_in_union) << Name;
6963         }
6964       }
6965     }
6966 
6967     // Match up the template parameter lists with the scope specifier, then
6968     // determine whether we have a template or a template specialization.
6969     bool InvalidScope = false;
6970     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6971         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6972         D.getCXXScopeSpec(),
6973         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6974             ? D.getName().TemplateId
6975             : nullptr,
6976         TemplateParamLists,
6977         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6978     Invalid |= InvalidScope;
6979 
6980     if (TemplateParams) {
6981       if (!TemplateParams->size() &&
6982           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6983         // There is an extraneous 'template<>' for this variable. Complain
6984         // about it, but allow the declaration of the variable.
6985         Diag(TemplateParams->getTemplateLoc(),
6986              diag::err_template_variable_noparams)
6987           << II
6988           << SourceRange(TemplateParams->getTemplateLoc(),
6989                          TemplateParams->getRAngleLoc());
6990         TemplateParams = nullptr;
6991       } else {
6992         // Check that we can declare a template here.
6993         if (CheckTemplateDeclScope(S, TemplateParams))
6994           return nullptr;
6995 
6996         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6997           // This is an explicit specialization or a partial specialization.
6998           IsVariableTemplateSpecialization = true;
6999           IsPartialSpecialization = TemplateParams->size() > 0;
7000         } else { // if (TemplateParams->size() > 0)
7001           // This is a template declaration.
7002           IsVariableTemplate = true;
7003 
7004           // Only C++1y supports variable templates (N3651).
7005           Diag(D.getIdentifierLoc(),
7006                getLangOpts().CPlusPlus14
7007                    ? diag::warn_cxx11_compat_variable_template
7008                    : diag::ext_variable_template);
7009         }
7010       }
7011     } else {
7012       // Check that we can declare a member specialization here.
7013       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7014           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7015         return nullptr;
7016       assert((Invalid ||
7017               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7018              "should have a 'template<>' for this decl");
7019     }
7020 
7021     if (IsVariableTemplateSpecialization) {
7022       SourceLocation TemplateKWLoc =
7023           TemplateParamLists.size() > 0
7024               ? TemplateParamLists[0]->getTemplateLoc()
7025               : SourceLocation();
7026       DeclResult Res = ActOnVarTemplateSpecialization(
7027           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7028           IsPartialSpecialization);
7029       if (Res.isInvalid())
7030         return nullptr;
7031       NewVD = cast<VarDecl>(Res.get());
7032       AddToScope = false;
7033     } else if (D.isDecompositionDeclarator()) {
7034       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7035                                         D.getIdentifierLoc(), R, TInfo, SC,
7036                                         Bindings);
7037     } else
7038       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7039                               D.getIdentifierLoc(), II, R, TInfo, SC);
7040 
7041     // If this is supposed to be a variable template, create it as such.
7042     if (IsVariableTemplate) {
7043       NewTemplate =
7044           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7045                                   TemplateParams, NewVD);
7046       NewVD->setDescribedVarTemplate(NewTemplate);
7047     }
7048 
7049     // If this decl has an auto type in need of deduction, make a note of the
7050     // Decl so we can diagnose uses of it in its own initializer.
7051     if (R->getContainedDeducedType())
7052       ParsingInitForAutoVars.insert(NewVD);
7053 
7054     if (D.isInvalidType() || Invalid) {
7055       NewVD->setInvalidDecl();
7056       if (NewTemplate)
7057         NewTemplate->setInvalidDecl();
7058     }
7059 
7060     SetNestedNameSpecifier(*this, NewVD, D);
7061 
7062     // If we have any template parameter lists that don't directly belong to
7063     // the variable (matching the scope specifier), store them.
7064     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7065     if (TemplateParamLists.size() > VDTemplateParamLists)
7066       NewVD->setTemplateParameterListsInfo(
7067           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7068   }
7069 
7070   if (D.getDeclSpec().isInlineSpecified()) {
7071     if (!getLangOpts().CPlusPlus) {
7072       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7073           << 0;
7074     } else if (CurContext->isFunctionOrMethod()) {
7075       // 'inline' is not allowed on block scope variable declaration.
7076       Diag(D.getDeclSpec().getInlineSpecLoc(),
7077            diag::err_inline_declaration_block_scope) << Name
7078         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7079     } else {
7080       Diag(D.getDeclSpec().getInlineSpecLoc(),
7081            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7082                                      : diag::ext_inline_variable);
7083       NewVD->setInlineSpecified();
7084     }
7085   }
7086 
7087   // Set the lexical context. If the declarator has a C++ scope specifier, the
7088   // lexical context will be different from the semantic context.
7089   NewVD->setLexicalDeclContext(CurContext);
7090   if (NewTemplate)
7091     NewTemplate->setLexicalDeclContext(CurContext);
7092 
7093   if (IsLocalExternDecl) {
7094     if (D.isDecompositionDeclarator())
7095       for (auto *B : Bindings)
7096         B->setLocalExternDecl();
7097     else
7098       NewVD->setLocalExternDecl();
7099   }
7100 
7101   bool EmitTLSUnsupportedError = false;
7102   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7103     // C++11 [dcl.stc]p4:
7104     //   When thread_local is applied to a variable of block scope the
7105     //   storage-class-specifier static is implied if it does not appear
7106     //   explicitly.
7107     // Core issue: 'static' is not implied if the variable is declared
7108     //   'extern'.
7109     if (NewVD->hasLocalStorage() &&
7110         (SCSpec != DeclSpec::SCS_unspecified ||
7111          TSCS != DeclSpec::TSCS_thread_local ||
7112          !DC->isFunctionOrMethod()))
7113       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7114            diag::err_thread_non_global)
7115         << DeclSpec::getSpecifierName(TSCS);
7116     else if (!Context.getTargetInfo().isTLSSupported()) {
7117       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7118           getLangOpts().SYCLIsDevice) {
7119         // Postpone error emission until we've collected attributes required to
7120         // figure out whether it's a host or device variable and whether the
7121         // error should be ignored.
7122         EmitTLSUnsupportedError = true;
7123         // We still need to mark the variable as TLS so it shows up in AST with
7124         // proper storage class for other tools to use even if we're not going
7125         // to emit any code for it.
7126         NewVD->setTSCSpec(TSCS);
7127       } else
7128         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7129              diag::err_thread_unsupported);
7130     } else
7131       NewVD->setTSCSpec(TSCS);
7132   }
7133 
7134   switch (D.getDeclSpec().getConstexprSpecifier()) {
7135   case CSK_unspecified:
7136     break;
7137 
7138   case CSK_consteval:
7139     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7140         diag::err_constexpr_wrong_decl_kind)
7141       << D.getDeclSpec().getConstexprSpecifier();
7142     LLVM_FALLTHROUGH;
7143 
7144   case CSK_constexpr:
7145     NewVD->setConstexpr(true);
7146     MaybeAddCUDAConstantAttr(NewVD);
7147     // C++1z [dcl.spec.constexpr]p1:
7148     //   A static data member declared with the constexpr specifier is
7149     //   implicitly an inline variable.
7150     if (NewVD->isStaticDataMember() &&
7151         (getLangOpts().CPlusPlus17 ||
7152          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7153       NewVD->setImplicitlyInline();
7154     break;
7155 
7156   case CSK_constinit:
7157     if (!NewVD->hasGlobalStorage())
7158       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7159            diag::err_constinit_local_variable);
7160     else
7161       NewVD->addAttr(ConstInitAttr::Create(
7162           Context, D.getDeclSpec().getConstexprSpecLoc(),
7163           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7164     break;
7165   }
7166 
7167   // C99 6.7.4p3
7168   //   An inline definition of a function with external linkage shall
7169   //   not contain a definition of a modifiable object with static or
7170   //   thread storage duration...
7171   // We only apply this when the function is required to be defined
7172   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7173   // that a local variable with thread storage duration still has to
7174   // be marked 'static'.  Also note that it's possible to get these
7175   // semantics in C++ using __attribute__((gnu_inline)).
7176   if (SC == SC_Static && S->getFnParent() != nullptr &&
7177       !NewVD->getType().isConstQualified()) {
7178     FunctionDecl *CurFD = getCurFunctionDecl();
7179     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7180       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7181            diag::warn_static_local_in_extern_inline);
7182       MaybeSuggestAddingStaticToDecl(CurFD);
7183     }
7184   }
7185 
7186   if (D.getDeclSpec().isModulePrivateSpecified()) {
7187     if (IsVariableTemplateSpecialization)
7188       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7189           << (IsPartialSpecialization ? 1 : 0)
7190           << FixItHint::CreateRemoval(
7191                  D.getDeclSpec().getModulePrivateSpecLoc());
7192     else if (IsMemberSpecialization)
7193       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7194         << 2
7195         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7196     else if (NewVD->hasLocalStorage())
7197       Diag(NewVD->getLocation(), diag::err_module_private_local)
7198           << 0 << NewVD
7199           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7200           << FixItHint::CreateRemoval(
7201                  D.getDeclSpec().getModulePrivateSpecLoc());
7202     else {
7203       NewVD->setModulePrivate();
7204       if (NewTemplate)
7205         NewTemplate->setModulePrivate();
7206       for (auto *B : Bindings)
7207         B->setModulePrivate();
7208     }
7209   }
7210 
7211   if (getLangOpts().OpenCL) {
7212 
7213     deduceOpenCLAddressSpace(NewVD);
7214 
7215     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7216   }
7217 
7218   // Handle attributes prior to checking for duplicates in MergeVarDecl
7219   ProcessDeclAttributes(S, NewVD, D);
7220 
7221   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7222       getLangOpts().SYCLIsDevice) {
7223     if (EmitTLSUnsupportedError &&
7224         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7225          (getLangOpts().OpenMPIsDevice &&
7226           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7227       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7228            diag::err_thread_unsupported);
7229 
7230     if (EmitTLSUnsupportedError &&
7231         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7232       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7233     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7234     // storage [duration]."
7235     if (SC == SC_None && S->getFnParent() != nullptr &&
7236         (NewVD->hasAttr<CUDASharedAttr>() ||
7237          NewVD->hasAttr<CUDAConstantAttr>())) {
7238       NewVD->setStorageClass(SC_Static);
7239     }
7240   }
7241 
7242   // Ensure that dllimport globals without explicit storage class are treated as
7243   // extern. The storage class is set above using parsed attributes. Now we can
7244   // check the VarDecl itself.
7245   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7246          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7247          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7248 
7249   // In auto-retain/release, infer strong retension for variables of
7250   // retainable type.
7251   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7252     NewVD->setInvalidDecl();
7253 
7254   // Handle GNU asm-label extension (encoded as an attribute).
7255   if (Expr *E = (Expr*)D.getAsmLabel()) {
7256     // The parser guarantees this is a string.
7257     StringLiteral *SE = cast<StringLiteral>(E);
7258     StringRef Label = SE->getString();
7259     if (S->getFnParent() != nullptr) {
7260       switch (SC) {
7261       case SC_None:
7262       case SC_Auto:
7263         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7264         break;
7265       case SC_Register:
7266         // Local Named register
7267         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7268             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7269           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7270         break;
7271       case SC_Static:
7272       case SC_Extern:
7273       case SC_PrivateExtern:
7274         break;
7275       }
7276     } else if (SC == SC_Register) {
7277       // Global Named register
7278       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7279         const auto &TI = Context.getTargetInfo();
7280         bool HasSizeMismatch;
7281 
7282         if (!TI.isValidGCCRegisterName(Label))
7283           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7284         else if (!TI.validateGlobalRegisterVariable(Label,
7285                                                     Context.getTypeSize(R),
7286                                                     HasSizeMismatch))
7287           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7288         else if (HasSizeMismatch)
7289           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7290       }
7291 
7292       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7293         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7294         NewVD->setInvalidDecl(true);
7295       }
7296     }
7297 
7298     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7299                                         /*IsLiteralLabel=*/true,
7300                                         SE->getStrTokenLoc(0)));
7301   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7302     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7303       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7304     if (I != ExtnameUndeclaredIdentifiers.end()) {
7305       if (isDeclExternC(NewVD)) {
7306         NewVD->addAttr(I->second);
7307         ExtnameUndeclaredIdentifiers.erase(I);
7308       } else
7309         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7310             << /*Variable*/1 << NewVD;
7311     }
7312   }
7313 
7314   // Find the shadowed declaration before filtering for scope.
7315   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7316                                 ? getShadowedDeclaration(NewVD, Previous)
7317                                 : nullptr;
7318 
7319   // Don't consider existing declarations that are in a different
7320   // scope and are out-of-semantic-context declarations (if the new
7321   // declaration has linkage).
7322   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7323                        D.getCXXScopeSpec().isNotEmpty() ||
7324                        IsMemberSpecialization ||
7325                        IsVariableTemplateSpecialization);
7326 
7327   // Check whether the previous declaration is in the same block scope. This
7328   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7329   if (getLangOpts().CPlusPlus &&
7330       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7331     NewVD->setPreviousDeclInSameBlockScope(
7332         Previous.isSingleResult() && !Previous.isShadowed() &&
7333         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7334 
7335   if (!getLangOpts().CPlusPlus) {
7336     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7337   } else {
7338     // If this is an explicit specialization of a static data member, check it.
7339     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7340         CheckMemberSpecialization(NewVD, Previous))
7341       NewVD->setInvalidDecl();
7342 
7343     // Merge the decl with the existing one if appropriate.
7344     if (!Previous.empty()) {
7345       if (Previous.isSingleResult() &&
7346           isa<FieldDecl>(Previous.getFoundDecl()) &&
7347           D.getCXXScopeSpec().isSet()) {
7348         // The user tried to define a non-static data member
7349         // out-of-line (C++ [dcl.meaning]p1).
7350         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7351           << D.getCXXScopeSpec().getRange();
7352         Previous.clear();
7353         NewVD->setInvalidDecl();
7354       }
7355     } else if (D.getCXXScopeSpec().isSet()) {
7356       // No previous declaration in the qualifying scope.
7357       Diag(D.getIdentifierLoc(), diag::err_no_member)
7358         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7359         << D.getCXXScopeSpec().getRange();
7360       NewVD->setInvalidDecl();
7361     }
7362 
7363     if (!IsVariableTemplateSpecialization)
7364       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7365 
7366     if (NewTemplate) {
7367       VarTemplateDecl *PrevVarTemplate =
7368           NewVD->getPreviousDecl()
7369               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7370               : nullptr;
7371 
7372       // Check the template parameter list of this declaration, possibly
7373       // merging in the template parameter list from the previous variable
7374       // template declaration.
7375       if (CheckTemplateParameterList(
7376               TemplateParams,
7377               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7378                               : nullptr,
7379               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7380                DC->isDependentContext())
7381                   ? TPC_ClassTemplateMember
7382                   : TPC_VarTemplate))
7383         NewVD->setInvalidDecl();
7384 
7385       // If we are providing an explicit specialization of a static variable
7386       // template, make a note of that.
7387       if (PrevVarTemplate &&
7388           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7389         PrevVarTemplate->setMemberSpecialization();
7390     }
7391   }
7392 
7393   // Diagnose shadowed variables iff this isn't a redeclaration.
7394   if (ShadowedDecl && !D.isRedeclaration())
7395     CheckShadow(NewVD, ShadowedDecl, Previous);
7396 
7397   ProcessPragmaWeak(S, NewVD);
7398 
7399   // If this is the first declaration of an extern C variable, update
7400   // the map of such variables.
7401   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7402       isIncompleteDeclExternC(*this, NewVD))
7403     RegisterLocallyScopedExternCDecl(NewVD, S);
7404 
7405   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7406     MangleNumberingContext *MCtx;
7407     Decl *ManglingContextDecl;
7408     std::tie(MCtx, ManglingContextDecl) =
7409         getCurrentMangleNumberContext(NewVD->getDeclContext());
7410     if (MCtx) {
7411       Context.setManglingNumber(
7412           NewVD, MCtx->getManglingNumber(
7413                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7414       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7415     }
7416   }
7417 
7418   // Special handling of variable named 'main'.
7419   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7420       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7421       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7422 
7423     // C++ [basic.start.main]p3
7424     // A program that declares a variable main at global scope is ill-formed.
7425     if (getLangOpts().CPlusPlus)
7426       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7427 
7428     // In C, and external-linkage variable named main results in undefined
7429     // behavior.
7430     else if (NewVD->hasExternalFormalLinkage())
7431       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7432   }
7433 
7434   if (D.isRedeclaration() && !Previous.empty()) {
7435     NamedDecl *Prev = Previous.getRepresentativeDecl();
7436     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7437                                    D.isFunctionDefinition());
7438   }
7439 
7440   if (NewTemplate) {
7441     if (NewVD->isInvalidDecl())
7442       NewTemplate->setInvalidDecl();
7443     ActOnDocumentableDecl(NewTemplate);
7444     return NewTemplate;
7445   }
7446 
7447   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7448     CompleteMemberSpecialization(NewVD, Previous);
7449 
7450   return NewVD;
7451 }
7452 
7453 /// Enum describing the %select options in diag::warn_decl_shadow.
7454 enum ShadowedDeclKind {
7455   SDK_Local,
7456   SDK_Global,
7457   SDK_StaticMember,
7458   SDK_Field,
7459   SDK_Typedef,
7460   SDK_Using
7461 };
7462 
7463 /// Determine what kind of declaration we're shadowing.
7464 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7465                                                 const DeclContext *OldDC) {
7466   if (isa<TypeAliasDecl>(ShadowedDecl))
7467     return SDK_Using;
7468   else if (isa<TypedefDecl>(ShadowedDecl))
7469     return SDK_Typedef;
7470   else if (isa<RecordDecl>(OldDC))
7471     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7472 
7473   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7474 }
7475 
7476 /// Return the location of the capture if the given lambda captures the given
7477 /// variable \p VD, or an invalid source location otherwise.
7478 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7479                                          const VarDecl *VD) {
7480   for (const Capture &Capture : LSI->Captures) {
7481     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7482       return Capture.getLocation();
7483   }
7484   return SourceLocation();
7485 }
7486 
7487 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7488                                      const LookupResult &R) {
7489   // Only diagnose if we're shadowing an unambiguous field or variable.
7490   if (R.getResultKind() != LookupResult::Found)
7491     return false;
7492 
7493   // Return false if warning is ignored.
7494   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7495 }
7496 
7497 /// Return the declaration shadowed by the given variable \p D, or null
7498 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7499 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7500                                         const LookupResult &R) {
7501   if (!shouldWarnIfShadowedDecl(Diags, R))
7502     return nullptr;
7503 
7504   // Don't diagnose declarations at file scope.
7505   if (D->hasGlobalStorage())
7506     return nullptr;
7507 
7508   NamedDecl *ShadowedDecl = R.getFoundDecl();
7509   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7510              ? ShadowedDecl
7511              : nullptr;
7512 }
7513 
7514 /// Return the declaration shadowed by the given typedef \p D, or null
7515 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7516 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7517                                         const LookupResult &R) {
7518   // Don't warn if typedef declaration is part of a class
7519   if (D->getDeclContext()->isRecord())
7520     return nullptr;
7521 
7522   if (!shouldWarnIfShadowedDecl(Diags, R))
7523     return nullptr;
7524 
7525   NamedDecl *ShadowedDecl = R.getFoundDecl();
7526   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7527 }
7528 
7529 /// Diagnose variable or built-in function shadowing.  Implements
7530 /// -Wshadow.
7531 ///
7532 /// This method is called whenever a VarDecl is added to a "useful"
7533 /// scope.
7534 ///
7535 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7536 /// \param R the lookup of the name
7537 ///
7538 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7539                        const LookupResult &R) {
7540   DeclContext *NewDC = D->getDeclContext();
7541 
7542   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7543     // Fields are not shadowed by variables in C++ static methods.
7544     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7545       if (MD->isStatic())
7546         return;
7547 
7548     // Fields shadowed by constructor parameters are a special case. Usually
7549     // the constructor initializes the field with the parameter.
7550     if (isa<CXXConstructorDecl>(NewDC))
7551       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7552         // Remember that this was shadowed so we can either warn about its
7553         // modification or its existence depending on warning settings.
7554         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7555         return;
7556       }
7557   }
7558 
7559   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7560     if (shadowedVar->isExternC()) {
7561       // For shadowing external vars, make sure that we point to the global
7562       // declaration, not a locally scoped extern declaration.
7563       for (auto I : shadowedVar->redecls())
7564         if (I->isFileVarDecl()) {
7565           ShadowedDecl = I;
7566           break;
7567         }
7568     }
7569 
7570   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7571 
7572   unsigned WarningDiag = diag::warn_decl_shadow;
7573   SourceLocation CaptureLoc;
7574   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7575       isa<CXXMethodDecl>(NewDC)) {
7576     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7577       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7578         if (RD->getLambdaCaptureDefault() == LCD_None) {
7579           // Try to avoid warnings for lambdas with an explicit capture list.
7580           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7581           // Warn only when the lambda captures the shadowed decl explicitly.
7582           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7583           if (CaptureLoc.isInvalid())
7584             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7585         } else {
7586           // Remember that this was shadowed so we can avoid the warning if the
7587           // shadowed decl isn't captured and the warning settings allow it.
7588           cast<LambdaScopeInfo>(getCurFunction())
7589               ->ShadowingDecls.push_back(
7590                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7591           return;
7592         }
7593       }
7594 
7595       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7596         // A variable can't shadow a local variable in an enclosing scope, if
7597         // they are separated by a non-capturing declaration context.
7598         for (DeclContext *ParentDC = NewDC;
7599              ParentDC && !ParentDC->Equals(OldDC);
7600              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7601           // Only block literals, captured statements, and lambda expressions
7602           // can capture; other scopes don't.
7603           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7604               !isLambdaCallOperator(ParentDC)) {
7605             return;
7606           }
7607         }
7608       }
7609     }
7610   }
7611 
7612   // Only warn about certain kinds of shadowing for class members.
7613   if (NewDC && NewDC->isRecord()) {
7614     // In particular, don't warn about shadowing non-class members.
7615     if (!OldDC->isRecord())
7616       return;
7617 
7618     // TODO: should we warn about static data members shadowing
7619     // static data members from base classes?
7620 
7621     // TODO: don't diagnose for inaccessible shadowed members.
7622     // This is hard to do perfectly because we might friend the
7623     // shadowing context, but that's just a false negative.
7624   }
7625 
7626 
7627   DeclarationName Name = R.getLookupName();
7628 
7629   // Emit warning and note.
7630   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7631     return;
7632   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7633   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7634   if (!CaptureLoc.isInvalid())
7635     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7636         << Name << /*explicitly*/ 1;
7637   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7638 }
7639 
7640 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7641 /// when these variables are captured by the lambda.
7642 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7643   for (const auto &Shadow : LSI->ShadowingDecls) {
7644     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7645     // Try to avoid the warning when the shadowed decl isn't captured.
7646     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7647     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7648     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7649                                        ? diag::warn_decl_shadow_uncaptured_local
7650                                        : diag::warn_decl_shadow)
7651         << Shadow.VD->getDeclName()
7652         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7653     if (!CaptureLoc.isInvalid())
7654       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7655           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7656     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7657   }
7658 }
7659 
7660 /// Check -Wshadow without the advantage of a previous lookup.
7661 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7662   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7663     return;
7664 
7665   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7666                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7667   LookupName(R, S);
7668   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7669     CheckShadow(D, ShadowedDecl, R);
7670 }
7671 
7672 /// Check if 'E', which is an expression that is about to be modified, refers
7673 /// to a constructor parameter that shadows a field.
7674 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7675   // Quickly ignore expressions that can't be shadowing ctor parameters.
7676   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7677     return;
7678   E = E->IgnoreParenImpCasts();
7679   auto *DRE = dyn_cast<DeclRefExpr>(E);
7680   if (!DRE)
7681     return;
7682   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7683   auto I = ShadowingDecls.find(D);
7684   if (I == ShadowingDecls.end())
7685     return;
7686   const NamedDecl *ShadowedDecl = I->second;
7687   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7688   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7689   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7690   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7691 
7692   // Avoid issuing multiple warnings about the same decl.
7693   ShadowingDecls.erase(I);
7694 }
7695 
7696 /// Check for conflict between this global or extern "C" declaration and
7697 /// previous global or extern "C" declarations. This is only used in C++.
7698 template<typename T>
7699 static bool checkGlobalOrExternCConflict(
7700     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7701   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7702   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7703 
7704   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7705     // The common case: this global doesn't conflict with any extern "C"
7706     // declaration.
7707     return false;
7708   }
7709 
7710   if (Prev) {
7711     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7712       // Both the old and new declarations have C language linkage. This is a
7713       // redeclaration.
7714       Previous.clear();
7715       Previous.addDecl(Prev);
7716       return true;
7717     }
7718 
7719     // This is a global, non-extern "C" declaration, and there is a previous
7720     // non-global extern "C" declaration. Diagnose if this is a variable
7721     // declaration.
7722     if (!isa<VarDecl>(ND))
7723       return false;
7724   } else {
7725     // The declaration is extern "C". Check for any declaration in the
7726     // translation unit which might conflict.
7727     if (IsGlobal) {
7728       // We have already performed the lookup into the translation unit.
7729       IsGlobal = false;
7730       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7731            I != E; ++I) {
7732         if (isa<VarDecl>(*I)) {
7733           Prev = *I;
7734           break;
7735         }
7736       }
7737     } else {
7738       DeclContext::lookup_result R =
7739           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7740       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7741            I != E; ++I) {
7742         if (isa<VarDecl>(*I)) {
7743           Prev = *I;
7744           break;
7745         }
7746         // FIXME: If we have any other entity with this name in global scope,
7747         // the declaration is ill-formed, but that is a defect: it breaks the
7748         // 'stat' hack, for instance. Only variables can have mangled name
7749         // clashes with extern "C" declarations, so only they deserve a
7750         // diagnostic.
7751       }
7752     }
7753 
7754     if (!Prev)
7755       return false;
7756   }
7757 
7758   // Use the first declaration's location to ensure we point at something which
7759   // is lexically inside an extern "C" linkage-spec.
7760   assert(Prev && "should have found a previous declaration to diagnose");
7761   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7762     Prev = FD->getFirstDecl();
7763   else
7764     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7765 
7766   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7767     << IsGlobal << ND;
7768   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7769     << IsGlobal;
7770   return false;
7771 }
7772 
7773 /// Apply special rules for handling extern "C" declarations. Returns \c true
7774 /// if we have found that this is a redeclaration of some prior entity.
7775 ///
7776 /// Per C++ [dcl.link]p6:
7777 ///   Two declarations [for a function or variable] with C language linkage
7778 ///   with the same name that appear in different scopes refer to the same
7779 ///   [entity]. An entity with C language linkage shall not be declared with
7780 ///   the same name as an entity in global scope.
7781 template<typename T>
7782 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7783                                                   LookupResult &Previous) {
7784   if (!S.getLangOpts().CPlusPlus) {
7785     // In C, when declaring a global variable, look for a corresponding 'extern'
7786     // variable declared in function scope. We don't need this in C++, because
7787     // we find local extern decls in the surrounding file-scope DeclContext.
7788     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7789       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7790         Previous.clear();
7791         Previous.addDecl(Prev);
7792         return true;
7793       }
7794     }
7795     return false;
7796   }
7797 
7798   // A declaration in the translation unit can conflict with an extern "C"
7799   // declaration.
7800   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7801     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7802 
7803   // An extern "C" declaration can conflict with a declaration in the
7804   // translation unit or can be a redeclaration of an extern "C" declaration
7805   // in another scope.
7806   if (isIncompleteDeclExternC(S,ND))
7807     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7808 
7809   // Neither global nor extern "C": nothing to do.
7810   return false;
7811 }
7812 
7813 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7814   // If the decl is already known invalid, don't check it.
7815   if (NewVD->isInvalidDecl())
7816     return;
7817 
7818   QualType T = NewVD->getType();
7819 
7820   // Defer checking an 'auto' type until its initializer is attached.
7821   if (T->isUndeducedType())
7822     return;
7823 
7824   if (NewVD->hasAttrs())
7825     CheckAlignasUnderalignment(NewVD);
7826 
7827   if (T->isObjCObjectType()) {
7828     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7829       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7830     T = Context.getObjCObjectPointerType(T);
7831     NewVD->setType(T);
7832   }
7833 
7834   // Emit an error if an address space was applied to decl with local storage.
7835   // This includes arrays of objects with address space qualifiers, but not
7836   // automatic variables that point to other address spaces.
7837   // ISO/IEC TR 18037 S5.1.2
7838   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7839       T.getAddressSpace() != LangAS::Default) {
7840     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7841     NewVD->setInvalidDecl();
7842     return;
7843   }
7844 
7845   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7846   // scope.
7847   if (getLangOpts().OpenCLVersion == 120 &&
7848       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7849       NewVD->isStaticLocal()) {
7850     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7851     NewVD->setInvalidDecl();
7852     return;
7853   }
7854 
7855   if (getLangOpts().OpenCL) {
7856     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7857     if (NewVD->hasAttr<BlocksAttr>()) {
7858       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7859       return;
7860     }
7861 
7862     if (T->isBlockPointerType()) {
7863       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7864       // can't use 'extern' storage class.
7865       if (!T.isConstQualified()) {
7866         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7867             << 0 /*const*/;
7868         NewVD->setInvalidDecl();
7869         return;
7870       }
7871       if (NewVD->hasExternalStorage()) {
7872         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7873         NewVD->setInvalidDecl();
7874         return;
7875       }
7876     }
7877     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7878     // __constant address space.
7879     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7880     // variables inside a function can also be declared in the global
7881     // address space.
7882     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7883     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7884     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7885         NewVD->hasExternalStorage()) {
7886       if (!T->isSamplerT() &&
7887           !T->isDependentType() &&
7888           !(T.getAddressSpace() == LangAS::opencl_constant ||
7889             (T.getAddressSpace() == LangAS::opencl_global &&
7890              (getLangOpts().OpenCLVersion == 200 ||
7891               getLangOpts().OpenCLCPlusPlus)))) {
7892         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7893         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7894           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7895               << Scope << "global or constant";
7896         else
7897           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7898               << Scope << "constant";
7899         NewVD->setInvalidDecl();
7900         return;
7901       }
7902     } else {
7903       if (T.getAddressSpace() == LangAS::opencl_global) {
7904         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7905             << 1 /*is any function*/ << "global";
7906         NewVD->setInvalidDecl();
7907         return;
7908       }
7909       if (T.getAddressSpace() == LangAS::opencl_constant ||
7910           T.getAddressSpace() == LangAS::opencl_local) {
7911         FunctionDecl *FD = getCurFunctionDecl();
7912         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7913         // in functions.
7914         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7915           if (T.getAddressSpace() == LangAS::opencl_constant)
7916             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7917                 << 0 /*non-kernel only*/ << "constant";
7918           else
7919             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7920                 << 0 /*non-kernel only*/ << "local";
7921           NewVD->setInvalidDecl();
7922           return;
7923         }
7924         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7925         // in the outermost scope of a kernel function.
7926         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7927           if (!getCurScope()->isFunctionScope()) {
7928             if (T.getAddressSpace() == LangAS::opencl_constant)
7929               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7930                   << "constant";
7931             else
7932               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7933                   << "local";
7934             NewVD->setInvalidDecl();
7935             return;
7936           }
7937         }
7938       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7939                  // If we are parsing a template we didn't deduce an addr
7940                  // space yet.
7941                  T.getAddressSpace() != LangAS::Default) {
7942         // Do not allow other address spaces on automatic variable.
7943         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7944         NewVD->setInvalidDecl();
7945         return;
7946       }
7947     }
7948   }
7949 
7950   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7951       && !NewVD->hasAttr<BlocksAttr>()) {
7952     if (getLangOpts().getGC() != LangOptions::NonGC)
7953       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7954     else {
7955       assert(!getLangOpts().ObjCAutoRefCount);
7956       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7957     }
7958   }
7959 
7960   bool isVM = T->isVariablyModifiedType();
7961   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7962       NewVD->hasAttr<BlocksAttr>())
7963     setFunctionHasBranchProtectedScope();
7964 
7965   if ((isVM && NewVD->hasLinkage()) ||
7966       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7967     bool SizeIsNegative;
7968     llvm::APSInt Oversized;
7969     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7970         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7971     QualType FixedT;
7972     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7973       FixedT = FixedTInfo->getType();
7974     else if (FixedTInfo) {
7975       // Type and type-as-written are canonically different. We need to fix up
7976       // both types separately.
7977       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7978                                                    Oversized);
7979     }
7980     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7981       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7982       // FIXME: This won't give the correct result for
7983       // int a[10][n];
7984       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7985 
7986       if (NewVD->isFileVarDecl())
7987         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7988         << SizeRange;
7989       else if (NewVD->isStaticLocal())
7990         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7991         << SizeRange;
7992       else
7993         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7994         << SizeRange;
7995       NewVD->setInvalidDecl();
7996       return;
7997     }
7998 
7999     if (!FixedTInfo) {
8000       if (NewVD->isFileVarDecl())
8001         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8002       else
8003         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8004       NewVD->setInvalidDecl();
8005       return;
8006     }
8007 
8008     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
8009     NewVD->setType(FixedT);
8010     NewVD->setTypeSourceInfo(FixedTInfo);
8011   }
8012 
8013   if (T->isVoidType()) {
8014     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8015     //                    of objects and functions.
8016     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8017       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8018         << T;
8019       NewVD->setInvalidDecl();
8020       return;
8021     }
8022   }
8023 
8024   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8025     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8026     NewVD->setInvalidDecl();
8027     return;
8028   }
8029 
8030   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8031     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8032     NewVD->setInvalidDecl();
8033     return;
8034   }
8035 
8036   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8037     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8038     NewVD->setInvalidDecl();
8039     return;
8040   }
8041 
8042   if (NewVD->isConstexpr() && !T->isDependentType() &&
8043       RequireLiteralType(NewVD->getLocation(), T,
8044                          diag::err_constexpr_var_non_literal)) {
8045     NewVD->setInvalidDecl();
8046     return;
8047   }
8048 }
8049 
8050 /// Perform semantic checking on a newly-created variable
8051 /// declaration.
8052 ///
8053 /// This routine performs all of the type-checking required for a
8054 /// variable declaration once it has been built. It is used both to
8055 /// check variables after they have been parsed and their declarators
8056 /// have been translated into a declaration, and to check variables
8057 /// that have been instantiated from a template.
8058 ///
8059 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8060 ///
8061 /// Returns true if the variable declaration is a redeclaration.
8062 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8063   CheckVariableDeclarationType(NewVD);
8064 
8065   // If the decl is already known invalid, don't check it.
8066   if (NewVD->isInvalidDecl())
8067     return false;
8068 
8069   // If we did not find anything by this name, look for a non-visible
8070   // extern "C" declaration with the same name.
8071   if (Previous.empty() &&
8072       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8073     Previous.setShadowed();
8074 
8075   if (!Previous.empty()) {
8076     MergeVarDecl(NewVD, Previous);
8077     return true;
8078   }
8079   return false;
8080 }
8081 
8082 namespace {
8083 struct FindOverriddenMethod {
8084   Sema *S;
8085   CXXMethodDecl *Method;
8086 
8087   /// Member lookup function that determines whether a given C++
8088   /// method overrides a method in a base class, to be used with
8089   /// CXXRecordDecl::lookupInBases().
8090   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8091     RecordDecl *BaseRecord =
8092         Specifier->getType()->castAs<RecordType>()->getDecl();
8093 
8094     DeclarationName Name = Method->getDeclName();
8095 
8096     // FIXME: Do we care about other names here too?
8097     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8098       // We really want to find the base class destructor here.
8099       QualType T = S->Context.getTypeDeclType(BaseRecord);
8100       CanQualType CT = S->Context.getCanonicalType(T);
8101 
8102       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8103     }
8104 
8105     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8106          Path.Decls = Path.Decls.slice(1)) {
8107       NamedDecl *D = Path.Decls.front();
8108       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8109         if (MD->isVirtual() &&
8110             !S->IsOverload(
8111                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8112                 /*ConsiderCudaAttrs=*/true,
8113                 // C++2a [class.virtual]p2 does not consider requires clauses
8114                 // when overriding.
8115                 /*ConsiderRequiresClauses=*/false))
8116           return true;
8117       }
8118     }
8119 
8120     return false;
8121   }
8122 };
8123 } // end anonymous namespace
8124 
8125 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8126 /// and if so, check that it's a valid override and remember it.
8127 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8128   // Look for methods in base classes that this method might override.
8129   CXXBasePaths Paths;
8130   FindOverriddenMethod FOM;
8131   FOM.Method = MD;
8132   FOM.S = this;
8133   bool AddedAny = false;
8134   if (DC->lookupInBases(FOM, Paths)) {
8135     for (auto *I : Paths.found_decls()) {
8136       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8137         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8138         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8139             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8140             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8141             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8142           AddedAny = true;
8143         }
8144       }
8145     }
8146   }
8147 
8148   return AddedAny;
8149 }
8150 
8151 namespace {
8152   // Struct for holding all of the extra arguments needed by
8153   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8154   struct ActOnFDArgs {
8155     Scope *S;
8156     Declarator &D;
8157     MultiTemplateParamsArg TemplateParamLists;
8158     bool AddToScope;
8159   };
8160 } // end anonymous namespace
8161 
8162 namespace {
8163 
8164 // Callback to only accept typo corrections that have a non-zero edit distance.
8165 // Also only accept corrections that have the same parent decl.
8166 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8167  public:
8168   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8169                             CXXRecordDecl *Parent)
8170       : Context(Context), OriginalFD(TypoFD),
8171         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8172 
8173   bool ValidateCandidate(const TypoCorrection &candidate) override {
8174     if (candidate.getEditDistance() == 0)
8175       return false;
8176 
8177     SmallVector<unsigned, 1> MismatchedParams;
8178     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8179                                           CDeclEnd = candidate.end();
8180          CDecl != CDeclEnd; ++CDecl) {
8181       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8182 
8183       if (FD && !FD->hasBody() &&
8184           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8185         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8186           CXXRecordDecl *Parent = MD->getParent();
8187           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8188             return true;
8189         } else if (!ExpectedParent) {
8190           return true;
8191         }
8192       }
8193     }
8194 
8195     return false;
8196   }
8197 
8198   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8199     return std::make_unique<DifferentNameValidatorCCC>(*this);
8200   }
8201 
8202  private:
8203   ASTContext &Context;
8204   FunctionDecl *OriginalFD;
8205   CXXRecordDecl *ExpectedParent;
8206 };
8207 
8208 } // end anonymous namespace
8209 
8210 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8211   TypoCorrectedFunctionDefinitions.insert(F);
8212 }
8213 
8214 /// Generate diagnostics for an invalid function redeclaration.
8215 ///
8216 /// This routine handles generating the diagnostic messages for an invalid
8217 /// function redeclaration, including finding possible similar declarations
8218 /// or performing typo correction if there are no previous declarations with
8219 /// the same name.
8220 ///
8221 /// Returns a NamedDecl iff typo correction was performed and substituting in
8222 /// the new declaration name does not cause new errors.
8223 static NamedDecl *DiagnoseInvalidRedeclaration(
8224     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8225     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8226   DeclarationName Name = NewFD->getDeclName();
8227   DeclContext *NewDC = NewFD->getDeclContext();
8228   SmallVector<unsigned, 1> MismatchedParams;
8229   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8230   TypoCorrection Correction;
8231   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8232   unsigned DiagMsg =
8233     IsLocalFriend ? diag::err_no_matching_local_friend :
8234     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8235     diag::err_member_decl_does_not_match;
8236   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8237                     IsLocalFriend ? Sema::LookupLocalFriendName
8238                                   : Sema::LookupOrdinaryName,
8239                     Sema::ForVisibleRedeclaration);
8240 
8241   NewFD->setInvalidDecl();
8242   if (IsLocalFriend)
8243     SemaRef.LookupName(Prev, S);
8244   else
8245     SemaRef.LookupQualifiedName(Prev, NewDC);
8246   assert(!Prev.isAmbiguous() &&
8247          "Cannot have an ambiguity in previous-declaration lookup");
8248   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8249   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8250                                 MD ? MD->getParent() : nullptr);
8251   if (!Prev.empty()) {
8252     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8253          Func != FuncEnd; ++Func) {
8254       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8255       if (FD &&
8256           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8257         // Add 1 to the index so that 0 can mean the mismatch didn't
8258         // involve a parameter
8259         unsigned ParamNum =
8260             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8261         NearMatches.push_back(std::make_pair(FD, ParamNum));
8262       }
8263     }
8264   // If the qualified name lookup yielded nothing, try typo correction
8265   } else if ((Correction = SemaRef.CorrectTypo(
8266                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8267                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8268                   IsLocalFriend ? nullptr : NewDC))) {
8269     // Set up everything for the call to ActOnFunctionDeclarator
8270     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8271                               ExtraArgs.D.getIdentifierLoc());
8272     Previous.clear();
8273     Previous.setLookupName(Correction.getCorrection());
8274     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8275                                     CDeclEnd = Correction.end();
8276          CDecl != CDeclEnd; ++CDecl) {
8277       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8278       if (FD && !FD->hasBody() &&
8279           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8280         Previous.addDecl(FD);
8281       }
8282     }
8283     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8284 
8285     NamedDecl *Result;
8286     // Retry building the function declaration with the new previous
8287     // declarations, and with errors suppressed.
8288     {
8289       // Trap errors.
8290       Sema::SFINAETrap Trap(SemaRef);
8291 
8292       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8293       // pieces need to verify the typo-corrected C++ declaration and hopefully
8294       // eliminate the need for the parameter pack ExtraArgs.
8295       Result = SemaRef.ActOnFunctionDeclarator(
8296           ExtraArgs.S, ExtraArgs.D,
8297           Correction.getCorrectionDecl()->getDeclContext(),
8298           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8299           ExtraArgs.AddToScope);
8300 
8301       if (Trap.hasErrorOccurred())
8302         Result = nullptr;
8303     }
8304 
8305     if (Result) {
8306       // Determine which correction we picked.
8307       Decl *Canonical = Result->getCanonicalDecl();
8308       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8309            I != E; ++I)
8310         if ((*I)->getCanonicalDecl() == Canonical)
8311           Correction.setCorrectionDecl(*I);
8312 
8313       // Let Sema know about the correction.
8314       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8315       SemaRef.diagnoseTypo(
8316           Correction,
8317           SemaRef.PDiag(IsLocalFriend
8318                           ? diag::err_no_matching_local_friend_suggest
8319                           : diag::err_member_decl_does_not_match_suggest)
8320             << Name << NewDC << IsDefinition);
8321       return Result;
8322     }
8323 
8324     // Pretend the typo correction never occurred
8325     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8326                               ExtraArgs.D.getIdentifierLoc());
8327     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8328     Previous.clear();
8329     Previous.setLookupName(Name);
8330   }
8331 
8332   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8333       << Name << NewDC << IsDefinition << NewFD->getLocation();
8334 
8335   bool NewFDisConst = false;
8336   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8337     NewFDisConst = NewMD->isConst();
8338 
8339   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8340        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8341        NearMatch != NearMatchEnd; ++NearMatch) {
8342     FunctionDecl *FD = NearMatch->first;
8343     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8344     bool FDisConst = MD && MD->isConst();
8345     bool IsMember = MD || !IsLocalFriend;
8346 
8347     // FIXME: These notes are poorly worded for the local friend case.
8348     if (unsigned Idx = NearMatch->second) {
8349       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8350       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8351       if (Loc.isInvalid()) Loc = FD->getLocation();
8352       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8353                                  : diag::note_local_decl_close_param_match)
8354         << Idx << FDParam->getType()
8355         << NewFD->getParamDecl(Idx - 1)->getType();
8356     } else if (FDisConst != NewFDisConst) {
8357       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8358           << NewFDisConst << FD->getSourceRange().getEnd();
8359     } else
8360       SemaRef.Diag(FD->getLocation(),
8361                    IsMember ? diag::note_member_def_close_match
8362                             : diag::note_local_decl_close_match);
8363   }
8364   return nullptr;
8365 }
8366 
8367 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8368   switch (D.getDeclSpec().getStorageClassSpec()) {
8369   default: llvm_unreachable("Unknown storage class!");
8370   case DeclSpec::SCS_auto:
8371   case DeclSpec::SCS_register:
8372   case DeclSpec::SCS_mutable:
8373     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8374                  diag::err_typecheck_sclass_func);
8375     D.getMutableDeclSpec().ClearStorageClassSpecs();
8376     D.setInvalidType();
8377     break;
8378   case DeclSpec::SCS_unspecified: break;
8379   case DeclSpec::SCS_extern:
8380     if (D.getDeclSpec().isExternInLinkageSpec())
8381       return SC_None;
8382     return SC_Extern;
8383   case DeclSpec::SCS_static: {
8384     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8385       // C99 6.7.1p5:
8386       //   The declaration of an identifier for a function that has
8387       //   block scope shall have no explicit storage-class specifier
8388       //   other than extern
8389       // See also (C++ [dcl.stc]p4).
8390       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8391                    diag::err_static_block_func);
8392       break;
8393     } else
8394       return SC_Static;
8395   }
8396   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8397   }
8398 
8399   // No explicit storage class has already been returned
8400   return SC_None;
8401 }
8402 
8403 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8404                                            DeclContext *DC, QualType &R,
8405                                            TypeSourceInfo *TInfo,
8406                                            StorageClass SC,
8407                                            bool &IsVirtualOkay) {
8408   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8409   DeclarationName Name = NameInfo.getName();
8410 
8411   FunctionDecl *NewFD = nullptr;
8412   bool isInline = D.getDeclSpec().isInlineSpecified();
8413 
8414   if (!SemaRef.getLangOpts().CPlusPlus) {
8415     // Determine whether the function was written with a
8416     // prototype. This true when:
8417     //   - there is a prototype in the declarator, or
8418     //   - the type R of the function is some kind of typedef or other non-
8419     //     attributed reference to a type name (which eventually refers to a
8420     //     function type).
8421     bool HasPrototype =
8422       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8423       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8424 
8425     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8426                                  R, TInfo, SC, isInline, HasPrototype,
8427                                  CSK_unspecified,
8428                                  /*TrailingRequiresClause=*/nullptr);
8429     if (D.isInvalidType())
8430       NewFD->setInvalidDecl();
8431 
8432     return NewFD;
8433   }
8434 
8435   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8436 
8437   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8438   if (ConstexprKind == CSK_constinit) {
8439     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8440                  diag::err_constexpr_wrong_decl_kind)
8441         << ConstexprKind;
8442     ConstexprKind = CSK_unspecified;
8443     D.getMutableDeclSpec().ClearConstexprSpec();
8444   }
8445   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8446 
8447   // Check that the return type is not an abstract class type.
8448   // For record types, this is done by the AbstractClassUsageDiagnoser once
8449   // the class has been completely parsed.
8450   if (!DC->isRecord() &&
8451       SemaRef.RequireNonAbstractType(
8452           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8453           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8454     D.setInvalidType();
8455 
8456   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8457     // This is a C++ constructor declaration.
8458     assert(DC->isRecord() &&
8459            "Constructors can only be declared in a member context");
8460 
8461     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8462     return CXXConstructorDecl::Create(
8463         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8464         TInfo, ExplicitSpecifier, isInline,
8465         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8466         TrailingRequiresClause);
8467 
8468   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8469     // This is a C++ destructor declaration.
8470     if (DC->isRecord()) {
8471       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8472       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8473       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8474           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8475           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8476           TrailingRequiresClause);
8477 
8478       // If the destructor needs an implicit exception specification, set it
8479       // now. FIXME: It'd be nice to be able to create the right type to start
8480       // with, but the type needs to reference the destructor declaration.
8481       if (SemaRef.getLangOpts().CPlusPlus11)
8482         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8483 
8484       IsVirtualOkay = true;
8485       return NewDD;
8486 
8487     } else {
8488       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8489       D.setInvalidType();
8490 
8491       // Create a FunctionDecl to satisfy the function definition parsing
8492       // code path.
8493       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8494                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8495                                   isInline,
8496                                   /*hasPrototype=*/true, ConstexprKind,
8497                                   TrailingRequiresClause);
8498     }
8499 
8500   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8501     if (!DC->isRecord()) {
8502       SemaRef.Diag(D.getIdentifierLoc(),
8503            diag::err_conv_function_not_member);
8504       return nullptr;
8505     }
8506 
8507     SemaRef.CheckConversionDeclarator(D, R, SC);
8508     if (D.isInvalidType())
8509       return nullptr;
8510 
8511     IsVirtualOkay = true;
8512     return CXXConversionDecl::Create(
8513         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8514         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8515         TrailingRequiresClause);
8516 
8517   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8518     if (TrailingRequiresClause)
8519       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8520                    diag::err_trailing_requires_clause_on_deduction_guide)
8521           << TrailingRequiresClause->getSourceRange();
8522     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8523 
8524     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8525                                          ExplicitSpecifier, NameInfo, R, TInfo,
8526                                          D.getEndLoc());
8527   } else if (DC->isRecord()) {
8528     // If the name of the function is the same as the name of the record,
8529     // then this must be an invalid constructor that has a return type.
8530     // (The parser checks for a return type and makes the declarator a
8531     // constructor if it has no return type).
8532     if (Name.getAsIdentifierInfo() &&
8533         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8534       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8535         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8536         << SourceRange(D.getIdentifierLoc());
8537       return nullptr;
8538     }
8539 
8540     // This is a C++ method declaration.
8541     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8542         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8543         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8544         TrailingRequiresClause);
8545     IsVirtualOkay = !Ret->isStatic();
8546     return Ret;
8547   } else {
8548     bool isFriend =
8549         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8550     if (!isFriend && SemaRef.CurContext->isRecord())
8551       return nullptr;
8552 
8553     // Determine whether the function was written with a
8554     // prototype. This true when:
8555     //   - we're in C++ (where every function has a prototype),
8556     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8557                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8558                                 ConstexprKind, TrailingRequiresClause);
8559   }
8560 }
8561 
8562 enum OpenCLParamType {
8563   ValidKernelParam,
8564   PtrPtrKernelParam,
8565   PtrKernelParam,
8566   InvalidAddrSpacePtrKernelParam,
8567   InvalidKernelParam,
8568   RecordKernelParam
8569 };
8570 
8571 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8572   // Size dependent types are just typedefs to normal integer types
8573   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8574   // integers other than by their names.
8575   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8576 
8577   // Remove typedefs one by one until we reach a typedef
8578   // for a size dependent type.
8579   QualType DesugaredTy = Ty;
8580   do {
8581     ArrayRef<StringRef> Names(SizeTypeNames);
8582     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8583     if (Names.end() != Match)
8584       return true;
8585 
8586     Ty = DesugaredTy;
8587     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8588   } while (DesugaredTy != Ty);
8589 
8590   return false;
8591 }
8592 
8593 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8594   if (PT->isPointerType()) {
8595     QualType PointeeType = PT->getPointeeType();
8596     if (PointeeType->isPointerType())
8597       return PtrPtrKernelParam;
8598     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8599         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8600         PointeeType.getAddressSpace() == LangAS::Default)
8601       return InvalidAddrSpacePtrKernelParam;
8602     return PtrKernelParam;
8603   }
8604 
8605   // OpenCL v1.2 s6.9.k:
8606   // Arguments to kernel functions in a program cannot be declared with the
8607   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8608   // uintptr_t or a struct and/or union that contain fields declared to be one
8609   // of these built-in scalar types.
8610   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8611     return InvalidKernelParam;
8612 
8613   if (PT->isImageType())
8614     return PtrKernelParam;
8615 
8616   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8617     return InvalidKernelParam;
8618 
8619   // OpenCL extension spec v1.2 s9.5:
8620   // This extension adds support for half scalar and vector types as built-in
8621   // types that can be used for arithmetic operations, conversions etc.
8622   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8623     return InvalidKernelParam;
8624 
8625   if (PT->isRecordType())
8626     return RecordKernelParam;
8627 
8628   // Look into an array argument to check if it has a forbidden type.
8629   if (PT->isArrayType()) {
8630     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8631     // Call ourself to check an underlying type of an array. Since the
8632     // getPointeeOrArrayElementType returns an innermost type which is not an
8633     // array, this recursive call only happens once.
8634     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8635   }
8636 
8637   return ValidKernelParam;
8638 }
8639 
8640 static void checkIsValidOpenCLKernelParameter(
8641   Sema &S,
8642   Declarator &D,
8643   ParmVarDecl *Param,
8644   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8645   QualType PT = Param->getType();
8646 
8647   // Cache the valid types we encounter to avoid rechecking structs that are
8648   // used again
8649   if (ValidTypes.count(PT.getTypePtr()))
8650     return;
8651 
8652   switch (getOpenCLKernelParameterType(S, PT)) {
8653   case PtrPtrKernelParam:
8654     // OpenCL v1.2 s6.9.a:
8655     // A kernel function argument cannot be declared as a
8656     // pointer to a pointer type.
8657     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8658     D.setInvalidType();
8659     return;
8660 
8661   case InvalidAddrSpacePtrKernelParam:
8662     // OpenCL v1.0 s6.5:
8663     // __kernel function arguments declared to be a pointer of a type can point
8664     // to one of the following address spaces only : __global, __local or
8665     // __constant.
8666     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8667     D.setInvalidType();
8668     return;
8669 
8670     // OpenCL v1.2 s6.9.k:
8671     // Arguments to kernel functions in a program cannot be declared with the
8672     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8673     // uintptr_t or a struct and/or union that contain fields declared to be
8674     // one of these built-in scalar types.
8675 
8676   case InvalidKernelParam:
8677     // OpenCL v1.2 s6.8 n:
8678     // A kernel function argument cannot be declared
8679     // of event_t type.
8680     // Do not diagnose half type since it is diagnosed as invalid argument
8681     // type for any function elsewhere.
8682     if (!PT->isHalfType()) {
8683       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8684 
8685       // Explain what typedefs are involved.
8686       const TypedefType *Typedef = nullptr;
8687       while ((Typedef = PT->getAs<TypedefType>())) {
8688         SourceLocation Loc = Typedef->getDecl()->getLocation();
8689         // SourceLocation may be invalid for a built-in type.
8690         if (Loc.isValid())
8691           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8692         PT = Typedef->desugar();
8693       }
8694     }
8695 
8696     D.setInvalidType();
8697     return;
8698 
8699   case PtrKernelParam:
8700   case ValidKernelParam:
8701     ValidTypes.insert(PT.getTypePtr());
8702     return;
8703 
8704   case RecordKernelParam:
8705     break;
8706   }
8707 
8708   // Track nested structs we will inspect
8709   SmallVector<const Decl *, 4> VisitStack;
8710 
8711   // Track where we are in the nested structs. Items will migrate from
8712   // VisitStack to HistoryStack as we do the DFS for bad field.
8713   SmallVector<const FieldDecl *, 4> HistoryStack;
8714   HistoryStack.push_back(nullptr);
8715 
8716   // At this point we already handled everything except of a RecordType or
8717   // an ArrayType of a RecordType.
8718   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8719   const RecordType *RecTy =
8720       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8721   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8722 
8723   VisitStack.push_back(RecTy->getDecl());
8724   assert(VisitStack.back() && "First decl null?");
8725 
8726   do {
8727     const Decl *Next = VisitStack.pop_back_val();
8728     if (!Next) {
8729       assert(!HistoryStack.empty());
8730       // Found a marker, we have gone up a level
8731       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8732         ValidTypes.insert(Hist->getType().getTypePtr());
8733 
8734       continue;
8735     }
8736 
8737     // Adds everything except the original parameter declaration (which is not a
8738     // field itself) to the history stack.
8739     const RecordDecl *RD;
8740     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8741       HistoryStack.push_back(Field);
8742 
8743       QualType FieldTy = Field->getType();
8744       // Other field types (known to be valid or invalid) are handled while we
8745       // walk around RecordDecl::fields().
8746       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8747              "Unexpected type.");
8748       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8749 
8750       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8751     } else {
8752       RD = cast<RecordDecl>(Next);
8753     }
8754 
8755     // Add a null marker so we know when we've gone back up a level
8756     VisitStack.push_back(nullptr);
8757 
8758     for (const auto *FD : RD->fields()) {
8759       QualType QT = FD->getType();
8760 
8761       if (ValidTypes.count(QT.getTypePtr()))
8762         continue;
8763 
8764       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8765       if (ParamType == ValidKernelParam)
8766         continue;
8767 
8768       if (ParamType == RecordKernelParam) {
8769         VisitStack.push_back(FD);
8770         continue;
8771       }
8772 
8773       // OpenCL v1.2 s6.9.p:
8774       // Arguments to kernel functions that are declared to be a struct or union
8775       // do not allow OpenCL objects to be passed as elements of the struct or
8776       // union.
8777       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8778           ParamType == InvalidAddrSpacePtrKernelParam) {
8779         S.Diag(Param->getLocation(),
8780                diag::err_record_with_pointers_kernel_param)
8781           << PT->isUnionType()
8782           << PT;
8783       } else {
8784         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8785       }
8786 
8787       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8788           << OrigRecDecl->getDeclName();
8789 
8790       // We have an error, now let's go back up through history and show where
8791       // the offending field came from
8792       for (ArrayRef<const FieldDecl *>::const_iterator
8793                I = HistoryStack.begin() + 1,
8794                E = HistoryStack.end();
8795            I != E; ++I) {
8796         const FieldDecl *OuterField = *I;
8797         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8798           << OuterField->getType();
8799       }
8800 
8801       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8802         << QT->isPointerType()
8803         << QT;
8804       D.setInvalidType();
8805       return;
8806     }
8807   } while (!VisitStack.empty());
8808 }
8809 
8810 /// Find the DeclContext in which a tag is implicitly declared if we see an
8811 /// elaborated type specifier in the specified context, and lookup finds
8812 /// nothing.
8813 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8814   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8815     DC = DC->getParent();
8816   return DC;
8817 }
8818 
8819 /// Find the Scope in which a tag is implicitly declared if we see an
8820 /// elaborated type specifier in the specified context, and lookup finds
8821 /// nothing.
8822 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8823   while (S->isClassScope() ||
8824          (LangOpts.CPlusPlus &&
8825           S->isFunctionPrototypeScope()) ||
8826          ((S->getFlags() & Scope::DeclScope) == 0) ||
8827          (S->getEntity() && S->getEntity()->isTransparentContext()))
8828     S = S->getParent();
8829   return S;
8830 }
8831 
8832 NamedDecl*
8833 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8834                               TypeSourceInfo *TInfo, LookupResult &Previous,
8835                               MultiTemplateParamsArg TemplateParamListsRef,
8836                               bool &AddToScope) {
8837   QualType R = TInfo->getType();
8838 
8839   assert(R->isFunctionType());
8840   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8841     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8842 
8843   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8844   for (TemplateParameterList *TPL : TemplateParamListsRef)
8845     TemplateParamLists.push_back(TPL);
8846   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8847     if (!TemplateParamLists.empty() &&
8848         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8849       TemplateParamLists.back() = Invented;
8850     else
8851       TemplateParamLists.push_back(Invented);
8852   }
8853 
8854   // TODO: consider using NameInfo for diagnostic.
8855   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8856   DeclarationName Name = NameInfo.getName();
8857   StorageClass SC = getFunctionStorageClass(*this, D);
8858 
8859   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8860     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8861          diag::err_invalid_thread)
8862       << DeclSpec::getSpecifierName(TSCS);
8863 
8864   if (D.isFirstDeclarationOfMember())
8865     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8866                            D.getIdentifierLoc());
8867 
8868   bool isFriend = false;
8869   FunctionTemplateDecl *FunctionTemplate = nullptr;
8870   bool isMemberSpecialization = false;
8871   bool isFunctionTemplateSpecialization = false;
8872 
8873   bool isDependentClassScopeExplicitSpecialization = false;
8874   bool HasExplicitTemplateArgs = false;
8875   TemplateArgumentListInfo TemplateArgs;
8876 
8877   bool isVirtualOkay = false;
8878 
8879   DeclContext *OriginalDC = DC;
8880   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8881 
8882   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8883                                               isVirtualOkay);
8884   if (!NewFD) return nullptr;
8885 
8886   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8887     NewFD->setTopLevelDeclInObjCContainer();
8888 
8889   // Set the lexical context. If this is a function-scope declaration, or has a
8890   // C++ scope specifier, or is the object of a friend declaration, the lexical
8891   // context will be different from the semantic context.
8892   NewFD->setLexicalDeclContext(CurContext);
8893 
8894   if (IsLocalExternDecl)
8895     NewFD->setLocalExternDecl();
8896 
8897   if (getLangOpts().CPlusPlus) {
8898     bool isInline = D.getDeclSpec().isInlineSpecified();
8899     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8900     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8901     isFriend = D.getDeclSpec().isFriendSpecified();
8902     if (isFriend && !isInline && D.isFunctionDefinition()) {
8903       // C++ [class.friend]p5
8904       //   A function can be defined in a friend declaration of a
8905       //   class . . . . Such a function is implicitly inline.
8906       NewFD->setImplicitlyInline();
8907     }
8908 
8909     // If this is a method defined in an __interface, and is not a constructor
8910     // or an overloaded operator, then set the pure flag (isVirtual will already
8911     // return true).
8912     if (const CXXRecordDecl *Parent =
8913           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8914       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8915         NewFD->setPure(true);
8916 
8917       // C++ [class.union]p2
8918       //   A union can have member functions, but not virtual functions.
8919       if (isVirtual && Parent->isUnion())
8920         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8921     }
8922 
8923     SetNestedNameSpecifier(*this, NewFD, D);
8924     isMemberSpecialization = false;
8925     isFunctionTemplateSpecialization = false;
8926     if (D.isInvalidType())
8927       NewFD->setInvalidDecl();
8928 
8929     // Match up the template parameter lists with the scope specifier, then
8930     // determine whether we have a template or a template specialization.
8931     bool Invalid = false;
8932     TemplateParameterList *TemplateParams =
8933         MatchTemplateParametersToScopeSpecifier(
8934             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8935             D.getCXXScopeSpec(),
8936             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8937                 ? D.getName().TemplateId
8938                 : nullptr,
8939             TemplateParamLists, isFriend, isMemberSpecialization,
8940             Invalid);
8941     if (TemplateParams) {
8942       // Check that we can declare a template here.
8943       if (CheckTemplateDeclScope(S, TemplateParams))
8944         NewFD->setInvalidDecl();
8945 
8946       if (TemplateParams->size() > 0) {
8947         // This is a function template
8948 
8949         // A destructor cannot be a template.
8950         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8951           Diag(NewFD->getLocation(), diag::err_destructor_template);
8952           NewFD->setInvalidDecl();
8953         }
8954 
8955         // If we're adding a template to a dependent context, we may need to
8956         // rebuilding some of the types used within the template parameter list,
8957         // now that we know what the current instantiation is.
8958         if (DC->isDependentContext()) {
8959           ContextRAII SavedContext(*this, DC);
8960           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8961             Invalid = true;
8962         }
8963 
8964         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8965                                                         NewFD->getLocation(),
8966                                                         Name, TemplateParams,
8967                                                         NewFD);
8968         FunctionTemplate->setLexicalDeclContext(CurContext);
8969         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8970 
8971         // For source fidelity, store the other template param lists.
8972         if (TemplateParamLists.size() > 1) {
8973           NewFD->setTemplateParameterListsInfo(Context,
8974               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8975                   .drop_back(1));
8976         }
8977       } else {
8978         // This is a function template specialization.
8979         isFunctionTemplateSpecialization = true;
8980         // For source fidelity, store all the template param lists.
8981         if (TemplateParamLists.size() > 0)
8982           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8983 
8984         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8985         if (isFriend) {
8986           // We want to remove the "template<>", found here.
8987           SourceRange RemoveRange = TemplateParams->getSourceRange();
8988 
8989           // If we remove the template<> and the name is not a
8990           // template-id, we're actually silently creating a problem:
8991           // the friend declaration will refer to an untemplated decl,
8992           // and clearly the user wants a template specialization.  So
8993           // we need to insert '<>' after the name.
8994           SourceLocation InsertLoc;
8995           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8996             InsertLoc = D.getName().getSourceRange().getEnd();
8997             InsertLoc = getLocForEndOfToken(InsertLoc);
8998           }
8999 
9000           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9001             << Name << RemoveRange
9002             << FixItHint::CreateRemoval(RemoveRange)
9003             << FixItHint::CreateInsertion(InsertLoc, "<>");
9004         }
9005       }
9006     } else {
9007       // Check that we can declare a template here.
9008       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9009           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9010         NewFD->setInvalidDecl();
9011 
9012       // All template param lists were matched against the scope specifier:
9013       // this is NOT (an explicit specialization of) a template.
9014       if (TemplateParamLists.size() > 0)
9015         // For source fidelity, store all the template param lists.
9016         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9017     }
9018 
9019     if (Invalid) {
9020       NewFD->setInvalidDecl();
9021       if (FunctionTemplate)
9022         FunctionTemplate->setInvalidDecl();
9023     }
9024 
9025     // C++ [dcl.fct.spec]p5:
9026     //   The virtual specifier shall only be used in declarations of
9027     //   nonstatic class member functions that appear within a
9028     //   member-specification of a class declaration; see 10.3.
9029     //
9030     if (isVirtual && !NewFD->isInvalidDecl()) {
9031       if (!isVirtualOkay) {
9032         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9033              diag::err_virtual_non_function);
9034       } else if (!CurContext->isRecord()) {
9035         // 'virtual' was specified outside of the class.
9036         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9037              diag::err_virtual_out_of_class)
9038           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9039       } else if (NewFD->getDescribedFunctionTemplate()) {
9040         // C++ [temp.mem]p3:
9041         //  A member function template shall not be virtual.
9042         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9043              diag::err_virtual_member_function_template)
9044           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9045       } else {
9046         // Okay: Add virtual to the method.
9047         NewFD->setVirtualAsWritten(true);
9048       }
9049 
9050       if (getLangOpts().CPlusPlus14 &&
9051           NewFD->getReturnType()->isUndeducedType())
9052         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9053     }
9054 
9055     if (getLangOpts().CPlusPlus14 &&
9056         (NewFD->isDependentContext() ||
9057          (isFriend && CurContext->isDependentContext())) &&
9058         NewFD->getReturnType()->isUndeducedType()) {
9059       // If the function template is referenced directly (for instance, as a
9060       // member of the current instantiation), pretend it has a dependent type.
9061       // This is not really justified by the standard, but is the only sane
9062       // thing to do.
9063       // FIXME: For a friend function, we have not marked the function as being
9064       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9065       const FunctionProtoType *FPT =
9066           NewFD->getType()->castAs<FunctionProtoType>();
9067       QualType Result =
9068           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9069       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9070                                              FPT->getExtProtoInfo()));
9071     }
9072 
9073     // C++ [dcl.fct.spec]p3:
9074     //  The inline specifier shall not appear on a block scope function
9075     //  declaration.
9076     if (isInline && !NewFD->isInvalidDecl()) {
9077       if (CurContext->isFunctionOrMethod()) {
9078         // 'inline' is not allowed on block scope function declaration.
9079         Diag(D.getDeclSpec().getInlineSpecLoc(),
9080              diag::err_inline_declaration_block_scope) << Name
9081           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9082       }
9083     }
9084 
9085     // C++ [dcl.fct.spec]p6:
9086     //  The explicit specifier shall be used only in the declaration of a
9087     //  constructor or conversion function within its class definition;
9088     //  see 12.3.1 and 12.3.2.
9089     if (hasExplicit && !NewFD->isInvalidDecl() &&
9090         !isa<CXXDeductionGuideDecl>(NewFD)) {
9091       if (!CurContext->isRecord()) {
9092         // 'explicit' was specified outside of the class.
9093         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9094              diag::err_explicit_out_of_class)
9095             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9096       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9097                  !isa<CXXConversionDecl>(NewFD)) {
9098         // 'explicit' was specified on a function that wasn't a constructor
9099         // or conversion function.
9100         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9101              diag::err_explicit_non_ctor_or_conv_function)
9102             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9103       }
9104     }
9105 
9106     if (ConstexprSpecKind ConstexprKind =
9107             D.getDeclSpec().getConstexprSpecifier()) {
9108       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9109       // are implicitly inline.
9110       NewFD->setImplicitlyInline();
9111 
9112       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9113       // be either constructors or to return a literal type. Therefore,
9114       // destructors cannot be declared constexpr.
9115       if (isa<CXXDestructorDecl>(NewFD) &&
9116           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9117         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9118             << ConstexprKind;
9119         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9120       }
9121       // C++20 [dcl.constexpr]p2: An allocation function, or a
9122       // deallocation function shall not be declared with the consteval
9123       // specifier.
9124       if (ConstexprKind == CSK_consteval &&
9125           (NewFD->getOverloadedOperator() == OO_New ||
9126            NewFD->getOverloadedOperator() == OO_Array_New ||
9127            NewFD->getOverloadedOperator() == OO_Delete ||
9128            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9129         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9130              diag::err_invalid_consteval_decl_kind)
9131             << NewFD;
9132         NewFD->setConstexprKind(CSK_constexpr);
9133       }
9134     }
9135 
9136     // If __module_private__ was specified, mark the function accordingly.
9137     if (D.getDeclSpec().isModulePrivateSpecified()) {
9138       if (isFunctionTemplateSpecialization) {
9139         SourceLocation ModulePrivateLoc
9140           = D.getDeclSpec().getModulePrivateSpecLoc();
9141         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9142           << 0
9143           << FixItHint::CreateRemoval(ModulePrivateLoc);
9144       } else {
9145         NewFD->setModulePrivate();
9146         if (FunctionTemplate)
9147           FunctionTemplate->setModulePrivate();
9148       }
9149     }
9150 
9151     if (isFriend) {
9152       if (FunctionTemplate) {
9153         FunctionTemplate->setObjectOfFriendDecl();
9154         FunctionTemplate->setAccess(AS_public);
9155       }
9156       NewFD->setObjectOfFriendDecl();
9157       NewFD->setAccess(AS_public);
9158     }
9159 
9160     // If a function is defined as defaulted or deleted, mark it as such now.
9161     // We'll do the relevant checks on defaulted / deleted functions later.
9162     switch (D.getFunctionDefinitionKind()) {
9163       case FDK_Declaration:
9164       case FDK_Definition:
9165         break;
9166 
9167       case FDK_Defaulted:
9168         NewFD->setDefaulted();
9169         break;
9170 
9171       case FDK_Deleted:
9172         NewFD->setDeletedAsWritten();
9173         break;
9174     }
9175 
9176     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9177         D.isFunctionDefinition()) {
9178       // C++ [class.mfct]p2:
9179       //   A member function may be defined (8.4) in its class definition, in
9180       //   which case it is an inline member function (7.1.2)
9181       NewFD->setImplicitlyInline();
9182     }
9183 
9184     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9185         !CurContext->isRecord()) {
9186       // C++ [class.static]p1:
9187       //   A data or function member of a class may be declared static
9188       //   in a class definition, in which case it is a static member of
9189       //   the class.
9190 
9191       // Complain about the 'static' specifier if it's on an out-of-line
9192       // member function definition.
9193 
9194       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9195       // member function template declaration and class member template
9196       // declaration (MSVC versions before 2015), warn about this.
9197       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9198            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9199              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9200            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9201            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9202         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9203     }
9204 
9205     // C++11 [except.spec]p15:
9206     //   A deallocation function with no exception-specification is treated
9207     //   as if it were specified with noexcept(true).
9208     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9209     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9210          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9211         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9212       NewFD->setType(Context.getFunctionType(
9213           FPT->getReturnType(), FPT->getParamTypes(),
9214           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9215   }
9216 
9217   // Filter out previous declarations that don't match the scope.
9218   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9219                        D.getCXXScopeSpec().isNotEmpty() ||
9220                        isMemberSpecialization ||
9221                        isFunctionTemplateSpecialization);
9222 
9223   // Handle GNU asm-label extension (encoded as an attribute).
9224   if (Expr *E = (Expr*) D.getAsmLabel()) {
9225     // The parser guarantees this is a string.
9226     StringLiteral *SE = cast<StringLiteral>(E);
9227     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9228                                         /*IsLiteralLabel=*/true,
9229                                         SE->getStrTokenLoc(0)));
9230   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9231     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9232       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9233     if (I != ExtnameUndeclaredIdentifiers.end()) {
9234       if (isDeclExternC(NewFD)) {
9235         NewFD->addAttr(I->second);
9236         ExtnameUndeclaredIdentifiers.erase(I);
9237       } else
9238         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9239             << /*Variable*/0 << NewFD;
9240     }
9241   }
9242 
9243   // Copy the parameter declarations from the declarator D to the function
9244   // declaration NewFD, if they are available.  First scavenge them into Params.
9245   SmallVector<ParmVarDecl*, 16> Params;
9246   unsigned FTIIdx;
9247   if (D.isFunctionDeclarator(FTIIdx)) {
9248     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9249 
9250     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9251     // function that takes no arguments, not a function that takes a
9252     // single void argument.
9253     // We let through "const void" here because Sema::GetTypeForDeclarator
9254     // already checks for that case.
9255     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9256       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9257         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9258         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9259         Param->setDeclContext(NewFD);
9260         Params.push_back(Param);
9261 
9262         if (Param->isInvalidDecl())
9263           NewFD->setInvalidDecl();
9264       }
9265     }
9266 
9267     if (!getLangOpts().CPlusPlus) {
9268       // In C, find all the tag declarations from the prototype and move them
9269       // into the function DeclContext. Remove them from the surrounding tag
9270       // injection context of the function, which is typically but not always
9271       // the TU.
9272       DeclContext *PrototypeTagContext =
9273           getTagInjectionContext(NewFD->getLexicalDeclContext());
9274       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9275         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9276 
9277         // We don't want to reparent enumerators. Look at their parent enum
9278         // instead.
9279         if (!TD) {
9280           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9281             TD = cast<EnumDecl>(ECD->getDeclContext());
9282         }
9283         if (!TD)
9284           continue;
9285         DeclContext *TagDC = TD->getLexicalDeclContext();
9286         if (!TagDC->containsDecl(TD))
9287           continue;
9288         TagDC->removeDecl(TD);
9289         TD->setDeclContext(NewFD);
9290         NewFD->addDecl(TD);
9291 
9292         // Preserve the lexical DeclContext if it is not the surrounding tag
9293         // injection context of the FD. In this example, the semantic context of
9294         // E will be f and the lexical context will be S, while both the
9295         // semantic and lexical contexts of S will be f:
9296         //   void f(struct S { enum E { a } f; } s);
9297         if (TagDC != PrototypeTagContext)
9298           TD->setLexicalDeclContext(TagDC);
9299       }
9300     }
9301   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9302     // When we're declaring a function with a typedef, typeof, etc as in the
9303     // following example, we'll need to synthesize (unnamed)
9304     // parameters for use in the declaration.
9305     //
9306     // @code
9307     // typedef void fn(int);
9308     // fn f;
9309     // @endcode
9310 
9311     // Synthesize a parameter for each argument type.
9312     for (const auto &AI : FT->param_types()) {
9313       ParmVarDecl *Param =
9314           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9315       Param->setScopeInfo(0, Params.size());
9316       Params.push_back(Param);
9317     }
9318   } else {
9319     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9320            "Should not need args for typedef of non-prototype fn");
9321   }
9322 
9323   // Finally, we know we have the right number of parameters, install them.
9324   NewFD->setParams(Params);
9325 
9326   if (D.getDeclSpec().isNoreturnSpecified())
9327     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9328                                            D.getDeclSpec().getNoreturnSpecLoc(),
9329                                            AttributeCommonInfo::AS_Keyword));
9330 
9331   // Functions returning a variably modified type violate C99 6.7.5.2p2
9332   // because all functions have linkage.
9333   if (!NewFD->isInvalidDecl() &&
9334       NewFD->getReturnType()->isVariablyModifiedType()) {
9335     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9336     NewFD->setInvalidDecl();
9337   }
9338 
9339   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9340   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9341       !NewFD->hasAttr<SectionAttr>())
9342     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9343         Context, PragmaClangTextSection.SectionName,
9344         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9345 
9346   // Apply an implicit SectionAttr if #pragma code_seg is active.
9347   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9348       !NewFD->hasAttr<SectionAttr>()) {
9349     NewFD->addAttr(SectionAttr::CreateImplicit(
9350         Context, CodeSegStack.CurrentValue->getString(),
9351         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9352         SectionAttr::Declspec_allocate));
9353     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9354                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9355                          ASTContext::PSF_Read,
9356                      NewFD))
9357       NewFD->dropAttr<SectionAttr>();
9358   }
9359 
9360   // Apply an implicit CodeSegAttr from class declspec or
9361   // apply an implicit SectionAttr from #pragma code_seg if active.
9362   if (!NewFD->hasAttr<CodeSegAttr>()) {
9363     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9364                                                                  D.isFunctionDefinition())) {
9365       NewFD->addAttr(SAttr);
9366     }
9367   }
9368 
9369   // Handle attributes.
9370   ProcessDeclAttributes(S, NewFD, D);
9371 
9372   if (getLangOpts().OpenCL) {
9373     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9374     // type declaration will generate a compilation error.
9375     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9376     if (AddressSpace != LangAS::Default) {
9377       Diag(NewFD->getLocation(),
9378            diag::err_opencl_return_value_with_address_space);
9379       NewFD->setInvalidDecl();
9380     }
9381   }
9382 
9383   if (!getLangOpts().CPlusPlus) {
9384     // Perform semantic checking on the function declaration.
9385     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9386       CheckMain(NewFD, D.getDeclSpec());
9387 
9388     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9389       CheckMSVCRTEntryPoint(NewFD);
9390 
9391     if (!NewFD->isInvalidDecl())
9392       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9393                                                   isMemberSpecialization));
9394     else if (!Previous.empty())
9395       // Recover gracefully from an invalid redeclaration.
9396       D.setRedeclaration(true);
9397     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9398             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9399            "previous declaration set still overloaded");
9400 
9401     // Diagnose no-prototype function declarations with calling conventions that
9402     // don't support variadic calls. Only do this in C and do it after merging
9403     // possibly prototyped redeclarations.
9404     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9405     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9406       CallingConv CC = FT->getExtInfo().getCC();
9407       if (!supportsVariadicCall(CC)) {
9408         // Windows system headers sometimes accidentally use stdcall without
9409         // (void) parameters, so we relax this to a warning.
9410         int DiagID =
9411             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9412         Diag(NewFD->getLocation(), DiagID)
9413             << FunctionType::getNameForCallConv(CC);
9414       }
9415     }
9416 
9417    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9418        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9419      checkNonTrivialCUnion(NewFD->getReturnType(),
9420                            NewFD->getReturnTypeSourceRange().getBegin(),
9421                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9422   } else {
9423     // C++11 [replacement.functions]p3:
9424     //  The program's definitions shall not be specified as inline.
9425     //
9426     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9427     //
9428     // Suppress the diagnostic if the function is __attribute__((used)), since
9429     // that forces an external definition to be emitted.
9430     if (D.getDeclSpec().isInlineSpecified() &&
9431         NewFD->isReplaceableGlobalAllocationFunction() &&
9432         !NewFD->hasAttr<UsedAttr>())
9433       Diag(D.getDeclSpec().getInlineSpecLoc(),
9434            diag::ext_operator_new_delete_declared_inline)
9435         << NewFD->getDeclName();
9436 
9437     // If the declarator is a template-id, translate the parser's template
9438     // argument list into our AST format.
9439     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9440       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9441       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9442       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9443       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9444                                          TemplateId->NumArgs);
9445       translateTemplateArguments(TemplateArgsPtr,
9446                                  TemplateArgs);
9447 
9448       HasExplicitTemplateArgs = true;
9449 
9450       if (NewFD->isInvalidDecl()) {
9451         HasExplicitTemplateArgs = false;
9452       } else if (FunctionTemplate) {
9453         // Function template with explicit template arguments.
9454         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9455           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9456 
9457         HasExplicitTemplateArgs = false;
9458       } else {
9459         assert((isFunctionTemplateSpecialization ||
9460                 D.getDeclSpec().isFriendSpecified()) &&
9461                "should have a 'template<>' for this decl");
9462         // "friend void foo<>(int);" is an implicit specialization decl.
9463         isFunctionTemplateSpecialization = true;
9464       }
9465     } else if (isFriend && isFunctionTemplateSpecialization) {
9466       // This combination is only possible in a recovery case;  the user
9467       // wrote something like:
9468       //   template <> friend void foo(int);
9469       // which we're recovering from as if the user had written:
9470       //   friend void foo<>(int);
9471       // Go ahead and fake up a template id.
9472       HasExplicitTemplateArgs = true;
9473       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9474       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9475     }
9476 
9477     // We do not add HD attributes to specializations here because
9478     // they may have different constexpr-ness compared to their
9479     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9480     // may end up with different effective targets. Instead, a
9481     // specialization inherits its target attributes from its template
9482     // in the CheckFunctionTemplateSpecialization() call below.
9483     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9484       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9485 
9486     // If it's a friend (and only if it's a friend), it's possible
9487     // that either the specialized function type or the specialized
9488     // template is dependent, and therefore matching will fail.  In
9489     // this case, don't check the specialization yet.
9490     bool InstantiationDependent = false;
9491     if (isFunctionTemplateSpecialization && isFriend &&
9492         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9493          TemplateSpecializationType::anyDependentTemplateArguments(
9494             TemplateArgs,
9495             InstantiationDependent))) {
9496       assert(HasExplicitTemplateArgs &&
9497              "friend function specialization without template args");
9498       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9499                                                        Previous))
9500         NewFD->setInvalidDecl();
9501     } else if (isFunctionTemplateSpecialization) {
9502       if (CurContext->isDependentContext() && CurContext->isRecord()
9503           && !isFriend) {
9504         isDependentClassScopeExplicitSpecialization = true;
9505       } else if (!NewFD->isInvalidDecl() &&
9506                  CheckFunctionTemplateSpecialization(
9507                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9508                      Previous))
9509         NewFD->setInvalidDecl();
9510 
9511       // C++ [dcl.stc]p1:
9512       //   A storage-class-specifier shall not be specified in an explicit
9513       //   specialization (14.7.3)
9514       FunctionTemplateSpecializationInfo *Info =
9515           NewFD->getTemplateSpecializationInfo();
9516       if (Info && SC != SC_None) {
9517         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9518           Diag(NewFD->getLocation(),
9519                diag::err_explicit_specialization_inconsistent_storage_class)
9520             << SC
9521             << FixItHint::CreateRemoval(
9522                                       D.getDeclSpec().getStorageClassSpecLoc());
9523 
9524         else
9525           Diag(NewFD->getLocation(),
9526                diag::ext_explicit_specialization_storage_class)
9527             << FixItHint::CreateRemoval(
9528                                       D.getDeclSpec().getStorageClassSpecLoc());
9529       }
9530     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9531       if (CheckMemberSpecialization(NewFD, Previous))
9532           NewFD->setInvalidDecl();
9533     }
9534 
9535     // Perform semantic checking on the function declaration.
9536     if (!isDependentClassScopeExplicitSpecialization) {
9537       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9538         CheckMain(NewFD, D.getDeclSpec());
9539 
9540       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9541         CheckMSVCRTEntryPoint(NewFD);
9542 
9543       if (!NewFD->isInvalidDecl())
9544         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9545                                                     isMemberSpecialization));
9546       else if (!Previous.empty())
9547         // Recover gracefully from an invalid redeclaration.
9548         D.setRedeclaration(true);
9549     }
9550 
9551     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9552             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9553            "previous declaration set still overloaded");
9554 
9555     NamedDecl *PrincipalDecl = (FunctionTemplate
9556                                 ? cast<NamedDecl>(FunctionTemplate)
9557                                 : NewFD);
9558 
9559     if (isFriend && NewFD->getPreviousDecl()) {
9560       AccessSpecifier Access = AS_public;
9561       if (!NewFD->isInvalidDecl())
9562         Access = NewFD->getPreviousDecl()->getAccess();
9563 
9564       NewFD->setAccess(Access);
9565       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9566     }
9567 
9568     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9569         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9570       PrincipalDecl->setNonMemberOperator();
9571 
9572     // If we have a function template, check the template parameter
9573     // list. This will check and merge default template arguments.
9574     if (FunctionTemplate) {
9575       FunctionTemplateDecl *PrevTemplate =
9576                                      FunctionTemplate->getPreviousDecl();
9577       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9578                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9579                                     : nullptr,
9580                             D.getDeclSpec().isFriendSpecified()
9581                               ? (D.isFunctionDefinition()
9582                                    ? TPC_FriendFunctionTemplateDefinition
9583                                    : TPC_FriendFunctionTemplate)
9584                               : (D.getCXXScopeSpec().isSet() &&
9585                                  DC && DC->isRecord() &&
9586                                  DC->isDependentContext())
9587                                   ? TPC_ClassTemplateMember
9588                                   : TPC_FunctionTemplate);
9589     }
9590 
9591     if (NewFD->isInvalidDecl()) {
9592       // Ignore all the rest of this.
9593     } else if (!D.isRedeclaration()) {
9594       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9595                                        AddToScope };
9596       // Fake up an access specifier if it's supposed to be a class member.
9597       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9598         NewFD->setAccess(AS_public);
9599 
9600       // Qualified decls generally require a previous declaration.
9601       if (D.getCXXScopeSpec().isSet()) {
9602         // ...with the major exception of templated-scope or
9603         // dependent-scope friend declarations.
9604 
9605         // TODO: we currently also suppress this check in dependent
9606         // contexts because (1) the parameter depth will be off when
9607         // matching friend templates and (2) we might actually be
9608         // selecting a friend based on a dependent factor.  But there
9609         // are situations where these conditions don't apply and we
9610         // can actually do this check immediately.
9611         //
9612         // Unless the scope is dependent, it's always an error if qualified
9613         // redeclaration lookup found nothing at all. Diagnose that now;
9614         // nothing will diagnose that error later.
9615         if (isFriend &&
9616             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9617              (!Previous.empty() && CurContext->isDependentContext()))) {
9618           // ignore these
9619         } else {
9620           // The user tried to provide an out-of-line definition for a
9621           // function that is a member of a class or namespace, but there
9622           // was no such member function declared (C++ [class.mfct]p2,
9623           // C++ [namespace.memdef]p2). For example:
9624           //
9625           // class X {
9626           //   void f() const;
9627           // };
9628           //
9629           // void X::f() { } // ill-formed
9630           //
9631           // Complain about this problem, and attempt to suggest close
9632           // matches (e.g., those that differ only in cv-qualifiers and
9633           // whether the parameter types are references).
9634 
9635           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9636                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9637             AddToScope = ExtraArgs.AddToScope;
9638             return Result;
9639           }
9640         }
9641 
9642         // Unqualified local friend declarations are required to resolve
9643         // to something.
9644       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9645         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9646                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9647           AddToScope = ExtraArgs.AddToScope;
9648           return Result;
9649         }
9650       }
9651     } else if (!D.isFunctionDefinition() &&
9652                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9653                !isFriend && !isFunctionTemplateSpecialization &&
9654                !isMemberSpecialization) {
9655       // An out-of-line member function declaration must also be a
9656       // definition (C++ [class.mfct]p2).
9657       // Note that this is not the case for explicit specializations of
9658       // function templates or member functions of class templates, per
9659       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9660       // extension for compatibility with old SWIG code which likes to
9661       // generate them.
9662       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9663         << D.getCXXScopeSpec().getRange();
9664     }
9665   }
9666 
9667   ProcessPragmaWeak(S, NewFD);
9668   checkAttributesAfterMerging(*this, *NewFD);
9669 
9670   AddKnownFunctionAttributes(NewFD);
9671 
9672   if (NewFD->hasAttr<OverloadableAttr>() &&
9673       !NewFD->getType()->getAs<FunctionProtoType>()) {
9674     Diag(NewFD->getLocation(),
9675          diag::err_attribute_overloadable_no_prototype)
9676       << NewFD;
9677 
9678     // Turn this into a variadic function with no parameters.
9679     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9680     FunctionProtoType::ExtProtoInfo EPI(
9681         Context.getDefaultCallingConvention(true, false));
9682     EPI.Variadic = true;
9683     EPI.ExtInfo = FT->getExtInfo();
9684 
9685     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9686     NewFD->setType(R);
9687   }
9688 
9689   // If there's a #pragma GCC visibility in scope, and this isn't a class
9690   // member, set the visibility of this function.
9691   if (!DC->isRecord() && NewFD->isExternallyVisible())
9692     AddPushedVisibilityAttribute(NewFD);
9693 
9694   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9695   // marking the function.
9696   AddCFAuditedAttribute(NewFD);
9697 
9698   // If this is a function definition, check if we have to apply optnone due to
9699   // a pragma.
9700   if(D.isFunctionDefinition())
9701     AddRangeBasedOptnone(NewFD);
9702 
9703   // If this is the first declaration of an extern C variable, update
9704   // the map of such variables.
9705   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9706       isIncompleteDeclExternC(*this, NewFD))
9707     RegisterLocallyScopedExternCDecl(NewFD, S);
9708 
9709   // Set this FunctionDecl's range up to the right paren.
9710   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9711 
9712   if (D.isRedeclaration() && !Previous.empty()) {
9713     NamedDecl *Prev = Previous.getRepresentativeDecl();
9714     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9715                                    isMemberSpecialization ||
9716                                        isFunctionTemplateSpecialization,
9717                                    D.isFunctionDefinition());
9718   }
9719 
9720   if (getLangOpts().CUDA) {
9721     IdentifierInfo *II = NewFD->getIdentifier();
9722     if (II && II->isStr(getCudaConfigureFuncName()) &&
9723         !NewFD->isInvalidDecl() &&
9724         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9725       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9726         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9727             << getCudaConfigureFuncName();
9728       Context.setcudaConfigureCallDecl(NewFD);
9729     }
9730 
9731     // Variadic functions, other than a *declaration* of printf, are not allowed
9732     // in device-side CUDA code, unless someone passed
9733     // -fcuda-allow-variadic-functions.
9734     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9735         (NewFD->hasAttr<CUDADeviceAttr>() ||
9736          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9737         !(II && II->isStr("printf") && NewFD->isExternC() &&
9738           !D.isFunctionDefinition())) {
9739       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9740     }
9741   }
9742 
9743   MarkUnusedFileScopedDecl(NewFD);
9744 
9745 
9746 
9747   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9748     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9749     if ((getLangOpts().OpenCLVersion >= 120)
9750         && (SC == SC_Static)) {
9751       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9752       D.setInvalidType();
9753     }
9754 
9755     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9756     if (!NewFD->getReturnType()->isVoidType()) {
9757       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9758       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9759           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9760                                 : FixItHint());
9761       D.setInvalidType();
9762     }
9763 
9764     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9765     for (auto Param : NewFD->parameters())
9766       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9767 
9768     if (getLangOpts().OpenCLCPlusPlus) {
9769       if (DC->isRecord()) {
9770         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9771         D.setInvalidType();
9772       }
9773       if (FunctionTemplate) {
9774         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9775         D.setInvalidType();
9776       }
9777     }
9778   }
9779 
9780   if (getLangOpts().CPlusPlus) {
9781     if (FunctionTemplate) {
9782       if (NewFD->isInvalidDecl())
9783         FunctionTemplate->setInvalidDecl();
9784       return FunctionTemplate;
9785     }
9786 
9787     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9788       CompleteMemberSpecialization(NewFD, Previous);
9789   }
9790 
9791   for (const ParmVarDecl *Param : NewFD->parameters()) {
9792     QualType PT = Param->getType();
9793 
9794     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9795     // types.
9796     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9797       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9798         QualType ElemTy = PipeTy->getElementType();
9799           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9800             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9801             D.setInvalidType();
9802           }
9803       }
9804     }
9805   }
9806 
9807   // Here we have an function template explicit specialization at class scope.
9808   // The actual specialization will be postponed to template instatiation
9809   // time via the ClassScopeFunctionSpecializationDecl node.
9810   if (isDependentClassScopeExplicitSpecialization) {
9811     ClassScopeFunctionSpecializationDecl *NewSpec =
9812                          ClassScopeFunctionSpecializationDecl::Create(
9813                                 Context, CurContext, NewFD->getLocation(),
9814                                 cast<CXXMethodDecl>(NewFD),
9815                                 HasExplicitTemplateArgs, TemplateArgs);
9816     CurContext->addDecl(NewSpec);
9817     AddToScope = false;
9818   }
9819 
9820   // Diagnose availability attributes. Availability cannot be used on functions
9821   // that are run during load/unload.
9822   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9823     if (NewFD->hasAttr<ConstructorAttr>()) {
9824       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9825           << 1;
9826       NewFD->dropAttr<AvailabilityAttr>();
9827     }
9828     if (NewFD->hasAttr<DestructorAttr>()) {
9829       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9830           << 2;
9831       NewFD->dropAttr<AvailabilityAttr>();
9832     }
9833   }
9834 
9835   // Diagnose no_builtin attribute on function declaration that are not a
9836   // definition.
9837   // FIXME: We should really be doing this in
9838   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9839   // the FunctionDecl and at this point of the code
9840   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9841   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9842   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9843     switch (D.getFunctionDefinitionKind()) {
9844     case FDK_Defaulted:
9845     case FDK_Deleted:
9846       Diag(NBA->getLocation(),
9847            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9848           << NBA->getSpelling();
9849       break;
9850     case FDK_Declaration:
9851       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9852           << NBA->getSpelling();
9853       break;
9854     case FDK_Definition:
9855       break;
9856     }
9857 
9858   return NewFD;
9859 }
9860 
9861 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9862 /// when __declspec(code_seg) "is applied to a class, all member functions of
9863 /// the class and nested classes -- this includes compiler-generated special
9864 /// member functions -- are put in the specified segment."
9865 /// The actual behavior is a little more complicated. The Microsoft compiler
9866 /// won't check outer classes if there is an active value from #pragma code_seg.
9867 /// The CodeSeg is always applied from the direct parent but only from outer
9868 /// classes when the #pragma code_seg stack is empty. See:
9869 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9870 /// available since MS has removed the page.
9871 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9872   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9873   if (!Method)
9874     return nullptr;
9875   const CXXRecordDecl *Parent = Method->getParent();
9876   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9877     Attr *NewAttr = SAttr->clone(S.getASTContext());
9878     NewAttr->setImplicit(true);
9879     return NewAttr;
9880   }
9881 
9882   // The Microsoft compiler won't check outer classes for the CodeSeg
9883   // when the #pragma code_seg stack is active.
9884   if (S.CodeSegStack.CurrentValue)
9885    return nullptr;
9886 
9887   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9888     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9889       Attr *NewAttr = SAttr->clone(S.getASTContext());
9890       NewAttr->setImplicit(true);
9891       return NewAttr;
9892     }
9893   }
9894   return nullptr;
9895 }
9896 
9897 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9898 /// containing class. Otherwise it will return implicit SectionAttr if the
9899 /// function is a definition and there is an active value on CodeSegStack
9900 /// (from the current #pragma code-seg value).
9901 ///
9902 /// \param FD Function being declared.
9903 /// \param IsDefinition Whether it is a definition or just a declarartion.
9904 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9905 ///          nullptr if no attribute should be added.
9906 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9907                                                        bool IsDefinition) {
9908   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9909     return A;
9910   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9911       CodeSegStack.CurrentValue)
9912     return SectionAttr::CreateImplicit(
9913         getASTContext(), CodeSegStack.CurrentValue->getString(),
9914         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9915         SectionAttr::Declspec_allocate);
9916   return nullptr;
9917 }
9918 
9919 /// Determines if we can perform a correct type check for \p D as a
9920 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9921 /// best-effort check.
9922 ///
9923 /// \param NewD The new declaration.
9924 /// \param OldD The old declaration.
9925 /// \param NewT The portion of the type of the new declaration to check.
9926 /// \param OldT The portion of the type of the old declaration to check.
9927 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9928                                           QualType NewT, QualType OldT) {
9929   if (!NewD->getLexicalDeclContext()->isDependentContext())
9930     return true;
9931 
9932   // For dependently-typed local extern declarations and friends, we can't
9933   // perform a correct type check in general until instantiation:
9934   //
9935   //   int f();
9936   //   template<typename T> void g() { T f(); }
9937   //
9938   // (valid if g() is only instantiated with T = int).
9939   if (NewT->isDependentType() &&
9940       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9941     return false;
9942 
9943   // Similarly, if the previous declaration was a dependent local extern
9944   // declaration, we don't really know its type yet.
9945   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9946     return false;
9947 
9948   return true;
9949 }
9950 
9951 /// Checks if the new declaration declared in dependent context must be
9952 /// put in the same redeclaration chain as the specified declaration.
9953 ///
9954 /// \param D Declaration that is checked.
9955 /// \param PrevDecl Previous declaration found with proper lookup method for the
9956 ///                 same declaration name.
9957 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9958 ///          belongs to.
9959 ///
9960 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9961   if (!D->getLexicalDeclContext()->isDependentContext())
9962     return true;
9963 
9964   // Don't chain dependent friend function definitions until instantiation, to
9965   // permit cases like
9966   //
9967   //   void func();
9968   //   template<typename T> class C1 { friend void func() {} };
9969   //   template<typename T> class C2 { friend void func() {} };
9970   //
9971   // ... which is valid if only one of C1 and C2 is ever instantiated.
9972   //
9973   // FIXME: This need only apply to function definitions. For now, we proxy
9974   // this by checking for a file-scope function. We do not want this to apply
9975   // to friend declarations nominating member functions, because that gets in
9976   // the way of access checks.
9977   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9978     return false;
9979 
9980   auto *VD = dyn_cast<ValueDecl>(D);
9981   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9982   return !VD || !PrevVD ||
9983          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9984                                         PrevVD->getType());
9985 }
9986 
9987 /// Check the target attribute of the function for MultiVersion
9988 /// validity.
9989 ///
9990 /// Returns true if there was an error, false otherwise.
9991 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9992   const auto *TA = FD->getAttr<TargetAttr>();
9993   assert(TA && "MultiVersion Candidate requires a target attribute");
9994   ParsedTargetAttr ParseInfo = TA->parse();
9995   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9996   enum ErrType { Feature = 0, Architecture = 1 };
9997 
9998   if (!ParseInfo.Architecture.empty() &&
9999       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10000     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10001         << Architecture << ParseInfo.Architecture;
10002     return true;
10003   }
10004 
10005   for (const auto &Feat : ParseInfo.Features) {
10006     auto BareFeat = StringRef{Feat}.substr(1);
10007     if (Feat[0] == '-') {
10008       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10009           << Feature << ("no-" + BareFeat).str();
10010       return true;
10011     }
10012 
10013     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10014         !TargetInfo.isValidFeatureName(BareFeat)) {
10015       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10016           << Feature << BareFeat;
10017       return true;
10018     }
10019   }
10020   return false;
10021 }
10022 
10023 // Provide a white-list of attributes that are allowed to be combined with
10024 // multiversion functions.
10025 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10026                                            MultiVersionKind MVType) {
10027   // Note: this list/diagnosis must match the list in
10028   // checkMultiversionAttributesAllSame.
10029   switch (Kind) {
10030   default:
10031     return false;
10032   case attr::Used:
10033     return MVType == MultiVersionKind::Target;
10034   case attr::NonNull:
10035   case attr::NoThrow:
10036     return true;
10037   }
10038 }
10039 
10040 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10041                                                  const FunctionDecl *FD,
10042                                                  const FunctionDecl *CausedFD,
10043                                                  MultiVersionKind MVType) {
10044   bool IsCPUSpecificCPUDispatchMVType =
10045       MVType == MultiVersionKind::CPUDispatch ||
10046       MVType == MultiVersionKind::CPUSpecific;
10047   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10048                             Sema &S, const Attr *A) {
10049     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10050         << IsCPUSpecificCPUDispatchMVType << A;
10051     if (CausedFD)
10052       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10053     return true;
10054   };
10055 
10056   for (const Attr *A : FD->attrs()) {
10057     switch (A->getKind()) {
10058     case attr::CPUDispatch:
10059     case attr::CPUSpecific:
10060       if (MVType != MultiVersionKind::CPUDispatch &&
10061           MVType != MultiVersionKind::CPUSpecific)
10062         return Diagnose(S, A);
10063       break;
10064     case attr::Target:
10065       if (MVType != MultiVersionKind::Target)
10066         return Diagnose(S, A);
10067       break;
10068     default:
10069       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10070         return Diagnose(S, A);
10071       break;
10072     }
10073   }
10074   return false;
10075 }
10076 
10077 bool Sema::areMultiversionVariantFunctionsCompatible(
10078     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10079     const PartialDiagnostic &NoProtoDiagID,
10080     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10081     const PartialDiagnosticAt &NoSupportDiagIDAt,
10082     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10083     bool ConstexprSupported, bool CLinkageMayDiffer) {
10084   enum DoesntSupport {
10085     FuncTemplates = 0,
10086     VirtFuncs = 1,
10087     DeducedReturn = 2,
10088     Constructors = 3,
10089     Destructors = 4,
10090     DeletedFuncs = 5,
10091     DefaultedFuncs = 6,
10092     ConstexprFuncs = 7,
10093     ConstevalFuncs = 8,
10094   };
10095   enum Different {
10096     CallingConv = 0,
10097     ReturnType = 1,
10098     ConstexprSpec = 2,
10099     InlineSpec = 3,
10100     StorageClass = 4,
10101     Linkage = 5,
10102   };
10103 
10104   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10105       !OldFD->getType()->getAs<FunctionProtoType>()) {
10106     Diag(OldFD->getLocation(), NoProtoDiagID);
10107     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10108     return true;
10109   }
10110 
10111   if (NoProtoDiagID.getDiagID() != 0 &&
10112       !NewFD->getType()->getAs<FunctionProtoType>())
10113     return Diag(NewFD->getLocation(), NoProtoDiagID);
10114 
10115   if (!TemplatesSupported &&
10116       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10117     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10118            << FuncTemplates;
10119 
10120   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10121     if (NewCXXFD->isVirtual())
10122       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10123              << VirtFuncs;
10124 
10125     if (isa<CXXConstructorDecl>(NewCXXFD))
10126       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10127              << Constructors;
10128 
10129     if (isa<CXXDestructorDecl>(NewCXXFD))
10130       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10131              << Destructors;
10132   }
10133 
10134   if (NewFD->isDeleted())
10135     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10136            << DeletedFuncs;
10137 
10138   if (NewFD->isDefaulted())
10139     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10140            << DefaultedFuncs;
10141 
10142   if (!ConstexprSupported && NewFD->isConstexpr())
10143     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10144            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10145 
10146   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10147   const auto *NewType = cast<FunctionType>(NewQType);
10148   QualType NewReturnType = NewType->getReturnType();
10149 
10150   if (NewReturnType->isUndeducedType())
10151     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10152            << DeducedReturn;
10153 
10154   // Ensure the return type is identical.
10155   if (OldFD) {
10156     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10157     const auto *OldType = cast<FunctionType>(OldQType);
10158     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10159     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10160 
10161     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10162       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10163 
10164     QualType OldReturnType = OldType->getReturnType();
10165 
10166     if (OldReturnType != NewReturnType)
10167       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10168 
10169     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10170       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10171 
10172     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10173       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10174 
10175     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10176       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10177 
10178     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10179       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10180 
10181     if (CheckEquivalentExceptionSpec(
10182             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10183             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10184       return true;
10185   }
10186   return false;
10187 }
10188 
10189 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10190                                              const FunctionDecl *NewFD,
10191                                              bool CausesMV,
10192                                              MultiVersionKind MVType) {
10193   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10194     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10195     if (OldFD)
10196       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10197     return true;
10198   }
10199 
10200   bool IsCPUSpecificCPUDispatchMVType =
10201       MVType == MultiVersionKind::CPUDispatch ||
10202       MVType == MultiVersionKind::CPUSpecific;
10203 
10204   if (CausesMV && OldFD &&
10205       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10206     return true;
10207 
10208   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10209     return true;
10210 
10211   // Only allow transition to MultiVersion if it hasn't been used.
10212   if (OldFD && CausesMV && OldFD->isUsed(false))
10213     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10214 
10215   return S.areMultiversionVariantFunctionsCompatible(
10216       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10217       PartialDiagnosticAt(NewFD->getLocation(),
10218                           S.PDiag(diag::note_multiversioning_caused_here)),
10219       PartialDiagnosticAt(NewFD->getLocation(),
10220                           S.PDiag(diag::err_multiversion_doesnt_support)
10221                               << IsCPUSpecificCPUDispatchMVType),
10222       PartialDiagnosticAt(NewFD->getLocation(),
10223                           S.PDiag(diag::err_multiversion_diff)),
10224       /*TemplatesSupported=*/false,
10225       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10226       /*CLinkageMayDiffer=*/false);
10227 }
10228 
10229 /// Check the validity of a multiversion function declaration that is the
10230 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10231 ///
10232 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10233 ///
10234 /// Returns true if there was an error, false otherwise.
10235 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10236                                            MultiVersionKind MVType,
10237                                            const TargetAttr *TA) {
10238   assert(MVType != MultiVersionKind::None &&
10239          "Function lacks multiversion attribute");
10240 
10241   // Target only causes MV if it is default, otherwise this is a normal
10242   // function.
10243   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10244     return false;
10245 
10246   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10247     FD->setInvalidDecl();
10248     return true;
10249   }
10250 
10251   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10252     FD->setInvalidDecl();
10253     return true;
10254   }
10255 
10256   FD->setIsMultiVersion();
10257   return false;
10258 }
10259 
10260 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10261   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10262     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10263       return true;
10264   }
10265 
10266   return false;
10267 }
10268 
10269 static bool CheckTargetCausesMultiVersioning(
10270     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10271     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10272     LookupResult &Previous) {
10273   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10274   ParsedTargetAttr NewParsed = NewTA->parse();
10275   // Sort order doesn't matter, it just needs to be consistent.
10276   llvm::sort(NewParsed.Features);
10277 
10278   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10279   // to change, this is a simple redeclaration.
10280   if (!NewTA->isDefaultVersion() &&
10281       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10282     return false;
10283 
10284   // Otherwise, this decl causes MultiVersioning.
10285   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10286     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10287     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10288     NewFD->setInvalidDecl();
10289     return true;
10290   }
10291 
10292   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10293                                        MultiVersionKind::Target)) {
10294     NewFD->setInvalidDecl();
10295     return true;
10296   }
10297 
10298   if (CheckMultiVersionValue(S, NewFD)) {
10299     NewFD->setInvalidDecl();
10300     return true;
10301   }
10302 
10303   // If this is 'default', permit the forward declaration.
10304   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10305     Redeclaration = true;
10306     OldDecl = OldFD;
10307     OldFD->setIsMultiVersion();
10308     NewFD->setIsMultiVersion();
10309     return false;
10310   }
10311 
10312   if (CheckMultiVersionValue(S, OldFD)) {
10313     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10314     NewFD->setInvalidDecl();
10315     return true;
10316   }
10317 
10318   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10319 
10320   if (OldParsed == NewParsed) {
10321     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10322     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10323     NewFD->setInvalidDecl();
10324     return true;
10325   }
10326 
10327   for (const auto *FD : OldFD->redecls()) {
10328     const auto *CurTA = FD->getAttr<TargetAttr>();
10329     // We allow forward declarations before ANY multiversioning attributes, but
10330     // nothing after the fact.
10331     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10332         (!CurTA || CurTA->isInherited())) {
10333       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10334           << 0;
10335       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10336       NewFD->setInvalidDecl();
10337       return true;
10338     }
10339   }
10340 
10341   OldFD->setIsMultiVersion();
10342   NewFD->setIsMultiVersion();
10343   Redeclaration = false;
10344   MergeTypeWithPrevious = false;
10345   OldDecl = nullptr;
10346   Previous.clear();
10347   return false;
10348 }
10349 
10350 /// Check the validity of a new function declaration being added to an existing
10351 /// multiversioned declaration collection.
10352 static bool CheckMultiVersionAdditionalDecl(
10353     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10354     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10355     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10356     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10357     LookupResult &Previous) {
10358 
10359   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10360   // Disallow mixing of multiversioning types.
10361   if ((OldMVType == MultiVersionKind::Target &&
10362        NewMVType != MultiVersionKind::Target) ||
10363       (NewMVType == MultiVersionKind::Target &&
10364        OldMVType != MultiVersionKind::Target)) {
10365     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10366     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10367     NewFD->setInvalidDecl();
10368     return true;
10369   }
10370 
10371   ParsedTargetAttr NewParsed;
10372   if (NewTA) {
10373     NewParsed = NewTA->parse();
10374     llvm::sort(NewParsed.Features);
10375   }
10376 
10377   bool UseMemberUsingDeclRules =
10378       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10379 
10380   // Next, check ALL non-overloads to see if this is a redeclaration of a
10381   // previous member of the MultiVersion set.
10382   for (NamedDecl *ND : Previous) {
10383     FunctionDecl *CurFD = ND->getAsFunction();
10384     if (!CurFD)
10385       continue;
10386     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10387       continue;
10388 
10389     if (NewMVType == MultiVersionKind::Target) {
10390       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10391       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10392         NewFD->setIsMultiVersion();
10393         Redeclaration = true;
10394         OldDecl = ND;
10395         return false;
10396       }
10397 
10398       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10399       if (CurParsed == NewParsed) {
10400         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10401         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10402         NewFD->setInvalidDecl();
10403         return true;
10404       }
10405     } else {
10406       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10407       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10408       // Handle CPUDispatch/CPUSpecific versions.
10409       // Only 1 CPUDispatch function is allowed, this will make it go through
10410       // the redeclaration errors.
10411       if (NewMVType == MultiVersionKind::CPUDispatch &&
10412           CurFD->hasAttr<CPUDispatchAttr>()) {
10413         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10414             std::equal(
10415                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10416                 NewCPUDisp->cpus_begin(),
10417                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10418                   return Cur->getName() == New->getName();
10419                 })) {
10420           NewFD->setIsMultiVersion();
10421           Redeclaration = true;
10422           OldDecl = ND;
10423           return false;
10424         }
10425 
10426         // If the declarations don't match, this is an error condition.
10427         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10428         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10429         NewFD->setInvalidDecl();
10430         return true;
10431       }
10432       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10433 
10434         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10435             std::equal(
10436                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10437                 NewCPUSpec->cpus_begin(),
10438                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10439                   return Cur->getName() == New->getName();
10440                 })) {
10441           NewFD->setIsMultiVersion();
10442           Redeclaration = true;
10443           OldDecl = ND;
10444           return false;
10445         }
10446 
10447         // Only 1 version of CPUSpecific is allowed for each CPU.
10448         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10449           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10450             if (CurII == NewII) {
10451               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10452                   << NewII;
10453               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10454               NewFD->setInvalidDecl();
10455               return true;
10456             }
10457           }
10458         }
10459       }
10460       // If the two decls aren't the same MVType, there is no possible error
10461       // condition.
10462     }
10463   }
10464 
10465   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10466   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10467   // handled in the attribute adding step.
10468   if (NewMVType == MultiVersionKind::Target &&
10469       CheckMultiVersionValue(S, NewFD)) {
10470     NewFD->setInvalidDecl();
10471     return true;
10472   }
10473 
10474   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10475                                        !OldFD->isMultiVersion(), NewMVType)) {
10476     NewFD->setInvalidDecl();
10477     return true;
10478   }
10479 
10480   // Permit forward declarations in the case where these two are compatible.
10481   if (!OldFD->isMultiVersion()) {
10482     OldFD->setIsMultiVersion();
10483     NewFD->setIsMultiVersion();
10484     Redeclaration = true;
10485     OldDecl = OldFD;
10486     return false;
10487   }
10488 
10489   NewFD->setIsMultiVersion();
10490   Redeclaration = false;
10491   MergeTypeWithPrevious = false;
10492   OldDecl = nullptr;
10493   Previous.clear();
10494   return false;
10495 }
10496 
10497 
10498 /// Check the validity of a mulitversion function declaration.
10499 /// Also sets the multiversion'ness' of the function itself.
10500 ///
10501 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10502 ///
10503 /// Returns true if there was an error, false otherwise.
10504 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10505                                       bool &Redeclaration, NamedDecl *&OldDecl,
10506                                       bool &MergeTypeWithPrevious,
10507                                       LookupResult &Previous) {
10508   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10509   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10510   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10511 
10512   // Mixing Multiversioning types is prohibited.
10513   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10514       (NewCPUDisp && NewCPUSpec)) {
10515     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10516     NewFD->setInvalidDecl();
10517     return true;
10518   }
10519 
10520   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10521 
10522   // Main isn't allowed to become a multiversion function, however it IS
10523   // permitted to have 'main' be marked with the 'target' optimization hint.
10524   if (NewFD->isMain()) {
10525     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10526         MVType == MultiVersionKind::CPUDispatch ||
10527         MVType == MultiVersionKind::CPUSpecific) {
10528       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10529       NewFD->setInvalidDecl();
10530       return true;
10531     }
10532     return false;
10533   }
10534 
10535   if (!OldDecl || !OldDecl->getAsFunction() ||
10536       OldDecl->getDeclContext()->getRedeclContext() !=
10537           NewFD->getDeclContext()->getRedeclContext()) {
10538     // If there's no previous declaration, AND this isn't attempting to cause
10539     // multiversioning, this isn't an error condition.
10540     if (MVType == MultiVersionKind::None)
10541       return false;
10542     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10543   }
10544 
10545   FunctionDecl *OldFD = OldDecl->getAsFunction();
10546 
10547   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10548     return false;
10549 
10550   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10551     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10552         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10553     NewFD->setInvalidDecl();
10554     return true;
10555   }
10556 
10557   // Handle the target potentially causes multiversioning case.
10558   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10559     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10560                                             Redeclaration, OldDecl,
10561                                             MergeTypeWithPrevious, Previous);
10562 
10563   // At this point, we have a multiversion function decl (in OldFD) AND an
10564   // appropriate attribute in the current function decl.  Resolve that these are
10565   // still compatible with previous declarations.
10566   return CheckMultiVersionAdditionalDecl(
10567       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10568       OldDecl, MergeTypeWithPrevious, Previous);
10569 }
10570 
10571 /// Perform semantic checking of a new function declaration.
10572 ///
10573 /// Performs semantic analysis of the new function declaration
10574 /// NewFD. This routine performs all semantic checking that does not
10575 /// require the actual declarator involved in the declaration, and is
10576 /// used both for the declaration of functions as they are parsed
10577 /// (called via ActOnDeclarator) and for the declaration of functions
10578 /// that have been instantiated via C++ template instantiation (called
10579 /// via InstantiateDecl).
10580 ///
10581 /// \param IsMemberSpecialization whether this new function declaration is
10582 /// a member specialization (that replaces any definition provided by the
10583 /// previous declaration).
10584 ///
10585 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10586 ///
10587 /// \returns true if the function declaration is a redeclaration.
10588 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10589                                     LookupResult &Previous,
10590                                     bool IsMemberSpecialization) {
10591   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10592          "Variably modified return types are not handled here");
10593 
10594   // Determine whether the type of this function should be merged with
10595   // a previous visible declaration. This never happens for functions in C++,
10596   // and always happens in C if the previous declaration was visible.
10597   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10598                                !Previous.isShadowed();
10599 
10600   bool Redeclaration = false;
10601   NamedDecl *OldDecl = nullptr;
10602   bool MayNeedOverloadableChecks = false;
10603 
10604   // Merge or overload the declaration with an existing declaration of
10605   // the same name, if appropriate.
10606   if (!Previous.empty()) {
10607     // Determine whether NewFD is an overload of PrevDecl or
10608     // a declaration that requires merging. If it's an overload,
10609     // there's no more work to do here; we'll just add the new
10610     // function to the scope.
10611     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10612       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10613       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10614         Redeclaration = true;
10615         OldDecl = Candidate;
10616       }
10617     } else {
10618       MayNeedOverloadableChecks = true;
10619       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10620                             /*NewIsUsingDecl*/ false)) {
10621       case Ovl_Match:
10622         Redeclaration = true;
10623         break;
10624 
10625       case Ovl_NonFunction:
10626         Redeclaration = true;
10627         break;
10628 
10629       case Ovl_Overload:
10630         Redeclaration = false;
10631         break;
10632       }
10633     }
10634   }
10635 
10636   // Check for a previous extern "C" declaration with this name.
10637   if (!Redeclaration &&
10638       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10639     if (!Previous.empty()) {
10640       // This is an extern "C" declaration with the same name as a previous
10641       // declaration, and thus redeclares that entity...
10642       Redeclaration = true;
10643       OldDecl = Previous.getFoundDecl();
10644       MergeTypeWithPrevious = false;
10645 
10646       // ... except in the presence of __attribute__((overloadable)).
10647       if (OldDecl->hasAttr<OverloadableAttr>() ||
10648           NewFD->hasAttr<OverloadableAttr>()) {
10649         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10650           MayNeedOverloadableChecks = true;
10651           Redeclaration = false;
10652           OldDecl = nullptr;
10653         }
10654       }
10655     }
10656   }
10657 
10658   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10659                                 MergeTypeWithPrevious, Previous))
10660     return Redeclaration;
10661 
10662   // C++11 [dcl.constexpr]p8:
10663   //   A constexpr specifier for a non-static member function that is not
10664   //   a constructor declares that member function to be const.
10665   //
10666   // This needs to be delayed until we know whether this is an out-of-line
10667   // definition of a static member function.
10668   //
10669   // This rule is not present in C++1y, so we produce a backwards
10670   // compatibility warning whenever it happens in C++11.
10671   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10672   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10673       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10674       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10675     CXXMethodDecl *OldMD = nullptr;
10676     if (OldDecl)
10677       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10678     if (!OldMD || !OldMD->isStatic()) {
10679       const FunctionProtoType *FPT =
10680         MD->getType()->castAs<FunctionProtoType>();
10681       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10682       EPI.TypeQuals.addConst();
10683       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10684                                           FPT->getParamTypes(), EPI));
10685 
10686       // Warn that we did this, if we're not performing template instantiation.
10687       // In that case, we'll have warned already when the template was defined.
10688       if (!inTemplateInstantiation()) {
10689         SourceLocation AddConstLoc;
10690         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10691                 .IgnoreParens().getAs<FunctionTypeLoc>())
10692           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10693 
10694         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10695           << FixItHint::CreateInsertion(AddConstLoc, " const");
10696       }
10697     }
10698   }
10699 
10700   if (Redeclaration) {
10701     // NewFD and OldDecl represent declarations that need to be
10702     // merged.
10703     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10704       NewFD->setInvalidDecl();
10705       return Redeclaration;
10706     }
10707 
10708     Previous.clear();
10709     Previous.addDecl(OldDecl);
10710 
10711     if (FunctionTemplateDecl *OldTemplateDecl =
10712             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10713       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10714       FunctionTemplateDecl *NewTemplateDecl
10715         = NewFD->getDescribedFunctionTemplate();
10716       assert(NewTemplateDecl && "Template/non-template mismatch");
10717 
10718       // The call to MergeFunctionDecl above may have created some state in
10719       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10720       // can add it as a redeclaration.
10721       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10722 
10723       NewFD->setPreviousDeclaration(OldFD);
10724       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10725       if (NewFD->isCXXClassMember()) {
10726         NewFD->setAccess(OldTemplateDecl->getAccess());
10727         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10728       }
10729 
10730       // If this is an explicit specialization of a member that is a function
10731       // template, mark it as a member specialization.
10732       if (IsMemberSpecialization &&
10733           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10734         NewTemplateDecl->setMemberSpecialization();
10735         assert(OldTemplateDecl->isMemberSpecialization());
10736         // Explicit specializations of a member template do not inherit deleted
10737         // status from the parent member template that they are specializing.
10738         if (OldFD->isDeleted()) {
10739           // FIXME: This assert will not hold in the presence of modules.
10740           assert(OldFD->getCanonicalDecl() == OldFD);
10741           // FIXME: We need an update record for this AST mutation.
10742           OldFD->setDeletedAsWritten(false);
10743         }
10744       }
10745 
10746     } else {
10747       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10748         auto *OldFD = cast<FunctionDecl>(OldDecl);
10749         // This needs to happen first so that 'inline' propagates.
10750         NewFD->setPreviousDeclaration(OldFD);
10751         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10752         if (NewFD->isCXXClassMember())
10753           NewFD->setAccess(OldFD->getAccess());
10754       }
10755     }
10756   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10757              !NewFD->getAttr<OverloadableAttr>()) {
10758     assert((Previous.empty() ||
10759             llvm::any_of(Previous,
10760                          [](const NamedDecl *ND) {
10761                            return ND->hasAttr<OverloadableAttr>();
10762                          })) &&
10763            "Non-redecls shouldn't happen without overloadable present");
10764 
10765     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10766       const auto *FD = dyn_cast<FunctionDecl>(ND);
10767       return FD && !FD->hasAttr<OverloadableAttr>();
10768     });
10769 
10770     if (OtherUnmarkedIter != Previous.end()) {
10771       Diag(NewFD->getLocation(),
10772            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10773       Diag((*OtherUnmarkedIter)->getLocation(),
10774            diag::note_attribute_overloadable_prev_overload)
10775           << false;
10776 
10777       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10778     }
10779   }
10780 
10781   // Semantic checking for this function declaration (in isolation).
10782 
10783   if (getLangOpts().CPlusPlus) {
10784     // C++-specific checks.
10785     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10786       CheckConstructor(Constructor);
10787     } else if (CXXDestructorDecl *Destructor =
10788                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10789       CXXRecordDecl *Record = Destructor->getParent();
10790       QualType ClassType = Context.getTypeDeclType(Record);
10791 
10792       // FIXME: Shouldn't we be able to perform this check even when the class
10793       // type is dependent? Both gcc and edg can handle that.
10794       if (!ClassType->isDependentType()) {
10795         DeclarationName Name
10796           = Context.DeclarationNames.getCXXDestructorName(
10797                                         Context.getCanonicalType(ClassType));
10798         if (NewFD->getDeclName() != Name) {
10799           Diag(NewFD->getLocation(), diag::err_destructor_name);
10800           NewFD->setInvalidDecl();
10801           return Redeclaration;
10802         }
10803       }
10804     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10805       if (auto *TD = Guide->getDescribedFunctionTemplate())
10806         CheckDeductionGuideTemplate(TD);
10807 
10808       // A deduction guide is not on the list of entities that can be
10809       // explicitly specialized.
10810       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10811         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10812             << /*explicit specialization*/ 1;
10813     }
10814 
10815     // Find any virtual functions that this function overrides.
10816     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10817       if (!Method->isFunctionTemplateSpecialization() &&
10818           !Method->getDescribedFunctionTemplate() &&
10819           Method->isCanonicalDecl()) {
10820         AddOverriddenMethods(Method->getParent(), Method);
10821       }
10822       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10823         // C++2a [class.virtual]p6
10824         // A virtual method shall not have a requires-clause.
10825         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10826              diag::err_constrained_virtual_method);
10827 
10828       if (Method->isStatic())
10829         checkThisInStaticMemberFunctionType(Method);
10830     }
10831 
10832     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10833       ActOnConversionDeclarator(Conversion);
10834 
10835     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10836     if (NewFD->isOverloadedOperator() &&
10837         CheckOverloadedOperatorDeclaration(NewFD)) {
10838       NewFD->setInvalidDecl();
10839       return Redeclaration;
10840     }
10841 
10842     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10843     if (NewFD->getLiteralIdentifier() &&
10844         CheckLiteralOperatorDeclaration(NewFD)) {
10845       NewFD->setInvalidDecl();
10846       return Redeclaration;
10847     }
10848 
10849     // In C++, check default arguments now that we have merged decls. Unless
10850     // the lexical context is the class, because in this case this is done
10851     // during delayed parsing anyway.
10852     if (!CurContext->isRecord())
10853       CheckCXXDefaultArguments(NewFD);
10854 
10855     // If this function declares a builtin function, check the type of this
10856     // declaration against the expected type for the builtin.
10857     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10858       ASTContext::GetBuiltinTypeError Error;
10859       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10860       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10861       // If the type of the builtin differs only in its exception
10862       // specification, that's OK.
10863       // FIXME: If the types do differ in this way, it would be better to
10864       // retain the 'noexcept' form of the type.
10865       if (!T.isNull() &&
10866           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10867                                                             NewFD->getType()))
10868         // The type of this function differs from the type of the builtin,
10869         // so forget about the builtin entirely.
10870         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10871     }
10872 
10873     // If this function is declared as being extern "C", then check to see if
10874     // the function returns a UDT (class, struct, or union type) that is not C
10875     // compatible, and if it does, warn the user.
10876     // But, issue any diagnostic on the first declaration only.
10877     if (Previous.empty() && NewFD->isExternC()) {
10878       QualType R = NewFD->getReturnType();
10879       if (R->isIncompleteType() && !R->isVoidType())
10880         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10881             << NewFD << R;
10882       else if (!R.isPODType(Context) && !R->isVoidType() &&
10883                !R->isObjCObjectPointerType())
10884         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10885     }
10886 
10887     // C++1z [dcl.fct]p6:
10888     //   [...] whether the function has a non-throwing exception-specification
10889     //   [is] part of the function type
10890     //
10891     // This results in an ABI break between C++14 and C++17 for functions whose
10892     // declared type includes an exception-specification in a parameter or
10893     // return type. (Exception specifications on the function itself are OK in
10894     // most cases, and exception specifications are not permitted in most other
10895     // contexts where they could make it into a mangling.)
10896     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10897       auto HasNoexcept = [&](QualType T) -> bool {
10898         // Strip off declarator chunks that could be between us and a function
10899         // type. We don't need to look far, exception specifications are very
10900         // restricted prior to C++17.
10901         if (auto *RT = T->getAs<ReferenceType>())
10902           T = RT->getPointeeType();
10903         else if (T->isAnyPointerType())
10904           T = T->getPointeeType();
10905         else if (auto *MPT = T->getAs<MemberPointerType>())
10906           T = MPT->getPointeeType();
10907         if (auto *FPT = T->getAs<FunctionProtoType>())
10908           if (FPT->isNothrow())
10909             return true;
10910         return false;
10911       };
10912 
10913       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10914       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10915       for (QualType T : FPT->param_types())
10916         AnyNoexcept |= HasNoexcept(T);
10917       if (AnyNoexcept)
10918         Diag(NewFD->getLocation(),
10919              diag::warn_cxx17_compat_exception_spec_in_signature)
10920             << NewFD;
10921     }
10922 
10923     if (!Redeclaration && LangOpts.CUDA)
10924       checkCUDATargetOverload(NewFD, Previous);
10925   }
10926   return Redeclaration;
10927 }
10928 
10929 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10930   // C++11 [basic.start.main]p3:
10931   //   A program that [...] declares main to be inline, static or
10932   //   constexpr is ill-formed.
10933   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10934   //   appear in a declaration of main.
10935   // static main is not an error under C99, but we should warn about it.
10936   // We accept _Noreturn main as an extension.
10937   if (FD->getStorageClass() == SC_Static)
10938     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10939          ? diag::err_static_main : diag::warn_static_main)
10940       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10941   if (FD->isInlineSpecified())
10942     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10943       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10944   if (DS.isNoreturnSpecified()) {
10945     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10946     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10947     Diag(NoreturnLoc, diag::ext_noreturn_main);
10948     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10949       << FixItHint::CreateRemoval(NoreturnRange);
10950   }
10951   if (FD->isConstexpr()) {
10952     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10953         << FD->isConsteval()
10954         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10955     FD->setConstexprKind(CSK_unspecified);
10956   }
10957 
10958   if (getLangOpts().OpenCL) {
10959     Diag(FD->getLocation(), diag::err_opencl_no_main)
10960         << FD->hasAttr<OpenCLKernelAttr>();
10961     FD->setInvalidDecl();
10962     return;
10963   }
10964 
10965   QualType T = FD->getType();
10966   assert(T->isFunctionType() && "function decl is not of function type");
10967   const FunctionType* FT = T->castAs<FunctionType>();
10968 
10969   // Set default calling convention for main()
10970   if (FT->getCallConv() != CC_C) {
10971     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10972     FD->setType(QualType(FT, 0));
10973     T = Context.getCanonicalType(FD->getType());
10974   }
10975 
10976   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10977     // In C with GNU extensions we allow main() to have non-integer return
10978     // type, but we should warn about the extension, and we disable the
10979     // implicit-return-zero rule.
10980 
10981     // GCC in C mode accepts qualified 'int'.
10982     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10983       FD->setHasImplicitReturnZero(true);
10984     else {
10985       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10986       SourceRange RTRange = FD->getReturnTypeSourceRange();
10987       if (RTRange.isValid())
10988         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10989             << FixItHint::CreateReplacement(RTRange, "int");
10990     }
10991   } else {
10992     // In C and C++, main magically returns 0 if you fall off the end;
10993     // set the flag which tells us that.
10994     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10995 
10996     // All the standards say that main() should return 'int'.
10997     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10998       FD->setHasImplicitReturnZero(true);
10999     else {
11000       // Otherwise, this is just a flat-out error.
11001       SourceRange RTRange = FD->getReturnTypeSourceRange();
11002       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11003           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11004                                 : FixItHint());
11005       FD->setInvalidDecl(true);
11006     }
11007   }
11008 
11009   // Treat protoless main() as nullary.
11010   if (isa<FunctionNoProtoType>(FT)) return;
11011 
11012   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11013   unsigned nparams = FTP->getNumParams();
11014   assert(FD->getNumParams() == nparams);
11015 
11016   bool HasExtraParameters = (nparams > 3);
11017 
11018   if (FTP->isVariadic()) {
11019     Diag(FD->getLocation(), diag::ext_variadic_main);
11020     // FIXME: if we had information about the location of the ellipsis, we
11021     // could add a FixIt hint to remove it as a parameter.
11022   }
11023 
11024   // Darwin passes an undocumented fourth argument of type char**.  If
11025   // other platforms start sprouting these, the logic below will start
11026   // getting shifty.
11027   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11028     HasExtraParameters = false;
11029 
11030   if (HasExtraParameters) {
11031     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11032     FD->setInvalidDecl(true);
11033     nparams = 3;
11034   }
11035 
11036   // FIXME: a lot of the following diagnostics would be improved
11037   // if we had some location information about types.
11038 
11039   QualType CharPP =
11040     Context.getPointerType(Context.getPointerType(Context.CharTy));
11041   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11042 
11043   for (unsigned i = 0; i < nparams; ++i) {
11044     QualType AT = FTP->getParamType(i);
11045 
11046     bool mismatch = true;
11047 
11048     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11049       mismatch = false;
11050     else if (Expected[i] == CharPP) {
11051       // As an extension, the following forms are okay:
11052       //   char const **
11053       //   char const * const *
11054       //   char * const *
11055 
11056       QualifierCollector qs;
11057       const PointerType* PT;
11058       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11059           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11060           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11061                               Context.CharTy)) {
11062         qs.removeConst();
11063         mismatch = !qs.empty();
11064       }
11065     }
11066 
11067     if (mismatch) {
11068       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11069       // TODO: suggest replacing given type with expected type
11070       FD->setInvalidDecl(true);
11071     }
11072   }
11073 
11074   if (nparams == 1 && !FD->isInvalidDecl()) {
11075     Diag(FD->getLocation(), diag::warn_main_one_arg);
11076   }
11077 
11078   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11079     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11080     FD->setInvalidDecl();
11081   }
11082 }
11083 
11084 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11085   QualType T = FD->getType();
11086   assert(T->isFunctionType() && "function decl is not of function type");
11087   const FunctionType *FT = T->castAs<FunctionType>();
11088 
11089   // Set an implicit return of 'zero' if the function can return some integral,
11090   // enumeration, pointer or nullptr type.
11091   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11092       FT->getReturnType()->isAnyPointerType() ||
11093       FT->getReturnType()->isNullPtrType())
11094     // DllMain is exempt because a return value of zero means it failed.
11095     if (FD->getName() != "DllMain")
11096       FD->setHasImplicitReturnZero(true);
11097 
11098   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11099     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11100     FD->setInvalidDecl();
11101   }
11102 }
11103 
11104 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11105   // FIXME: Need strict checking.  In C89, we need to check for
11106   // any assignment, increment, decrement, function-calls, or
11107   // commas outside of a sizeof.  In C99, it's the same list,
11108   // except that the aforementioned are allowed in unevaluated
11109   // expressions.  Everything else falls under the
11110   // "may accept other forms of constant expressions" exception.
11111   //
11112   // Regular C++ code will not end up here (exceptions: language extensions,
11113   // OpenCL C++ etc), so the constant expression rules there don't matter.
11114   if (Init->isValueDependent()) {
11115     assert(Init->containsErrors() &&
11116            "Dependent code should only occur in error-recovery path.");
11117     return true;
11118   }
11119   const Expr *Culprit;
11120   if (Init->isConstantInitializer(Context, false, &Culprit))
11121     return false;
11122   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11123     << Culprit->getSourceRange();
11124   return true;
11125 }
11126 
11127 namespace {
11128   // Visits an initialization expression to see if OrigDecl is evaluated in
11129   // its own initialization and throws a warning if it does.
11130   class SelfReferenceChecker
11131       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11132     Sema &S;
11133     Decl *OrigDecl;
11134     bool isRecordType;
11135     bool isPODType;
11136     bool isReferenceType;
11137 
11138     bool isInitList;
11139     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11140 
11141   public:
11142     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11143 
11144     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11145                                                     S(S), OrigDecl(OrigDecl) {
11146       isPODType = false;
11147       isRecordType = false;
11148       isReferenceType = false;
11149       isInitList = false;
11150       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11151         isPODType = VD->getType().isPODType(S.Context);
11152         isRecordType = VD->getType()->isRecordType();
11153         isReferenceType = VD->getType()->isReferenceType();
11154       }
11155     }
11156 
11157     // For most expressions, just call the visitor.  For initializer lists,
11158     // track the index of the field being initialized since fields are
11159     // initialized in order allowing use of previously initialized fields.
11160     void CheckExpr(Expr *E) {
11161       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11162       if (!InitList) {
11163         Visit(E);
11164         return;
11165       }
11166 
11167       // Track and increment the index here.
11168       isInitList = true;
11169       InitFieldIndex.push_back(0);
11170       for (auto Child : InitList->children()) {
11171         CheckExpr(cast<Expr>(Child));
11172         ++InitFieldIndex.back();
11173       }
11174       InitFieldIndex.pop_back();
11175     }
11176 
11177     // Returns true if MemberExpr is checked and no further checking is needed.
11178     // Returns false if additional checking is required.
11179     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11180       llvm::SmallVector<FieldDecl*, 4> Fields;
11181       Expr *Base = E;
11182       bool ReferenceField = false;
11183 
11184       // Get the field members used.
11185       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11186         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11187         if (!FD)
11188           return false;
11189         Fields.push_back(FD);
11190         if (FD->getType()->isReferenceType())
11191           ReferenceField = true;
11192         Base = ME->getBase()->IgnoreParenImpCasts();
11193       }
11194 
11195       // Keep checking only if the base Decl is the same.
11196       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11197       if (!DRE || DRE->getDecl() != OrigDecl)
11198         return false;
11199 
11200       // A reference field can be bound to an unininitialized field.
11201       if (CheckReference && !ReferenceField)
11202         return true;
11203 
11204       // Convert FieldDecls to their index number.
11205       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11206       for (const FieldDecl *I : llvm::reverse(Fields))
11207         UsedFieldIndex.push_back(I->getFieldIndex());
11208 
11209       // See if a warning is needed by checking the first difference in index
11210       // numbers.  If field being used has index less than the field being
11211       // initialized, then the use is safe.
11212       for (auto UsedIter = UsedFieldIndex.begin(),
11213                 UsedEnd = UsedFieldIndex.end(),
11214                 OrigIter = InitFieldIndex.begin(),
11215                 OrigEnd = InitFieldIndex.end();
11216            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11217         if (*UsedIter < *OrigIter)
11218           return true;
11219         if (*UsedIter > *OrigIter)
11220           break;
11221       }
11222 
11223       // TODO: Add a different warning which will print the field names.
11224       HandleDeclRefExpr(DRE);
11225       return true;
11226     }
11227 
11228     // For most expressions, the cast is directly above the DeclRefExpr.
11229     // For conditional operators, the cast can be outside the conditional
11230     // operator if both expressions are DeclRefExpr's.
11231     void HandleValue(Expr *E) {
11232       E = E->IgnoreParens();
11233       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11234         HandleDeclRefExpr(DRE);
11235         return;
11236       }
11237 
11238       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11239         Visit(CO->getCond());
11240         HandleValue(CO->getTrueExpr());
11241         HandleValue(CO->getFalseExpr());
11242         return;
11243       }
11244 
11245       if (BinaryConditionalOperator *BCO =
11246               dyn_cast<BinaryConditionalOperator>(E)) {
11247         Visit(BCO->getCond());
11248         HandleValue(BCO->getFalseExpr());
11249         return;
11250       }
11251 
11252       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11253         HandleValue(OVE->getSourceExpr());
11254         return;
11255       }
11256 
11257       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11258         if (BO->getOpcode() == BO_Comma) {
11259           Visit(BO->getLHS());
11260           HandleValue(BO->getRHS());
11261           return;
11262         }
11263       }
11264 
11265       if (isa<MemberExpr>(E)) {
11266         if (isInitList) {
11267           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11268                                       false /*CheckReference*/))
11269             return;
11270         }
11271 
11272         Expr *Base = E->IgnoreParenImpCasts();
11273         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11274           // Check for static member variables and don't warn on them.
11275           if (!isa<FieldDecl>(ME->getMemberDecl()))
11276             return;
11277           Base = ME->getBase()->IgnoreParenImpCasts();
11278         }
11279         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11280           HandleDeclRefExpr(DRE);
11281         return;
11282       }
11283 
11284       Visit(E);
11285     }
11286 
11287     // Reference types not handled in HandleValue are handled here since all
11288     // uses of references are bad, not just r-value uses.
11289     void VisitDeclRefExpr(DeclRefExpr *E) {
11290       if (isReferenceType)
11291         HandleDeclRefExpr(E);
11292     }
11293 
11294     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11295       if (E->getCastKind() == CK_LValueToRValue) {
11296         HandleValue(E->getSubExpr());
11297         return;
11298       }
11299 
11300       Inherited::VisitImplicitCastExpr(E);
11301     }
11302 
11303     void VisitMemberExpr(MemberExpr *E) {
11304       if (isInitList) {
11305         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11306           return;
11307       }
11308 
11309       // Don't warn on arrays since they can be treated as pointers.
11310       if (E->getType()->canDecayToPointerType()) return;
11311 
11312       // Warn when a non-static method call is followed by non-static member
11313       // field accesses, which is followed by a DeclRefExpr.
11314       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11315       bool Warn = (MD && !MD->isStatic());
11316       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11317       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11318         if (!isa<FieldDecl>(ME->getMemberDecl()))
11319           Warn = false;
11320         Base = ME->getBase()->IgnoreParenImpCasts();
11321       }
11322 
11323       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11324         if (Warn)
11325           HandleDeclRefExpr(DRE);
11326         return;
11327       }
11328 
11329       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11330       // Visit that expression.
11331       Visit(Base);
11332     }
11333 
11334     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11335       Expr *Callee = E->getCallee();
11336 
11337       if (isa<UnresolvedLookupExpr>(Callee))
11338         return Inherited::VisitCXXOperatorCallExpr(E);
11339 
11340       Visit(Callee);
11341       for (auto Arg: E->arguments())
11342         HandleValue(Arg->IgnoreParenImpCasts());
11343     }
11344 
11345     void VisitUnaryOperator(UnaryOperator *E) {
11346       // For POD record types, addresses of its own members are well-defined.
11347       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11348           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11349         if (!isPODType)
11350           HandleValue(E->getSubExpr());
11351         return;
11352       }
11353 
11354       if (E->isIncrementDecrementOp()) {
11355         HandleValue(E->getSubExpr());
11356         return;
11357       }
11358 
11359       Inherited::VisitUnaryOperator(E);
11360     }
11361 
11362     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11363 
11364     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11365       if (E->getConstructor()->isCopyConstructor()) {
11366         Expr *ArgExpr = E->getArg(0);
11367         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11368           if (ILE->getNumInits() == 1)
11369             ArgExpr = ILE->getInit(0);
11370         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11371           if (ICE->getCastKind() == CK_NoOp)
11372             ArgExpr = ICE->getSubExpr();
11373         HandleValue(ArgExpr);
11374         return;
11375       }
11376       Inherited::VisitCXXConstructExpr(E);
11377     }
11378 
11379     void VisitCallExpr(CallExpr *E) {
11380       // Treat std::move as a use.
11381       if (E->isCallToStdMove()) {
11382         HandleValue(E->getArg(0));
11383         return;
11384       }
11385 
11386       Inherited::VisitCallExpr(E);
11387     }
11388 
11389     void VisitBinaryOperator(BinaryOperator *E) {
11390       if (E->isCompoundAssignmentOp()) {
11391         HandleValue(E->getLHS());
11392         Visit(E->getRHS());
11393         return;
11394       }
11395 
11396       Inherited::VisitBinaryOperator(E);
11397     }
11398 
11399     // A custom visitor for BinaryConditionalOperator is needed because the
11400     // regular visitor would check the condition and true expression separately
11401     // but both point to the same place giving duplicate diagnostics.
11402     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11403       Visit(E->getCond());
11404       Visit(E->getFalseExpr());
11405     }
11406 
11407     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11408       Decl* ReferenceDecl = DRE->getDecl();
11409       if (OrigDecl != ReferenceDecl) return;
11410       unsigned diag;
11411       if (isReferenceType) {
11412         diag = diag::warn_uninit_self_reference_in_reference_init;
11413       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11414         diag = diag::warn_static_self_reference_in_init;
11415       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11416                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11417                  DRE->getDecl()->getType()->isRecordType()) {
11418         diag = diag::warn_uninit_self_reference_in_init;
11419       } else {
11420         // Local variables will be handled by the CFG analysis.
11421         return;
11422       }
11423 
11424       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11425                             S.PDiag(diag)
11426                                 << DRE->getDecl() << OrigDecl->getLocation()
11427                                 << DRE->getSourceRange());
11428     }
11429   };
11430 
11431   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11432   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11433                                  bool DirectInit) {
11434     // Parameters arguments are occassionially constructed with itself,
11435     // for instance, in recursive functions.  Skip them.
11436     if (isa<ParmVarDecl>(OrigDecl))
11437       return;
11438 
11439     E = E->IgnoreParens();
11440 
11441     // Skip checking T a = a where T is not a record or reference type.
11442     // Doing so is a way to silence uninitialized warnings.
11443     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11444       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11445         if (ICE->getCastKind() == CK_LValueToRValue)
11446           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11447             if (DRE->getDecl() == OrigDecl)
11448               return;
11449 
11450     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11451   }
11452 } // end anonymous namespace
11453 
11454 namespace {
11455   // Simple wrapper to add the name of a variable or (if no variable is
11456   // available) a DeclarationName into a diagnostic.
11457   struct VarDeclOrName {
11458     VarDecl *VDecl;
11459     DeclarationName Name;
11460 
11461     friend const Sema::SemaDiagnosticBuilder &
11462     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11463       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11464     }
11465   };
11466 } // end anonymous namespace
11467 
11468 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11469                                             DeclarationName Name, QualType Type,
11470                                             TypeSourceInfo *TSI,
11471                                             SourceRange Range, bool DirectInit,
11472                                             Expr *Init) {
11473   bool IsInitCapture = !VDecl;
11474   assert((!VDecl || !VDecl->isInitCapture()) &&
11475          "init captures are expected to be deduced prior to initialization");
11476 
11477   VarDeclOrName VN{VDecl, Name};
11478 
11479   DeducedType *Deduced = Type->getContainedDeducedType();
11480   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11481 
11482   // C++11 [dcl.spec.auto]p3
11483   if (!Init) {
11484     assert(VDecl && "no init for init capture deduction?");
11485 
11486     // Except for class argument deduction, and then for an initializing
11487     // declaration only, i.e. no static at class scope or extern.
11488     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11489         VDecl->hasExternalStorage() ||
11490         VDecl->isStaticDataMember()) {
11491       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11492         << VDecl->getDeclName() << Type;
11493       return QualType();
11494     }
11495   }
11496 
11497   ArrayRef<Expr*> DeduceInits;
11498   if (Init)
11499     DeduceInits = Init;
11500 
11501   if (DirectInit) {
11502     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11503       DeduceInits = PL->exprs();
11504   }
11505 
11506   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11507     assert(VDecl && "non-auto type for init capture deduction?");
11508     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11509     InitializationKind Kind = InitializationKind::CreateForInit(
11510         VDecl->getLocation(), DirectInit, Init);
11511     // FIXME: Initialization should not be taking a mutable list of inits.
11512     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11513     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11514                                                        InitsCopy);
11515   }
11516 
11517   if (DirectInit) {
11518     if (auto *IL = dyn_cast<InitListExpr>(Init))
11519       DeduceInits = IL->inits();
11520   }
11521 
11522   // Deduction only works if we have exactly one source expression.
11523   if (DeduceInits.empty()) {
11524     // It isn't possible to write this directly, but it is possible to
11525     // end up in this situation with "auto x(some_pack...);"
11526     Diag(Init->getBeginLoc(), IsInitCapture
11527                                   ? diag::err_init_capture_no_expression
11528                                   : diag::err_auto_var_init_no_expression)
11529         << VN << Type << Range;
11530     return QualType();
11531   }
11532 
11533   if (DeduceInits.size() > 1) {
11534     Diag(DeduceInits[1]->getBeginLoc(),
11535          IsInitCapture ? diag::err_init_capture_multiple_expressions
11536                        : diag::err_auto_var_init_multiple_expressions)
11537         << VN << Type << Range;
11538     return QualType();
11539   }
11540 
11541   Expr *DeduceInit = DeduceInits[0];
11542   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11543     Diag(Init->getBeginLoc(), IsInitCapture
11544                                   ? diag::err_init_capture_paren_braces
11545                                   : diag::err_auto_var_init_paren_braces)
11546         << isa<InitListExpr>(Init) << VN << Type << Range;
11547     return QualType();
11548   }
11549 
11550   // Expressions default to 'id' when we're in a debugger.
11551   bool DefaultedAnyToId = false;
11552   if (getLangOpts().DebuggerCastResultToId &&
11553       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11554     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11555     if (Result.isInvalid()) {
11556       return QualType();
11557     }
11558     Init = Result.get();
11559     DefaultedAnyToId = true;
11560   }
11561 
11562   // C++ [dcl.decomp]p1:
11563   //   If the assignment-expression [...] has array type A and no ref-qualifier
11564   //   is present, e has type cv A
11565   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11566       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11567       DeduceInit->getType()->isConstantArrayType())
11568     return Context.getQualifiedType(DeduceInit->getType(),
11569                                     Type.getQualifiers());
11570 
11571   QualType DeducedType;
11572   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11573     if (!IsInitCapture)
11574       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11575     else if (isa<InitListExpr>(Init))
11576       Diag(Range.getBegin(),
11577            diag::err_init_capture_deduction_failure_from_init_list)
11578           << VN
11579           << (DeduceInit->getType().isNull() ? TSI->getType()
11580                                              : DeduceInit->getType())
11581           << DeduceInit->getSourceRange();
11582     else
11583       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11584           << VN << TSI->getType()
11585           << (DeduceInit->getType().isNull() ? TSI->getType()
11586                                              : DeduceInit->getType())
11587           << DeduceInit->getSourceRange();
11588   }
11589 
11590   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11591   // 'id' instead of a specific object type prevents most of our usual
11592   // checks.
11593   // We only want to warn outside of template instantiations, though:
11594   // inside a template, the 'id' could have come from a parameter.
11595   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11596       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11597     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11598     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11599   }
11600 
11601   return DeducedType;
11602 }
11603 
11604 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11605                                          Expr *Init) {
11606   assert(!Init || !Init->containsErrors());
11607   QualType DeducedType = deduceVarTypeFromInitializer(
11608       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11609       VDecl->getSourceRange(), DirectInit, Init);
11610   if (DeducedType.isNull()) {
11611     VDecl->setInvalidDecl();
11612     return true;
11613   }
11614 
11615   VDecl->setType(DeducedType);
11616   assert(VDecl->isLinkageValid());
11617 
11618   // In ARC, infer lifetime.
11619   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11620     VDecl->setInvalidDecl();
11621 
11622   if (getLangOpts().OpenCL)
11623     deduceOpenCLAddressSpace(VDecl);
11624 
11625   // If this is a redeclaration, check that the type we just deduced matches
11626   // the previously declared type.
11627   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11628     // We never need to merge the type, because we cannot form an incomplete
11629     // array of auto, nor deduce such a type.
11630     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11631   }
11632 
11633   // Check the deduced type is valid for a variable declaration.
11634   CheckVariableDeclarationType(VDecl);
11635   return VDecl->isInvalidDecl();
11636 }
11637 
11638 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11639                                               SourceLocation Loc) {
11640   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11641     Init = EWC->getSubExpr();
11642 
11643   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11644     Init = CE->getSubExpr();
11645 
11646   QualType InitType = Init->getType();
11647   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11648           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11649          "shouldn't be called if type doesn't have a non-trivial C struct");
11650   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11651     for (auto I : ILE->inits()) {
11652       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11653           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11654         continue;
11655       SourceLocation SL = I->getExprLoc();
11656       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11657     }
11658     return;
11659   }
11660 
11661   if (isa<ImplicitValueInitExpr>(Init)) {
11662     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11663       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11664                             NTCUK_Init);
11665   } else {
11666     // Assume all other explicit initializers involving copying some existing
11667     // object.
11668     // TODO: ignore any explicit initializers where we can guarantee
11669     // copy-elision.
11670     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11671       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11672   }
11673 }
11674 
11675 namespace {
11676 
11677 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11678   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11679   // in the source code or implicitly by the compiler if it is in a union
11680   // defined in a system header and has non-trivial ObjC ownership
11681   // qualifications. We don't want those fields to participate in determining
11682   // whether the containing union is non-trivial.
11683   return FD->hasAttr<UnavailableAttr>();
11684 }
11685 
11686 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11687     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11688                                     void> {
11689   using Super =
11690       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11691                                     void>;
11692 
11693   DiagNonTrivalCUnionDefaultInitializeVisitor(
11694       QualType OrigTy, SourceLocation OrigLoc,
11695       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11696       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11697 
11698   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11699                      const FieldDecl *FD, bool InNonTrivialUnion) {
11700     if (const auto *AT = S.Context.getAsArrayType(QT))
11701       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11702                                      InNonTrivialUnion);
11703     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11704   }
11705 
11706   void visitARCStrong(QualType QT, const FieldDecl *FD,
11707                       bool InNonTrivialUnion) {
11708     if (InNonTrivialUnion)
11709       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11710           << 1 << 0 << QT << FD->getName();
11711   }
11712 
11713   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11714     if (InNonTrivialUnion)
11715       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11716           << 1 << 0 << QT << FD->getName();
11717   }
11718 
11719   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11720     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11721     if (RD->isUnion()) {
11722       if (OrigLoc.isValid()) {
11723         bool IsUnion = false;
11724         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11725           IsUnion = OrigRD->isUnion();
11726         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11727             << 0 << OrigTy << IsUnion << UseContext;
11728         // Reset OrigLoc so that this diagnostic is emitted only once.
11729         OrigLoc = SourceLocation();
11730       }
11731       InNonTrivialUnion = true;
11732     }
11733 
11734     if (InNonTrivialUnion)
11735       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11736           << 0 << 0 << QT.getUnqualifiedType() << "";
11737 
11738     for (const FieldDecl *FD : RD->fields())
11739       if (!shouldIgnoreForRecordTriviality(FD))
11740         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11741   }
11742 
11743   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11744 
11745   // The non-trivial C union type or the struct/union type that contains a
11746   // non-trivial C union.
11747   QualType OrigTy;
11748   SourceLocation OrigLoc;
11749   Sema::NonTrivialCUnionContext UseContext;
11750   Sema &S;
11751 };
11752 
11753 struct DiagNonTrivalCUnionDestructedTypeVisitor
11754     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11755   using Super =
11756       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11757 
11758   DiagNonTrivalCUnionDestructedTypeVisitor(
11759       QualType OrigTy, SourceLocation OrigLoc,
11760       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11761       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11762 
11763   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11764                      const FieldDecl *FD, bool InNonTrivialUnion) {
11765     if (const auto *AT = S.Context.getAsArrayType(QT))
11766       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11767                                      InNonTrivialUnion);
11768     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11769   }
11770 
11771   void visitARCStrong(QualType QT, const FieldDecl *FD,
11772                       bool InNonTrivialUnion) {
11773     if (InNonTrivialUnion)
11774       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11775           << 1 << 1 << QT << FD->getName();
11776   }
11777 
11778   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11779     if (InNonTrivialUnion)
11780       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11781           << 1 << 1 << QT << FD->getName();
11782   }
11783 
11784   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11785     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11786     if (RD->isUnion()) {
11787       if (OrigLoc.isValid()) {
11788         bool IsUnion = false;
11789         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11790           IsUnion = OrigRD->isUnion();
11791         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11792             << 1 << OrigTy << IsUnion << UseContext;
11793         // Reset OrigLoc so that this diagnostic is emitted only once.
11794         OrigLoc = SourceLocation();
11795       }
11796       InNonTrivialUnion = true;
11797     }
11798 
11799     if (InNonTrivialUnion)
11800       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11801           << 0 << 1 << QT.getUnqualifiedType() << "";
11802 
11803     for (const FieldDecl *FD : RD->fields())
11804       if (!shouldIgnoreForRecordTriviality(FD))
11805         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11806   }
11807 
11808   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11809   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11810                           bool InNonTrivialUnion) {}
11811 
11812   // The non-trivial C union type or the struct/union type that contains a
11813   // non-trivial C union.
11814   QualType OrigTy;
11815   SourceLocation OrigLoc;
11816   Sema::NonTrivialCUnionContext UseContext;
11817   Sema &S;
11818 };
11819 
11820 struct DiagNonTrivalCUnionCopyVisitor
11821     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11822   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11823 
11824   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11825                                  Sema::NonTrivialCUnionContext UseContext,
11826                                  Sema &S)
11827       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11828 
11829   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11830                      const FieldDecl *FD, bool InNonTrivialUnion) {
11831     if (const auto *AT = S.Context.getAsArrayType(QT))
11832       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11833                                      InNonTrivialUnion);
11834     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11835   }
11836 
11837   void visitARCStrong(QualType QT, const FieldDecl *FD,
11838                       bool InNonTrivialUnion) {
11839     if (InNonTrivialUnion)
11840       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11841           << 1 << 2 << QT << FD->getName();
11842   }
11843 
11844   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11845     if (InNonTrivialUnion)
11846       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11847           << 1 << 2 << QT << FD->getName();
11848   }
11849 
11850   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11851     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11852     if (RD->isUnion()) {
11853       if (OrigLoc.isValid()) {
11854         bool IsUnion = false;
11855         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11856           IsUnion = OrigRD->isUnion();
11857         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11858             << 2 << OrigTy << IsUnion << UseContext;
11859         // Reset OrigLoc so that this diagnostic is emitted only once.
11860         OrigLoc = SourceLocation();
11861       }
11862       InNonTrivialUnion = true;
11863     }
11864 
11865     if (InNonTrivialUnion)
11866       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11867           << 0 << 2 << QT.getUnqualifiedType() << "";
11868 
11869     for (const FieldDecl *FD : RD->fields())
11870       if (!shouldIgnoreForRecordTriviality(FD))
11871         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11872   }
11873 
11874   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11875                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11876   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11877   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11878                             bool InNonTrivialUnion) {}
11879 
11880   // The non-trivial C union type or the struct/union type that contains a
11881   // non-trivial C union.
11882   QualType OrigTy;
11883   SourceLocation OrigLoc;
11884   Sema::NonTrivialCUnionContext UseContext;
11885   Sema &S;
11886 };
11887 
11888 } // namespace
11889 
11890 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11891                                  NonTrivialCUnionContext UseContext,
11892                                  unsigned NonTrivialKind) {
11893   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11894           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11895           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11896          "shouldn't be called if type doesn't have a non-trivial C union");
11897 
11898   if ((NonTrivialKind & NTCUK_Init) &&
11899       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11900     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11901         .visit(QT, nullptr, false);
11902   if ((NonTrivialKind & NTCUK_Destruct) &&
11903       QT.hasNonTrivialToPrimitiveDestructCUnion())
11904     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11905         .visit(QT, nullptr, false);
11906   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11907     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11908         .visit(QT, nullptr, false);
11909 }
11910 
11911 /// AddInitializerToDecl - Adds the initializer Init to the
11912 /// declaration dcl. If DirectInit is true, this is C++ direct
11913 /// initialization rather than copy initialization.
11914 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11915   // If there is no declaration, there was an error parsing it.  Just ignore
11916   // the initializer.
11917   if (!RealDecl || RealDecl->isInvalidDecl()) {
11918     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11919     return;
11920   }
11921 
11922   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11923     // Pure-specifiers are handled in ActOnPureSpecifier.
11924     Diag(Method->getLocation(), diag::err_member_function_initialization)
11925       << Method->getDeclName() << Init->getSourceRange();
11926     Method->setInvalidDecl();
11927     return;
11928   }
11929 
11930   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11931   if (!VDecl) {
11932     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11933     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11934     RealDecl->setInvalidDecl();
11935     return;
11936   }
11937 
11938   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11939   if (VDecl->getType()->isUndeducedType()) {
11940     // Attempt typo correction early so that the type of the init expression can
11941     // be deduced based on the chosen correction if the original init contains a
11942     // TypoExpr.
11943     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11944     if (!Res.isUsable()) {
11945       // There are unresolved typos in Init, just drop them.
11946       // FIXME: improve the recovery strategy to preserve the Init.
11947       RealDecl->setInvalidDecl();
11948       return;
11949     }
11950     if (Res.get()->containsErrors()) {
11951       // Invalidate the decl as we don't know the type for recovery-expr yet.
11952       RealDecl->setInvalidDecl();
11953       VDecl->setInit(Res.get());
11954       return;
11955     }
11956     Init = Res.get();
11957 
11958     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11959       return;
11960   }
11961 
11962   // dllimport cannot be used on variable definitions.
11963   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11964     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11965     VDecl->setInvalidDecl();
11966     return;
11967   }
11968 
11969   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11970     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11971     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11972     VDecl->setInvalidDecl();
11973     return;
11974   }
11975 
11976   if (!VDecl->getType()->isDependentType()) {
11977     // A definition must end up with a complete type, which means it must be
11978     // complete with the restriction that an array type might be completed by
11979     // the initializer; note that later code assumes this restriction.
11980     QualType BaseDeclType = VDecl->getType();
11981     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11982       BaseDeclType = Array->getElementType();
11983     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11984                             diag::err_typecheck_decl_incomplete_type)) {
11985       RealDecl->setInvalidDecl();
11986       return;
11987     }
11988 
11989     // The variable can not have an abstract class type.
11990     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11991                                diag::err_abstract_type_in_decl,
11992                                AbstractVariableType))
11993       VDecl->setInvalidDecl();
11994   }
11995 
11996   // If adding the initializer will turn this declaration into a definition,
11997   // and we already have a definition for this variable, diagnose or otherwise
11998   // handle the situation.
11999   VarDecl *Def;
12000   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12001       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12002       !VDecl->isThisDeclarationADemotedDefinition() &&
12003       checkVarDeclRedefinition(Def, VDecl))
12004     return;
12005 
12006   if (getLangOpts().CPlusPlus) {
12007     // C++ [class.static.data]p4
12008     //   If a static data member is of const integral or const
12009     //   enumeration type, its declaration in the class definition can
12010     //   specify a constant-initializer which shall be an integral
12011     //   constant expression (5.19). In that case, the member can appear
12012     //   in integral constant expressions. The member shall still be
12013     //   defined in a namespace scope if it is used in the program and the
12014     //   namespace scope definition shall not contain an initializer.
12015     //
12016     // We already performed a redefinition check above, but for static
12017     // data members we also need to check whether there was an in-class
12018     // declaration with an initializer.
12019     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12020       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12021           << VDecl->getDeclName();
12022       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12023            diag::note_previous_initializer)
12024           << 0;
12025       return;
12026     }
12027 
12028     if (VDecl->hasLocalStorage())
12029       setFunctionHasBranchProtectedScope();
12030 
12031     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12032       VDecl->setInvalidDecl();
12033       return;
12034     }
12035   }
12036 
12037   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12038   // a kernel function cannot be initialized."
12039   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12040     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12041     VDecl->setInvalidDecl();
12042     return;
12043   }
12044 
12045   // The LoaderUninitialized attribute acts as a definition (of undef).
12046   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12047     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12048     VDecl->setInvalidDecl();
12049     return;
12050   }
12051 
12052   // Get the decls type and save a reference for later, since
12053   // CheckInitializerTypes may change it.
12054   QualType DclT = VDecl->getType(), SavT = DclT;
12055 
12056   // Expressions default to 'id' when we're in a debugger
12057   // and we are assigning it to a variable of Objective-C pointer type.
12058   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12059       Init->getType() == Context.UnknownAnyTy) {
12060     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12061     if (Result.isInvalid()) {
12062       VDecl->setInvalidDecl();
12063       return;
12064     }
12065     Init = Result.get();
12066   }
12067 
12068   // Perform the initialization.
12069   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12070   if (!VDecl->isInvalidDecl()) {
12071     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12072     InitializationKind Kind = InitializationKind::CreateForInit(
12073         VDecl->getLocation(), DirectInit, Init);
12074 
12075     MultiExprArg Args = Init;
12076     if (CXXDirectInit)
12077       Args = MultiExprArg(CXXDirectInit->getExprs(),
12078                           CXXDirectInit->getNumExprs());
12079 
12080     // Try to correct any TypoExprs in the initialization arguments.
12081     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12082       ExprResult Res = CorrectDelayedTyposInExpr(
12083           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12084           [this, Entity, Kind](Expr *E) {
12085             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12086             return Init.Failed() ? ExprError() : E;
12087           });
12088       if (Res.isInvalid()) {
12089         VDecl->setInvalidDecl();
12090       } else if (Res.get() != Args[Idx]) {
12091         Args[Idx] = Res.get();
12092       }
12093     }
12094     if (VDecl->isInvalidDecl())
12095       return;
12096 
12097     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12098                                    /*TopLevelOfInitList=*/false,
12099                                    /*TreatUnavailableAsInvalid=*/false);
12100     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12101     if (Result.isInvalid()) {
12102       // If the provied initializer fails to initialize the var decl,
12103       // we attach a recovery expr for better recovery.
12104       auto RecoveryExpr =
12105           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12106       if (RecoveryExpr.get())
12107         VDecl->setInit(RecoveryExpr.get());
12108       return;
12109     }
12110 
12111     Init = Result.getAs<Expr>();
12112   }
12113 
12114   // Check for self-references within variable initializers.
12115   // Variables declared within a function/method body (except for references)
12116   // are handled by a dataflow analysis.
12117   // This is undefined behavior in C++, but valid in C.
12118   if (getLangOpts().CPlusPlus) {
12119     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12120         VDecl->getType()->isReferenceType()) {
12121       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12122     }
12123   }
12124 
12125   // If the type changed, it means we had an incomplete type that was
12126   // completed by the initializer. For example:
12127   //   int ary[] = { 1, 3, 5 };
12128   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12129   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12130     VDecl->setType(DclT);
12131 
12132   if (!VDecl->isInvalidDecl()) {
12133     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12134 
12135     if (VDecl->hasAttr<BlocksAttr>())
12136       checkRetainCycles(VDecl, Init);
12137 
12138     // It is safe to assign a weak reference into a strong variable.
12139     // Although this code can still have problems:
12140     //   id x = self.weakProp;
12141     //   id y = self.weakProp;
12142     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12143     // paths through the function. This should be revisited if
12144     // -Wrepeated-use-of-weak is made flow-sensitive.
12145     if (FunctionScopeInfo *FSI = getCurFunction())
12146       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12147            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12148           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12149                            Init->getBeginLoc()))
12150         FSI->markSafeWeakUse(Init);
12151   }
12152 
12153   // The initialization is usually a full-expression.
12154   //
12155   // FIXME: If this is a braced initialization of an aggregate, it is not
12156   // an expression, and each individual field initializer is a separate
12157   // full-expression. For instance, in:
12158   //
12159   //   struct Temp { ~Temp(); };
12160   //   struct S { S(Temp); };
12161   //   struct T { S a, b; } t = { Temp(), Temp() }
12162   //
12163   // we should destroy the first Temp before constructing the second.
12164   ExprResult Result =
12165       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12166                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12167   if (Result.isInvalid()) {
12168     VDecl->setInvalidDecl();
12169     return;
12170   }
12171   Init = Result.get();
12172 
12173   // Attach the initializer to the decl.
12174   VDecl->setInit(Init);
12175 
12176   if (VDecl->isLocalVarDecl()) {
12177     // Don't check the initializer if the declaration is malformed.
12178     if (VDecl->isInvalidDecl()) {
12179       // do nothing
12180 
12181     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12182     // This is true even in C++ for OpenCL.
12183     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12184       CheckForConstantInitializer(Init, DclT);
12185 
12186     // Otherwise, C++ does not restrict the initializer.
12187     } else if (getLangOpts().CPlusPlus) {
12188       // do nothing
12189 
12190     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12191     // static storage duration shall be constant expressions or string literals.
12192     } else if (VDecl->getStorageClass() == SC_Static) {
12193       CheckForConstantInitializer(Init, DclT);
12194 
12195     // C89 is stricter than C99 for aggregate initializers.
12196     // C89 6.5.7p3: All the expressions [...] in an initializer list
12197     // for an object that has aggregate or union type shall be
12198     // constant expressions.
12199     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12200                isa<InitListExpr>(Init)) {
12201       const Expr *Culprit;
12202       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12203         Diag(Culprit->getExprLoc(),
12204              diag::ext_aggregate_init_not_constant)
12205           << Culprit->getSourceRange();
12206       }
12207     }
12208 
12209     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12210       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12211         if (VDecl->hasLocalStorage())
12212           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12213   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12214              VDecl->getLexicalDeclContext()->isRecord()) {
12215     // This is an in-class initialization for a static data member, e.g.,
12216     //
12217     // struct S {
12218     //   static const int value = 17;
12219     // };
12220 
12221     // C++ [class.mem]p4:
12222     //   A member-declarator can contain a constant-initializer only
12223     //   if it declares a static member (9.4) of const integral or
12224     //   const enumeration type, see 9.4.2.
12225     //
12226     // C++11 [class.static.data]p3:
12227     //   If a non-volatile non-inline const static data member is of integral
12228     //   or enumeration type, its declaration in the class definition can
12229     //   specify a brace-or-equal-initializer in which every initializer-clause
12230     //   that is an assignment-expression is a constant expression. A static
12231     //   data member of literal type can be declared in the class definition
12232     //   with the constexpr specifier; if so, its declaration shall specify a
12233     //   brace-or-equal-initializer in which every initializer-clause that is
12234     //   an assignment-expression is a constant expression.
12235 
12236     // Do nothing on dependent types.
12237     if (DclT->isDependentType()) {
12238 
12239     // Allow any 'static constexpr' members, whether or not they are of literal
12240     // type. We separately check that every constexpr variable is of literal
12241     // type.
12242     } else if (VDecl->isConstexpr()) {
12243 
12244     // Require constness.
12245     } else if (!DclT.isConstQualified()) {
12246       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12247         << Init->getSourceRange();
12248       VDecl->setInvalidDecl();
12249 
12250     // We allow integer constant expressions in all cases.
12251     } else if (DclT->isIntegralOrEnumerationType()) {
12252       // Check whether the expression is a constant expression.
12253       SourceLocation Loc;
12254       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12255         // In C++11, a non-constexpr const static data member with an
12256         // in-class initializer cannot be volatile.
12257         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12258       else if (Init->isValueDependent())
12259         ; // Nothing to check.
12260       else if (Init->isIntegerConstantExpr(Context, &Loc))
12261         ; // Ok, it's an ICE!
12262       else if (Init->getType()->isScopedEnumeralType() &&
12263                Init->isCXX11ConstantExpr(Context))
12264         ; // Ok, it is a scoped-enum constant expression.
12265       else if (Init->isEvaluatable(Context)) {
12266         // If we can constant fold the initializer through heroics, accept it,
12267         // but report this as a use of an extension for -pedantic.
12268         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12269           << Init->getSourceRange();
12270       } else {
12271         // Otherwise, this is some crazy unknown case.  Report the issue at the
12272         // location provided by the isIntegerConstantExpr failed check.
12273         Diag(Loc, diag::err_in_class_initializer_non_constant)
12274           << Init->getSourceRange();
12275         VDecl->setInvalidDecl();
12276       }
12277 
12278     // We allow foldable floating-point constants as an extension.
12279     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12280       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12281       // it anyway and provide a fixit to add the 'constexpr'.
12282       if (getLangOpts().CPlusPlus11) {
12283         Diag(VDecl->getLocation(),
12284              diag::ext_in_class_initializer_float_type_cxx11)
12285             << DclT << Init->getSourceRange();
12286         Diag(VDecl->getBeginLoc(),
12287              diag::note_in_class_initializer_float_type_cxx11)
12288             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12289       } else {
12290         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12291           << DclT << Init->getSourceRange();
12292 
12293         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12294           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12295             << Init->getSourceRange();
12296           VDecl->setInvalidDecl();
12297         }
12298       }
12299 
12300     // Suggest adding 'constexpr' in C++11 for literal types.
12301     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12302       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12303           << DclT << Init->getSourceRange()
12304           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12305       VDecl->setConstexpr(true);
12306 
12307     } else {
12308       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12309         << DclT << Init->getSourceRange();
12310       VDecl->setInvalidDecl();
12311     }
12312   } else if (VDecl->isFileVarDecl()) {
12313     // In C, extern is typically used to avoid tentative definitions when
12314     // declaring variables in headers, but adding an intializer makes it a
12315     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12316     // In C++, extern is often used to give implictly static const variables
12317     // external linkage, so don't warn in that case. If selectany is present,
12318     // this might be header code intended for C and C++ inclusion, so apply the
12319     // C++ rules.
12320     if (VDecl->getStorageClass() == SC_Extern &&
12321         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12322          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12323         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12324         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12325       Diag(VDecl->getLocation(), diag::warn_extern_init);
12326 
12327     // In Microsoft C++ mode, a const variable defined in namespace scope has
12328     // external linkage by default if the variable is declared with
12329     // __declspec(dllexport).
12330     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12331         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12332         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12333       VDecl->setStorageClass(SC_Extern);
12334 
12335     // C99 6.7.8p4. All file scoped initializers need to be constant.
12336     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12337       CheckForConstantInitializer(Init, DclT);
12338   }
12339 
12340   QualType InitType = Init->getType();
12341   if (!InitType.isNull() &&
12342       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12343        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12344     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12345 
12346   // We will represent direct-initialization similarly to copy-initialization:
12347   //    int x(1);  -as-> int x = 1;
12348   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12349   //
12350   // Clients that want to distinguish between the two forms, can check for
12351   // direct initializer using VarDecl::getInitStyle().
12352   // A major benefit is that clients that don't particularly care about which
12353   // exactly form was it (like the CodeGen) can handle both cases without
12354   // special case code.
12355 
12356   // C++ 8.5p11:
12357   // The form of initialization (using parentheses or '=') is generally
12358   // insignificant, but does matter when the entity being initialized has a
12359   // class type.
12360   if (CXXDirectInit) {
12361     assert(DirectInit && "Call-style initializer must be direct init.");
12362     VDecl->setInitStyle(VarDecl::CallInit);
12363   } else if (DirectInit) {
12364     // This must be list-initialization. No other way is direct-initialization.
12365     VDecl->setInitStyle(VarDecl::ListInit);
12366   }
12367 
12368   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12369     DeclsToCheckForDeferredDiags.push_back(VDecl);
12370   CheckCompleteVariableDeclaration(VDecl);
12371 }
12372 
12373 /// ActOnInitializerError - Given that there was an error parsing an
12374 /// initializer for the given declaration, try to return to some form
12375 /// of sanity.
12376 void Sema::ActOnInitializerError(Decl *D) {
12377   // Our main concern here is re-establishing invariants like "a
12378   // variable's type is either dependent or complete".
12379   if (!D || D->isInvalidDecl()) return;
12380 
12381   VarDecl *VD = dyn_cast<VarDecl>(D);
12382   if (!VD) return;
12383 
12384   // Bindings are not usable if we can't make sense of the initializer.
12385   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12386     for (auto *BD : DD->bindings())
12387       BD->setInvalidDecl();
12388 
12389   // Auto types are meaningless if we can't make sense of the initializer.
12390   if (VD->getType()->isUndeducedType()) {
12391     D->setInvalidDecl();
12392     return;
12393   }
12394 
12395   QualType Ty = VD->getType();
12396   if (Ty->isDependentType()) return;
12397 
12398   // Require a complete type.
12399   if (RequireCompleteType(VD->getLocation(),
12400                           Context.getBaseElementType(Ty),
12401                           diag::err_typecheck_decl_incomplete_type)) {
12402     VD->setInvalidDecl();
12403     return;
12404   }
12405 
12406   // Require a non-abstract type.
12407   if (RequireNonAbstractType(VD->getLocation(), Ty,
12408                              diag::err_abstract_type_in_decl,
12409                              AbstractVariableType)) {
12410     VD->setInvalidDecl();
12411     return;
12412   }
12413 
12414   // Don't bother complaining about constructors or destructors,
12415   // though.
12416 }
12417 
12418 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12419   // If there is no declaration, there was an error parsing it. Just ignore it.
12420   if (!RealDecl)
12421     return;
12422 
12423   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12424     QualType Type = Var->getType();
12425 
12426     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12427     if (isa<DecompositionDecl>(RealDecl)) {
12428       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12429       Var->setInvalidDecl();
12430       return;
12431     }
12432 
12433     if (Type->isUndeducedType() &&
12434         DeduceVariableDeclarationType(Var, false, nullptr))
12435       return;
12436 
12437     // C++11 [class.static.data]p3: A static data member can be declared with
12438     // the constexpr specifier; if so, its declaration shall specify
12439     // a brace-or-equal-initializer.
12440     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12441     // the definition of a variable [...] or the declaration of a static data
12442     // member.
12443     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12444         !Var->isThisDeclarationADemotedDefinition()) {
12445       if (Var->isStaticDataMember()) {
12446         // C++1z removes the relevant rule; the in-class declaration is always
12447         // a definition there.
12448         if (!getLangOpts().CPlusPlus17 &&
12449             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12450           Diag(Var->getLocation(),
12451                diag::err_constexpr_static_mem_var_requires_init)
12452               << Var;
12453           Var->setInvalidDecl();
12454           return;
12455         }
12456       } else {
12457         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12458         Var->setInvalidDecl();
12459         return;
12460       }
12461     }
12462 
12463     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12464     // be initialized.
12465     if (!Var->isInvalidDecl() &&
12466         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12467         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12468       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12469       Var->setInvalidDecl();
12470       return;
12471     }
12472 
12473     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12474       if (Var->getStorageClass() == SC_Extern) {
12475         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12476             << Var;
12477         Var->setInvalidDecl();
12478         return;
12479       }
12480       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12481                               diag::err_typecheck_decl_incomplete_type)) {
12482         Var->setInvalidDecl();
12483         return;
12484       }
12485       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12486         if (!RD->hasTrivialDefaultConstructor()) {
12487           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12488           Var->setInvalidDecl();
12489           return;
12490         }
12491       }
12492     }
12493 
12494     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12495     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12496         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12497       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12498                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12499 
12500 
12501     switch (DefKind) {
12502     case VarDecl::Definition:
12503       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12504         break;
12505 
12506       // We have an out-of-line definition of a static data member
12507       // that has an in-class initializer, so we type-check this like
12508       // a declaration.
12509       //
12510       LLVM_FALLTHROUGH;
12511 
12512     case VarDecl::DeclarationOnly:
12513       // It's only a declaration.
12514 
12515       // Block scope. C99 6.7p7: If an identifier for an object is
12516       // declared with no linkage (C99 6.2.2p6), the type for the
12517       // object shall be complete.
12518       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12519           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12520           RequireCompleteType(Var->getLocation(), Type,
12521                               diag::err_typecheck_decl_incomplete_type))
12522         Var->setInvalidDecl();
12523 
12524       // Make sure that the type is not abstract.
12525       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12526           RequireNonAbstractType(Var->getLocation(), Type,
12527                                  diag::err_abstract_type_in_decl,
12528                                  AbstractVariableType))
12529         Var->setInvalidDecl();
12530       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12531           Var->getStorageClass() == SC_PrivateExtern) {
12532         Diag(Var->getLocation(), diag::warn_private_extern);
12533         Diag(Var->getLocation(), diag::note_private_extern);
12534       }
12535 
12536       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12537           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12538         ExternalDeclarations.push_back(Var);
12539 
12540       return;
12541 
12542     case VarDecl::TentativeDefinition:
12543       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12544       // object that has file scope without an initializer, and without a
12545       // storage-class specifier or with the storage-class specifier "static",
12546       // constitutes a tentative definition. Note: A tentative definition with
12547       // external linkage is valid (C99 6.2.2p5).
12548       if (!Var->isInvalidDecl()) {
12549         if (const IncompleteArrayType *ArrayT
12550                                     = Context.getAsIncompleteArrayType(Type)) {
12551           if (RequireCompleteSizedType(
12552                   Var->getLocation(), ArrayT->getElementType(),
12553                   diag::err_array_incomplete_or_sizeless_type))
12554             Var->setInvalidDecl();
12555         } else if (Var->getStorageClass() == SC_Static) {
12556           // C99 6.9.2p3: If the declaration of an identifier for an object is
12557           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12558           // declared type shall not be an incomplete type.
12559           // NOTE: code such as the following
12560           //     static struct s;
12561           //     struct s { int a; };
12562           // is accepted by gcc. Hence here we issue a warning instead of
12563           // an error and we do not invalidate the static declaration.
12564           // NOTE: to avoid multiple warnings, only check the first declaration.
12565           if (Var->isFirstDecl())
12566             RequireCompleteType(Var->getLocation(), Type,
12567                                 diag::ext_typecheck_decl_incomplete_type);
12568         }
12569       }
12570 
12571       // Record the tentative definition; we're done.
12572       if (!Var->isInvalidDecl())
12573         TentativeDefinitions.push_back(Var);
12574       return;
12575     }
12576 
12577     // Provide a specific diagnostic for uninitialized variable
12578     // definitions with incomplete array type.
12579     if (Type->isIncompleteArrayType()) {
12580       Diag(Var->getLocation(),
12581            diag::err_typecheck_incomplete_array_needs_initializer);
12582       Var->setInvalidDecl();
12583       return;
12584     }
12585 
12586     // Provide a specific diagnostic for uninitialized variable
12587     // definitions with reference type.
12588     if (Type->isReferenceType()) {
12589       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12590           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12591       Var->setInvalidDecl();
12592       return;
12593     }
12594 
12595     // Do not attempt to type-check the default initializer for a
12596     // variable with dependent type.
12597     if (Type->isDependentType())
12598       return;
12599 
12600     if (Var->isInvalidDecl())
12601       return;
12602 
12603     if (!Var->hasAttr<AliasAttr>()) {
12604       if (RequireCompleteType(Var->getLocation(),
12605                               Context.getBaseElementType(Type),
12606                               diag::err_typecheck_decl_incomplete_type)) {
12607         Var->setInvalidDecl();
12608         return;
12609       }
12610     } else {
12611       return;
12612     }
12613 
12614     // The variable can not have an abstract class type.
12615     if (RequireNonAbstractType(Var->getLocation(), Type,
12616                                diag::err_abstract_type_in_decl,
12617                                AbstractVariableType)) {
12618       Var->setInvalidDecl();
12619       return;
12620     }
12621 
12622     // Check for jumps past the implicit initializer.  C++0x
12623     // clarifies that this applies to a "variable with automatic
12624     // storage duration", not a "local variable".
12625     // C++11 [stmt.dcl]p3
12626     //   A program that jumps from a point where a variable with automatic
12627     //   storage duration is not in scope to a point where it is in scope is
12628     //   ill-formed unless the variable has scalar type, class type with a
12629     //   trivial default constructor and a trivial destructor, a cv-qualified
12630     //   version of one of these types, or an array of one of the preceding
12631     //   types and is declared without an initializer.
12632     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12633       if (const RecordType *Record
12634             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12635         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12636         // Mark the function (if we're in one) for further checking even if the
12637         // looser rules of C++11 do not require such checks, so that we can
12638         // diagnose incompatibilities with C++98.
12639         if (!CXXRecord->isPOD())
12640           setFunctionHasBranchProtectedScope();
12641       }
12642     }
12643     // In OpenCL, we can't initialize objects in the __local address space,
12644     // even implicitly, so don't synthesize an implicit initializer.
12645     if (getLangOpts().OpenCL &&
12646         Var->getType().getAddressSpace() == LangAS::opencl_local)
12647       return;
12648     // C++03 [dcl.init]p9:
12649     //   If no initializer is specified for an object, and the
12650     //   object is of (possibly cv-qualified) non-POD class type (or
12651     //   array thereof), the object shall be default-initialized; if
12652     //   the object is of const-qualified type, the underlying class
12653     //   type shall have a user-declared default
12654     //   constructor. Otherwise, if no initializer is specified for
12655     //   a non- static object, the object and its subobjects, if
12656     //   any, have an indeterminate initial value); if the object
12657     //   or any of its subobjects are of const-qualified type, the
12658     //   program is ill-formed.
12659     // C++0x [dcl.init]p11:
12660     //   If no initializer is specified for an object, the object is
12661     //   default-initialized; [...].
12662     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12663     InitializationKind Kind
12664       = InitializationKind::CreateDefault(Var->getLocation());
12665 
12666     InitializationSequence InitSeq(*this, Entity, Kind, None);
12667     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12668 
12669     if (Init.get()) {
12670       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12671       // This is important for template substitution.
12672       Var->setInitStyle(VarDecl::CallInit);
12673     } else if (Init.isInvalid()) {
12674       // If default-init fails, attach a recovery-expr initializer to track
12675       // that initialization was attempted and failed.
12676       auto RecoveryExpr =
12677           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12678       if (RecoveryExpr.get())
12679         Var->setInit(RecoveryExpr.get());
12680     }
12681 
12682     CheckCompleteVariableDeclaration(Var);
12683   }
12684 }
12685 
12686 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12687   // If there is no declaration, there was an error parsing it. Ignore it.
12688   if (!D)
12689     return;
12690 
12691   VarDecl *VD = dyn_cast<VarDecl>(D);
12692   if (!VD) {
12693     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12694     D->setInvalidDecl();
12695     return;
12696   }
12697 
12698   VD->setCXXForRangeDecl(true);
12699 
12700   // for-range-declaration cannot be given a storage class specifier.
12701   int Error = -1;
12702   switch (VD->getStorageClass()) {
12703   case SC_None:
12704     break;
12705   case SC_Extern:
12706     Error = 0;
12707     break;
12708   case SC_Static:
12709     Error = 1;
12710     break;
12711   case SC_PrivateExtern:
12712     Error = 2;
12713     break;
12714   case SC_Auto:
12715     Error = 3;
12716     break;
12717   case SC_Register:
12718     Error = 4;
12719     break;
12720   }
12721   if (Error != -1) {
12722     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12723         << VD << Error;
12724     D->setInvalidDecl();
12725   }
12726 }
12727 
12728 StmtResult
12729 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12730                                  IdentifierInfo *Ident,
12731                                  ParsedAttributes &Attrs,
12732                                  SourceLocation AttrEnd) {
12733   // C++1y [stmt.iter]p1:
12734   //   A range-based for statement of the form
12735   //      for ( for-range-identifier : for-range-initializer ) statement
12736   //   is equivalent to
12737   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12738   DeclSpec DS(Attrs.getPool().getFactory());
12739 
12740   const char *PrevSpec;
12741   unsigned DiagID;
12742   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12743                      getPrintingPolicy());
12744 
12745   Declarator D(DS, DeclaratorContext::ForContext);
12746   D.SetIdentifier(Ident, IdentLoc);
12747   D.takeAttributes(Attrs, AttrEnd);
12748 
12749   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12750                 IdentLoc);
12751   Decl *Var = ActOnDeclarator(S, D);
12752   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12753   FinalizeDeclaration(Var);
12754   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12755                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12756 }
12757 
12758 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12759   if (var->isInvalidDecl()) return;
12760 
12761   if (getLangOpts().OpenCL) {
12762     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12763     // initialiser
12764     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12765         !var->hasInit()) {
12766       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12767           << 1 /*Init*/;
12768       var->setInvalidDecl();
12769       return;
12770     }
12771   }
12772 
12773   // In Objective-C, don't allow jumps past the implicit initialization of a
12774   // local retaining variable.
12775   if (getLangOpts().ObjC &&
12776       var->hasLocalStorage()) {
12777     switch (var->getType().getObjCLifetime()) {
12778     case Qualifiers::OCL_None:
12779     case Qualifiers::OCL_ExplicitNone:
12780     case Qualifiers::OCL_Autoreleasing:
12781       break;
12782 
12783     case Qualifiers::OCL_Weak:
12784     case Qualifiers::OCL_Strong:
12785       setFunctionHasBranchProtectedScope();
12786       break;
12787     }
12788   }
12789 
12790   if (var->hasLocalStorage() &&
12791       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12792     setFunctionHasBranchProtectedScope();
12793 
12794   // Warn about externally-visible variables being defined without a
12795   // prior declaration.  We only want to do this for global
12796   // declarations, but we also specifically need to avoid doing it for
12797   // class members because the linkage of an anonymous class can
12798   // change if it's later given a typedef name.
12799   if (var->isThisDeclarationADefinition() &&
12800       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12801       var->isExternallyVisible() && var->hasLinkage() &&
12802       !var->isInline() && !var->getDescribedVarTemplate() &&
12803       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12804       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12805       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12806                                   var->getLocation())) {
12807     // Find a previous declaration that's not a definition.
12808     VarDecl *prev = var->getPreviousDecl();
12809     while (prev && prev->isThisDeclarationADefinition())
12810       prev = prev->getPreviousDecl();
12811 
12812     if (!prev) {
12813       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12814       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12815           << /* variable */ 0;
12816     }
12817   }
12818 
12819   // Cache the result of checking for constant initialization.
12820   Optional<bool> CacheHasConstInit;
12821   const Expr *CacheCulprit = nullptr;
12822   auto checkConstInit = [&]() mutable {
12823     if (!CacheHasConstInit)
12824       CacheHasConstInit = var->getInit()->isConstantInitializer(
12825             Context, var->getType()->isReferenceType(), &CacheCulprit);
12826     return *CacheHasConstInit;
12827   };
12828 
12829   if (var->getTLSKind() == VarDecl::TLS_Static) {
12830     if (var->getType().isDestructedType()) {
12831       // GNU C++98 edits for __thread, [basic.start.term]p3:
12832       //   The type of an object with thread storage duration shall not
12833       //   have a non-trivial destructor.
12834       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12835       if (getLangOpts().CPlusPlus11)
12836         Diag(var->getLocation(), diag::note_use_thread_local);
12837     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12838       if (!checkConstInit()) {
12839         // GNU C++98 edits for __thread, [basic.start.init]p4:
12840         //   An object of thread storage duration shall not require dynamic
12841         //   initialization.
12842         // FIXME: Need strict checking here.
12843         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12844           << CacheCulprit->getSourceRange();
12845         if (getLangOpts().CPlusPlus11)
12846           Diag(var->getLocation(), diag::note_use_thread_local);
12847       }
12848     }
12849   }
12850 
12851   // Apply section attributes and pragmas to global variables.
12852   bool GlobalStorage = var->hasGlobalStorage();
12853   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12854       !inTemplateInstantiation()) {
12855     PragmaStack<StringLiteral *> *Stack = nullptr;
12856     int SectionFlags = ASTContext::PSF_Read;
12857     if (var->getType().isConstQualified())
12858       Stack = &ConstSegStack;
12859     else if (!var->getInit()) {
12860       Stack = &BSSSegStack;
12861       SectionFlags |= ASTContext::PSF_Write;
12862     } else {
12863       Stack = &DataSegStack;
12864       SectionFlags |= ASTContext::PSF_Write;
12865     }
12866     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12867       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12868         SectionFlags |= ASTContext::PSF_Implicit;
12869       UnifySection(SA->getName(), SectionFlags, var);
12870     } else if (Stack->CurrentValue) {
12871       SectionFlags |= ASTContext::PSF_Implicit;
12872       auto SectionName = Stack->CurrentValue->getString();
12873       var->addAttr(SectionAttr::CreateImplicit(
12874           Context, SectionName, Stack->CurrentPragmaLocation,
12875           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12876       if (UnifySection(SectionName, SectionFlags, var))
12877         var->dropAttr<SectionAttr>();
12878     }
12879 
12880     // Apply the init_seg attribute if this has an initializer.  If the
12881     // initializer turns out to not be dynamic, we'll end up ignoring this
12882     // attribute.
12883     if (CurInitSeg && var->getInit())
12884       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12885                                                CurInitSegLoc,
12886                                                AttributeCommonInfo::AS_Pragma));
12887   }
12888 
12889   if (!var->getType()->isStructureType() && var->hasInit() &&
12890       isa<InitListExpr>(var->getInit())) {
12891     const auto *ILE = cast<InitListExpr>(var->getInit());
12892     unsigned NumInits = ILE->getNumInits();
12893     if (NumInits > 2)
12894       for (unsigned I = 0; I < NumInits; ++I) {
12895         const auto *Init = ILE->getInit(I);
12896         if (!Init)
12897           break;
12898         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12899         if (!SL)
12900           break;
12901 
12902         unsigned NumConcat = SL->getNumConcatenated();
12903         // Diagnose missing comma in string array initialization.
12904         // Do not warn when all the elements in the initializer are concatenated
12905         // together. Do not warn for macros too.
12906         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12907           bool OnlyOneMissingComma = true;
12908           for (unsigned J = I + 1; J < NumInits; ++J) {
12909             const auto *Init = ILE->getInit(J);
12910             if (!Init)
12911               break;
12912             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12913             if (!SLJ || SLJ->getNumConcatenated() > 1) {
12914               OnlyOneMissingComma = false;
12915               break;
12916             }
12917           }
12918 
12919           if (OnlyOneMissingComma) {
12920             SmallVector<FixItHint, 1> Hints;
12921             for (unsigned i = 0; i < NumConcat - 1; ++i)
12922               Hints.push_back(FixItHint::CreateInsertion(
12923                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12924 
12925             Diag(SL->getStrTokenLoc(1),
12926                  diag::warn_concatenated_literal_array_init)
12927                 << Hints;
12928             Diag(SL->getBeginLoc(),
12929                  diag::note_concatenated_string_literal_silence);
12930           }
12931           // In any case, stop now.
12932           break;
12933         }
12934       }
12935   }
12936 
12937   // All the following checks are C++ only.
12938   if (!getLangOpts().CPlusPlus) {
12939       // If this variable must be emitted, add it as an initializer for the
12940       // current module.
12941      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12942        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12943      return;
12944   }
12945 
12946   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12947     CheckCompleteDecompositionDeclaration(DD);
12948 
12949   QualType type = var->getType();
12950   if (type->isDependentType()) return;
12951 
12952   if (var->hasAttr<BlocksAttr>())
12953     getCurFunction()->addByrefBlockVar(var);
12954 
12955   Expr *Init = var->getInit();
12956   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12957   QualType baseType = Context.getBaseElementType(type);
12958 
12959   if (Init && !Init->isValueDependent()) {
12960     if (var->isConstexpr()) {
12961       SmallVector<PartialDiagnosticAt, 8> Notes;
12962       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12963         SourceLocation DiagLoc = var->getLocation();
12964         // If the note doesn't add any useful information other than a source
12965         // location, fold it into the primary diagnostic.
12966         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12967               diag::note_invalid_subexpr_in_const_expr) {
12968           DiagLoc = Notes[0].first;
12969           Notes.clear();
12970         }
12971         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12972           << var << Init->getSourceRange();
12973         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12974           Diag(Notes[I].first, Notes[I].second);
12975       }
12976     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12977       // Check whether the initializer of a const variable of integral or
12978       // enumeration type is an ICE now, since we can't tell whether it was
12979       // initialized by a constant expression if we check later.
12980       var->checkInitIsICE();
12981     }
12982 
12983     // Don't emit further diagnostics about constexpr globals since they
12984     // were just diagnosed.
12985     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12986       // FIXME: Need strict checking in C++03 here.
12987       bool DiagErr = getLangOpts().CPlusPlus11
12988           ? !var->checkInitIsICE() : !checkConstInit();
12989       if (DiagErr) {
12990         auto *Attr = var->getAttr<ConstInitAttr>();
12991         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12992           << Init->getSourceRange();
12993         Diag(Attr->getLocation(),
12994              diag::note_declared_required_constant_init_here)
12995             << Attr->getRange() << Attr->isConstinit();
12996         if (getLangOpts().CPlusPlus11) {
12997           APValue Value;
12998           SmallVector<PartialDiagnosticAt, 8> Notes;
12999           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
13000           for (auto &it : Notes)
13001             Diag(it.first, it.second);
13002         } else {
13003           Diag(CacheCulprit->getExprLoc(),
13004                diag::note_invalid_subexpr_in_const_expr)
13005               << CacheCulprit->getSourceRange();
13006         }
13007       }
13008     }
13009     else if (!var->isConstexpr() && IsGlobal &&
13010              !getDiagnostics().isIgnored(diag::warn_global_constructor,
13011                                     var->getLocation())) {
13012       // Warn about globals which don't have a constant initializer.  Don't
13013       // warn about globals with a non-trivial destructor because we already
13014       // warned about them.
13015       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13016       if (!(RD && !RD->hasTrivialDestructor())) {
13017         if (!checkConstInit())
13018           Diag(var->getLocation(), diag::warn_global_constructor)
13019             << Init->getSourceRange();
13020       }
13021     }
13022   }
13023 
13024   // Require the destructor.
13025   if (const RecordType *recordType = baseType->getAs<RecordType>())
13026     FinalizeVarWithDestructor(var, recordType);
13027 
13028   // If this variable must be emitted, add it as an initializer for the current
13029   // module.
13030   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13031     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13032 }
13033 
13034 /// Determines if a variable's alignment is dependent.
13035 static bool hasDependentAlignment(VarDecl *VD) {
13036   if (VD->getType()->isDependentType())
13037     return true;
13038   for (auto *I : VD->specific_attrs<AlignedAttr>())
13039     if (I->isAlignmentDependent())
13040       return true;
13041   return false;
13042 }
13043 
13044 /// Check if VD needs to be dllexport/dllimport due to being in a
13045 /// dllexport/import function.
13046 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13047   assert(VD->isStaticLocal());
13048 
13049   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13050 
13051   // Find outermost function when VD is in lambda function.
13052   while (FD && !getDLLAttr(FD) &&
13053          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13054          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13055     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13056   }
13057 
13058   if (!FD)
13059     return;
13060 
13061   // Static locals inherit dll attributes from their function.
13062   if (Attr *A = getDLLAttr(FD)) {
13063     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13064     NewAttr->setInherited(true);
13065     VD->addAttr(NewAttr);
13066   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13067     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13068     NewAttr->setInherited(true);
13069     VD->addAttr(NewAttr);
13070 
13071     // Export this function to enforce exporting this static variable even
13072     // if it is not used in this compilation unit.
13073     if (!FD->hasAttr<DLLExportAttr>())
13074       FD->addAttr(NewAttr);
13075 
13076   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13077     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13078     NewAttr->setInherited(true);
13079     VD->addAttr(NewAttr);
13080   }
13081 }
13082 
13083 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13084 /// any semantic actions necessary after any initializer has been attached.
13085 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13086   // Note that we are no longer parsing the initializer for this declaration.
13087   ParsingInitForAutoVars.erase(ThisDecl);
13088 
13089   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13090   if (!VD)
13091     return;
13092 
13093   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13094   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13095       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13096     if (PragmaClangBSSSection.Valid)
13097       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13098           Context, PragmaClangBSSSection.SectionName,
13099           PragmaClangBSSSection.PragmaLocation,
13100           AttributeCommonInfo::AS_Pragma));
13101     if (PragmaClangDataSection.Valid)
13102       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13103           Context, PragmaClangDataSection.SectionName,
13104           PragmaClangDataSection.PragmaLocation,
13105           AttributeCommonInfo::AS_Pragma));
13106     if (PragmaClangRodataSection.Valid)
13107       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13108           Context, PragmaClangRodataSection.SectionName,
13109           PragmaClangRodataSection.PragmaLocation,
13110           AttributeCommonInfo::AS_Pragma));
13111     if (PragmaClangRelroSection.Valid)
13112       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13113           Context, PragmaClangRelroSection.SectionName,
13114           PragmaClangRelroSection.PragmaLocation,
13115           AttributeCommonInfo::AS_Pragma));
13116   }
13117 
13118   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13119     for (auto *BD : DD->bindings()) {
13120       FinalizeDeclaration(BD);
13121     }
13122   }
13123 
13124   checkAttributesAfterMerging(*this, *VD);
13125 
13126   // Perform TLS alignment check here after attributes attached to the variable
13127   // which may affect the alignment have been processed. Only perform the check
13128   // if the target has a maximum TLS alignment (zero means no constraints).
13129   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13130     // Protect the check so that it's not performed on dependent types and
13131     // dependent alignments (we can't determine the alignment in that case).
13132     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13133         !VD->isInvalidDecl()) {
13134       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13135       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13136         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13137           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13138           << (unsigned)MaxAlignChars.getQuantity();
13139       }
13140     }
13141   }
13142 
13143   if (VD->isStaticLocal()) {
13144     CheckStaticLocalForDllExport(VD);
13145 
13146     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13147       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13148       // function, only __shared__ variables or variables without any device
13149       // memory qualifiers may be declared with static storage class.
13150       // Note: It is unclear how a function-scope non-const static variable
13151       // without device memory qualifier is implemented, therefore only static
13152       // const variable without device memory qualifier is allowed.
13153       [&]() {
13154         if (!getLangOpts().CUDA)
13155           return;
13156         if (VD->hasAttr<CUDASharedAttr>())
13157           return;
13158         if (VD->getType().isConstQualified() &&
13159             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13160           return;
13161         if (CUDADiagIfDeviceCode(VD->getLocation(),
13162                                  diag::err_device_static_local_var)
13163             << CurrentCUDATarget())
13164           VD->setInvalidDecl();
13165       }();
13166     }
13167   }
13168 
13169   // Perform check for initializers of device-side global variables.
13170   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13171   // 7.5). We must also apply the same checks to all __shared__
13172   // variables whether they are local or not. CUDA also allows
13173   // constant initializers for __constant__ and __device__ variables.
13174   if (getLangOpts().CUDA)
13175     checkAllowedCUDAInitializer(VD);
13176 
13177   // Grab the dllimport or dllexport attribute off of the VarDecl.
13178   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13179 
13180   // Imported static data members cannot be defined out-of-line.
13181   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13182     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13183         VD->isThisDeclarationADefinition()) {
13184       // We allow definitions of dllimport class template static data members
13185       // with a warning.
13186       CXXRecordDecl *Context =
13187         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13188       bool IsClassTemplateMember =
13189           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13190           Context->getDescribedClassTemplate();
13191 
13192       Diag(VD->getLocation(),
13193            IsClassTemplateMember
13194                ? diag::warn_attribute_dllimport_static_field_definition
13195                : diag::err_attribute_dllimport_static_field_definition);
13196       Diag(IA->getLocation(), diag::note_attribute);
13197       if (!IsClassTemplateMember)
13198         VD->setInvalidDecl();
13199     }
13200   }
13201 
13202   // dllimport/dllexport variables cannot be thread local, their TLS index
13203   // isn't exported with the variable.
13204   if (DLLAttr && VD->getTLSKind()) {
13205     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13206     if (F && getDLLAttr(F)) {
13207       assert(VD->isStaticLocal());
13208       // But if this is a static local in a dlimport/dllexport function, the
13209       // function will never be inlined, which means the var would never be
13210       // imported, so having it marked import/export is safe.
13211     } else {
13212       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13213                                                                     << DLLAttr;
13214       VD->setInvalidDecl();
13215     }
13216   }
13217 
13218   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13219     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13220       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13221       VD->dropAttr<UsedAttr>();
13222     }
13223   }
13224 
13225   const DeclContext *DC = VD->getDeclContext();
13226   // If there's a #pragma GCC visibility in scope, and this isn't a class
13227   // member, set the visibility of this variable.
13228   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13229     AddPushedVisibilityAttribute(VD);
13230 
13231   // FIXME: Warn on unused var template partial specializations.
13232   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13233     MarkUnusedFileScopedDecl(VD);
13234 
13235   // Now we have parsed the initializer and can update the table of magic
13236   // tag values.
13237   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13238       !VD->getType()->isIntegralOrEnumerationType())
13239     return;
13240 
13241   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13242     const Expr *MagicValueExpr = VD->getInit();
13243     if (!MagicValueExpr) {
13244       continue;
13245     }
13246     Optional<llvm::APSInt> MagicValueInt;
13247     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13248       Diag(I->getRange().getBegin(),
13249            diag::err_type_tag_for_datatype_not_ice)
13250         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13251       continue;
13252     }
13253     if (MagicValueInt->getActiveBits() > 64) {
13254       Diag(I->getRange().getBegin(),
13255            diag::err_type_tag_for_datatype_too_large)
13256         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13257       continue;
13258     }
13259     uint64_t MagicValue = MagicValueInt->getZExtValue();
13260     RegisterTypeTagForDatatype(I->getArgumentKind(),
13261                                MagicValue,
13262                                I->getMatchingCType(),
13263                                I->getLayoutCompatible(),
13264                                I->getMustBeNull());
13265   }
13266 }
13267 
13268 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13269   auto *VD = dyn_cast<VarDecl>(DD);
13270   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13271 }
13272 
13273 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13274                                                    ArrayRef<Decl *> Group) {
13275   SmallVector<Decl*, 8> Decls;
13276 
13277   if (DS.isTypeSpecOwned())
13278     Decls.push_back(DS.getRepAsDecl());
13279 
13280   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13281   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13282   bool DiagnosedMultipleDecomps = false;
13283   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13284   bool DiagnosedNonDeducedAuto = false;
13285 
13286   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13287     if (Decl *D = Group[i]) {
13288       // For declarators, there are some additional syntactic-ish checks we need
13289       // to perform.
13290       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13291         if (!FirstDeclaratorInGroup)
13292           FirstDeclaratorInGroup = DD;
13293         if (!FirstDecompDeclaratorInGroup)
13294           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13295         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13296             !hasDeducedAuto(DD))
13297           FirstNonDeducedAutoInGroup = DD;
13298 
13299         if (FirstDeclaratorInGroup != DD) {
13300           // A decomposition declaration cannot be combined with any other
13301           // declaration in the same group.
13302           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13303             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13304                  diag::err_decomp_decl_not_alone)
13305                 << FirstDeclaratorInGroup->getSourceRange()
13306                 << DD->getSourceRange();
13307             DiagnosedMultipleDecomps = true;
13308           }
13309 
13310           // A declarator that uses 'auto' in any way other than to declare a
13311           // variable with a deduced type cannot be combined with any other
13312           // declarator in the same group.
13313           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13314             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13315                  diag::err_auto_non_deduced_not_alone)
13316                 << FirstNonDeducedAutoInGroup->getType()
13317                        ->hasAutoForTrailingReturnType()
13318                 << FirstDeclaratorInGroup->getSourceRange()
13319                 << DD->getSourceRange();
13320             DiagnosedNonDeducedAuto = true;
13321           }
13322         }
13323       }
13324 
13325       Decls.push_back(D);
13326     }
13327   }
13328 
13329   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13330     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13331       handleTagNumbering(Tag, S);
13332       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13333           getLangOpts().CPlusPlus)
13334         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13335     }
13336   }
13337 
13338   return BuildDeclaratorGroup(Decls);
13339 }
13340 
13341 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13342 /// group, performing any necessary semantic checking.
13343 Sema::DeclGroupPtrTy
13344 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13345   // C++14 [dcl.spec.auto]p7: (DR1347)
13346   //   If the type that replaces the placeholder type is not the same in each
13347   //   deduction, the program is ill-formed.
13348   if (Group.size() > 1) {
13349     QualType Deduced;
13350     VarDecl *DeducedDecl = nullptr;
13351     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13352       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13353       if (!D || D->isInvalidDecl())
13354         break;
13355       DeducedType *DT = D->getType()->getContainedDeducedType();
13356       if (!DT || DT->getDeducedType().isNull())
13357         continue;
13358       if (Deduced.isNull()) {
13359         Deduced = DT->getDeducedType();
13360         DeducedDecl = D;
13361       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13362         auto *AT = dyn_cast<AutoType>(DT);
13363         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13364                         diag::err_auto_different_deductions)
13365                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13366                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13367                    << D->getDeclName();
13368         if (DeducedDecl->hasInit())
13369           Dia << DeducedDecl->getInit()->getSourceRange();
13370         if (D->getInit())
13371           Dia << D->getInit()->getSourceRange();
13372         D->setInvalidDecl();
13373         break;
13374       }
13375     }
13376   }
13377 
13378   ActOnDocumentableDecls(Group);
13379 
13380   return DeclGroupPtrTy::make(
13381       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13382 }
13383 
13384 void Sema::ActOnDocumentableDecl(Decl *D) {
13385   ActOnDocumentableDecls(D);
13386 }
13387 
13388 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13389   // Don't parse the comment if Doxygen diagnostics are ignored.
13390   if (Group.empty() || !Group[0])
13391     return;
13392 
13393   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13394                       Group[0]->getLocation()) &&
13395       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13396                       Group[0]->getLocation()))
13397     return;
13398 
13399   if (Group.size() >= 2) {
13400     // This is a decl group.  Normally it will contain only declarations
13401     // produced from declarator list.  But in case we have any definitions or
13402     // additional declaration references:
13403     //   'typedef struct S {} S;'
13404     //   'typedef struct S *S;'
13405     //   'struct S *pS;'
13406     // FinalizeDeclaratorGroup adds these as separate declarations.
13407     Decl *MaybeTagDecl = Group[0];
13408     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13409       Group = Group.slice(1);
13410     }
13411   }
13412 
13413   // FIMXE: We assume every Decl in the group is in the same file.
13414   // This is false when preprocessor constructs the group from decls in
13415   // different files (e. g. macros or #include).
13416   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13417 }
13418 
13419 /// Common checks for a parameter-declaration that should apply to both function
13420 /// parameters and non-type template parameters.
13421 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13422   // Check that there are no default arguments inside the type of this
13423   // parameter.
13424   if (getLangOpts().CPlusPlus)
13425     CheckExtraCXXDefaultArguments(D);
13426 
13427   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13428   if (D.getCXXScopeSpec().isSet()) {
13429     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13430       << D.getCXXScopeSpec().getRange();
13431   }
13432 
13433   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13434   // simple identifier except [...irrelevant cases...].
13435   switch (D.getName().getKind()) {
13436   case UnqualifiedIdKind::IK_Identifier:
13437     break;
13438 
13439   case UnqualifiedIdKind::IK_OperatorFunctionId:
13440   case UnqualifiedIdKind::IK_ConversionFunctionId:
13441   case UnqualifiedIdKind::IK_LiteralOperatorId:
13442   case UnqualifiedIdKind::IK_ConstructorName:
13443   case UnqualifiedIdKind::IK_DestructorName:
13444   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13445   case UnqualifiedIdKind::IK_DeductionGuideName:
13446     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13447       << GetNameForDeclarator(D).getName();
13448     break;
13449 
13450   case UnqualifiedIdKind::IK_TemplateId:
13451   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13452     // GetNameForDeclarator would not produce a useful name in this case.
13453     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13454     break;
13455   }
13456 }
13457 
13458 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13459 /// to introduce parameters into function prototype scope.
13460 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13461   const DeclSpec &DS = D.getDeclSpec();
13462 
13463   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13464 
13465   // C++03 [dcl.stc]p2 also permits 'auto'.
13466   StorageClass SC = SC_None;
13467   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13468     SC = SC_Register;
13469     // In C++11, the 'register' storage class specifier is deprecated.
13470     // In C++17, it is not allowed, but we tolerate it as an extension.
13471     if (getLangOpts().CPlusPlus11) {
13472       Diag(DS.getStorageClassSpecLoc(),
13473            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13474                                      : diag::warn_deprecated_register)
13475         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13476     }
13477   } else if (getLangOpts().CPlusPlus &&
13478              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13479     SC = SC_Auto;
13480   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13481     Diag(DS.getStorageClassSpecLoc(),
13482          diag::err_invalid_storage_class_in_func_decl);
13483     D.getMutableDeclSpec().ClearStorageClassSpecs();
13484   }
13485 
13486   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13487     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13488       << DeclSpec::getSpecifierName(TSCS);
13489   if (DS.isInlineSpecified())
13490     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13491         << getLangOpts().CPlusPlus17;
13492   if (DS.hasConstexprSpecifier())
13493     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13494         << 0 << D.getDeclSpec().getConstexprSpecifier();
13495 
13496   DiagnoseFunctionSpecifiers(DS);
13497 
13498   CheckFunctionOrTemplateParamDeclarator(S, D);
13499 
13500   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13501   QualType parmDeclType = TInfo->getType();
13502 
13503   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13504   IdentifierInfo *II = D.getIdentifier();
13505   if (II) {
13506     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13507                    ForVisibleRedeclaration);
13508     LookupName(R, S);
13509     if (R.isSingleResult()) {
13510       NamedDecl *PrevDecl = R.getFoundDecl();
13511       if (PrevDecl->isTemplateParameter()) {
13512         // Maybe we will complain about the shadowed template parameter.
13513         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13514         // Just pretend that we didn't see the previous declaration.
13515         PrevDecl = nullptr;
13516       } else if (S->isDeclScope(PrevDecl)) {
13517         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13518         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13519 
13520         // Recover by removing the name
13521         II = nullptr;
13522         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13523         D.setInvalidType(true);
13524       }
13525     }
13526   }
13527 
13528   // Temporarily put parameter variables in the translation unit, not
13529   // the enclosing context.  This prevents them from accidentally
13530   // looking like class members in C++.
13531   ParmVarDecl *New =
13532       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13533                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13534 
13535   if (D.isInvalidType())
13536     New->setInvalidDecl();
13537 
13538   assert(S->isFunctionPrototypeScope());
13539   assert(S->getFunctionPrototypeDepth() >= 1);
13540   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13541                     S->getNextFunctionPrototypeIndex());
13542 
13543   // Add the parameter declaration into this scope.
13544   S->AddDecl(New);
13545   if (II)
13546     IdResolver.AddDecl(New);
13547 
13548   ProcessDeclAttributes(S, New, D);
13549 
13550   if (D.getDeclSpec().isModulePrivateSpecified())
13551     Diag(New->getLocation(), diag::err_module_private_local)
13552         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13553         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13554 
13555   if (New->hasAttr<BlocksAttr>()) {
13556     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13557   }
13558 
13559   if (getLangOpts().OpenCL)
13560     deduceOpenCLAddressSpace(New);
13561 
13562   return New;
13563 }
13564 
13565 /// Synthesizes a variable for a parameter arising from a
13566 /// typedef.
13567 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13568                                               SourceLocation Loc,
13569                                               QualType T) {
13570   /* FIXME: setting StartLoc == Loc.
13571      Would it be worth to modify callers so as to provide proper source
13572      location for the unnamed parameters, embedding the parameter's type? */
13573   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13574                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13575                                            SC_None, nullptr);
13576   Param->setImplicit();
13577   return Param;
13578 }
13579 
13580 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13581   // Don't diagnose unused-parameter errors in template instantiations; we
13582   // will already have done so in the template itself.
13583   if (inTemplateInstantiation())
13584     return;
13585 
13586   for (const ParmVarDecl *Parameter : Parameters) {
13587     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13588         !Parameter->hasAttr<UnusedAttr>()) {
13589       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13590         << Parameter->getDeclName();
13591     }
13592   }
13593 }
13594 
13595 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13596     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13597   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13598     return;
13599 
13600   // Warn if the return value is pass-by-value and larger than the specified
13601   // threshold.
13602   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13603     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13604     if (Size > LangOpts.NumLargeByValueCopy)
13605       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13606   }
13607 
13608   // Warn if any parameter is pass-by-value and larger than the specified
13609   // threshold.
13610   for (const ParmVarDecl *Parameter : Parameters) {
13611     QualType T = Parameter->getType();
13612     if (T->isDependentType() || !T.isPODType(Context))
13613       continue;
13614     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13615     if (Size > LangOpts.NumLargeByValueCopy)
13616       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13617           << Parameter << Size;
13618   }
13619 }
13620 
13621 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13622                                   SourceLocation NameLoc, IdentifierInfo *Name,
13623                                   QualType T, TypeSourceInfo *TSInfo,
13624                                   StorageClass SC) {
13625   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13626   if (getLangOpts().ObjCAutoRefCount &&
13627       T.getObjCLifetime() == Qualifiers::OCL_None &&
13628       T->isObjCLifetimeType()) {
13629 
13630     Qualifiers::ObjCLifetime lifetime;
13631 
13632     // Special cases for arrays:
13633     //   - if it's const, use __unsafe_unretained
13634     //   - otherwise, it's an error
13635     if (T->isArrayType()) {
13636       if (!T.isConstQualified()) {
13637         if (DelayedDiagnostics.shouldDelayDiagnostics())
13638           DelayedDiagnostics.add(
13639               sema::DelayedDiagnostic::makeForbiddenType(
13640               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13641         else
13642           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13643               << TSInfo->getTypeLoc().getSourceRange();
13644       }
13645       lifetime = Qualifiers::OCL_ExplicitNone;
13646     } else {
13647       lifetime = T->getObjCARCImplicitLifetime();
13648     }
13649     T = Context.getLifetimeQualifiedType(T, lifetime);
13650   }
13651 
13652   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13653                                          Context.getAdjustedParameterType(T),
13654                                          TSInfo, SC, nullptr);
13655 
13656   // Make a note if we created a new pack in the scope of a lambda, so that
13657   // we know that references to that pack must also be expanded within the
13658   // lambda scope.
13659   if (New->isParameterPack())
13660     if (auto *LSI = getEnclosingLambda())
13661       LSI->LocalPacks.push_back(New);
13662 
13663   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13664       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13665     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13666                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13667 
13668   // Parameters can not be abstract class types.
13669   // For record types, this is done by the AbstractClassUsageDiagnoser once
13670   // the class has been completely parsed.
13671   if (!CurContext->isRecord() &&
13672       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13673                              AbstractParamType))
13674     New->setInvalidDecl();
13675 
13676   // Parameter declarators cannot be interface types. All ObjC objects are
13677   // passed by reference.
13678   if (T->isObjCObjectType()) {
13679     SourceLocation TypeEndLoc =
13680         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13681     Diag(NameLoc,
13682          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13683       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13684     T = Context.getObjCObjectPointerType(T);
13685     New->setType(T);
13686   }
13687 
13688   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13689   // duration shall not be qualified by an address-space qualifier."
13690   // Since all parameters have automatic store duration, they can not have
13691   // an address space.
13692   if (T.getAddressSpace() != LangAS::Default &&
13693       // OpenCL allows function arguments declared to be an array of a type
13694       // to be qualified with an address space.
13695       !(getLangOpts().OpenCL &&
13696         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13697     Diag(NameLoc, diag::err_arg_with_address_space);
13698     New->setInvalidDecl();
13699   }
13700 
13701   return New;
13702 }
13703 
13704 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13705                                            SourceLocation LocAfterDecls) {
13706   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13707 
13708   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13709   // for a K&R function.
13710   if (!FTI.hasPrototype) {
13711     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13712       --i;
13713       if (FTI.Params[i].Param == nullptr) {
13714         SmallString<256> Code;
13715         llvm::raw_svector_ostream(Code)
13716             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13717         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13718             << FTI.Params[i].Ident
13719             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13720 
13721         // Implicitly declare the argument as type 'int' for lack of a better
13722         // type.
13723         AttributeFactory attrs;
13724         DeclSpec DS(attrs);
13725         const char* PrevSpec; // unused
13726         unsigned DiagID; // unused
13727         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13728                            DiagID, Context.getPrintingPolicy());
13729         // Use the identifier location for the type source range.
13730         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13731         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13732         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13733         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13734         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13735       }
13736     }
13737   }
13738 }
13739 
13740 Decl *
13741 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13742                               MultiTemplateParamsArg TemplateParameterLists,
13743                               SkipBodyInfo *SkipBody) {
13744   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13745   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13746   Scope *ParentScope = FnBodyScope->getParent();
13747 
13748   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13749   // we define a non-templated function definition, we will create a declaration
13750   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13751   // The base function declaration will have the equivalent of an `omp declare
13752   // variant` annotation which specifies the mangled definition as a
13753   // specialization function under the OpenMP context defined as part of the
13754   // `omp begin declare variant`.
13755   FunctionDecl *BaseFD = nullptr;
13756   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13757       TemplateParameterLists.empty())
13758     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13759         ParentScope, D);
13760 
13761   D.setFunctionDefinitionKind(FDK_Definition);
13762   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13763   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13764 
13765   if (BaseFD)
13766     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13767         cast<FunctionDecl>(Dcl), BaseFD);
13768 
13769   return Dcl;
13770 }
13771 
13772 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13773   Consumer.HandleInlineFunctionDefinition(D);
13774 }
13775 
13776 static bool
13777 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13778                                 const FunctionDecl *&PossiblePrototype) {
13779   // Don't warn about invalid declarations.
13780   if (FD->isInvalidDecl())
13781     return false;
13782 
13783   // Or declarations that aren't global.
13784   if (!FD->isGlobal())
13785     return false;
13786 
13787   // Don't warn about C++ member functions.
13788   if (isa<CXXMethodDecl>(FD))
13789     return false;
13790 
13791   // Don't warn about 'main'.
13792   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13793     if (IdentifierInfo *II = FD->getIdentifier())
13794       if (II->isStr("main"))
13795         return false;
13796 
13797   // Don't warn about inline functions.
13798   if (FD->isInlined())
13799     return false;
13800 
13801   // Don't warn about function templates.
13802   if (FD->getDescribedFunctionTemplate())
13803     return false;
13804 
13805   // Don't warn about function template specializations.
13806   if (FD->isFunctionTemplateSpecialization())
13807     return false;
13808 
13809   // Don't warn for OpenCL kernels.
13810   if (FD->hasAttr<OpenCLKernelAttr>())
13811     return false;
13812 
13813   // Don't warn on explicitly deleted functions.
13814   if (FD->isDeleted())
13815     return false;
13816 
13817   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13818        Prev; Prev = Prev->getPreviousDecl()) {
13819     // Ignore any declarations that occur in function or method
13820     // scope, because they aren't visible from the header.
13821     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13822       continue;
13823 
13824     PossiblePrototype = Prev;
13825     return Prev->getType()->isFunctionNoProtoType();
13826   }
13827 
13828   return true;
13829 }
13830 
13831 void
13832 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13833                                    const FunctionDecl *EffectiveDefinition,
13834                                    SkipBodyInfo *SkipBody) {
13835   const FunctionDecl *Definition = EffectiveDefinition;
13836   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13837     // If this is a friend function defined in a class template, it does not
13838     // have a body until it is used, nevertheless it is a definition, see
13839     // [temp.inst]p2:
13840     //
13841     // ... for the purpose of determining whether an instantiated redeclaration
13842     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13843     // corresponds to a definition in the template is considered to be a
13844     // definition.
13845     //
13846     // The following code must produce redefinition error:
13847     //
13848     //     template<typename T> struct C20 { friend void func_20() {} };
13849     //     C20<int> c20i;
13850     //     void func_20() {}
13851     //
13852     for (auto I : FD->redecls()) {
13853       if (I != FD && !I->isInvalidDecl() &&
13854           I->getFriendObjectKind() != Decl::FOK_None) {
13855         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13856           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13857             // A merged copy of the same function, instantiated as a member of
13858             // the same class, is OK.
13859             if (declaresSameEntity(OrigFD, Original) &&
13860                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13861                                    cast<Decl>(FD->getLexicalDeclContext())))
13862               continue;
13863           }
13864 
13865           if (Original->isThisDeclarationADefinition()) {
13866             Definition = I;
13867             break;
13868           }
13869         }
13870       }
13871     }
13872   }
13873 
13874   if (!Definition)
13875     // Similar to friend functions a friend function template may be a
13876     // definition and do not have a body if it is instantiated in a class
13877     // template.
13878     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13879       for (auto I : FTD->redecls()) {
13880         auto D = cast<FunctionTemplateDecl>(I);
13881         if (D != FTD) {
13882           assert(!D->isThisDeclarationADefinition() &&
13883                  "More than one definition in redeclaration chain");
13884           if (D->getFriendObjectKind() != Decl::FOK_None)
13885             if (FunctionTemplateDecl *FT =
13886                                        D->getInstantiatedFromMemberTemplate()) {
13887               if (FT->isThisDeclarationADefinition()) {
13888                 Definition = D->getTemplatedDecl();
13889                 break;
13890               }
13891             }
13892         }
13893       }
13894     }
13895 
13896   if (!Definition)
13897     return;
13898 
13899   if (canRedefineFunction(Definition, getLangOpts()))
13900     return;
13901 
13902   // Don't emit an error when this is redefinition of a typo-corrected
13903   // definition.
13904   if (TypoCorrectedFunctionDefinitions.count(Definition))
13905     return;
13906 
13907   // If we don't have a visible definition of the function, and it's inline or
13908   // a template, skip the new definition.
13909   if (SkipBody && !hasVisibleDefinition(Definition) &&
13910       (Definition->getFormalLinkage() == InternalLinkage ||
13911        Definition->isInlined() ||
13912        Definition->getDescribedFunctionTemplate() ||
13913        Definition->getNumTemplateParameterLists())) {
13914     SkipBody->ShouldSkip = true;
13915     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13916     if (auto *TD = Definition->getDescribedFunctionTemplate())
13917       makeMergedDefinitionVisible(TD);
13918     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13919     return;
13920   }
13921 
13922   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13923       Definition->getStorageClass() == SC_Extern)
13924     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13925         << FD << getLangOpts().CPlusPlus;
13926   else
13927     Diag(FD->getLocation(), diag::err_redefinition) << FD;
13928 
13929   Diag(Definition->getLocation(), diag::note_previous_definition);
13930   FD->setInvalidDecl();
13931 }
13932 
13933 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13934                                    Sema &S) {
13935   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13936 
13937   LambdaScopeInfo *LSI = S.PushLambdaScope();
13938   LSI->CallOperator = CallOperator;
13939   LSI->Lambda = LambdaClass;
13940   LSI->ReturnType = CallOperator->getReturnType();
13941   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13942 
13943   if (LCD == LCD_None)
13944     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13945   else if (LCD == LCD_ByCopy)
13946     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13947   else if (LCD == LCD_ByRef)
13948     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13949   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13950 
13951   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13952   LSI->Mutable = !CallOperator->isConst();
13953 
13954   // Add the captures to the LSI so they can be noted as already
13955   // captured within tryCaptureVar.
13956   auto I = LambdaClass->field_begin();
13957   for (const auto &C : LambdaClass->captures()) {
13958     if (C.capturesVariable()) {
13959       VarDecl *VD = C.getCapturedVar();
13960       if (VD->isInitCapture())
13961         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13962       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13963       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13964           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13965           /*EllipsisLoc*/C.isPackExpansion()
13966                          ? C.getEllipsisLoc() : SourceLocation(),
13967           I->getType(), /*Invalid*/false);
13968 
13969     } else if (C.capturesThis()) {
13970       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13971                           C.getCaptureKind() == LCK_StarThis);
13972     } else {
13973       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13974                              I->getType());
13975     }
13976     ++I;
13977   }
13978 }
13979 
13980 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13981                                     SkipBodyInfo *SkipBody) {
13982   if (!D) {
13983     // Parsing the function declaration failed in some way. Push on a fake scope
13984     // anyway so we can try to parse the function body.
13985     PushFunctionScope();
13986     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13987     return D;
13988   }
13989 
13990   FunctionDecl *FD = nullptr;
13991 
13992   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13993     FD = FunTmpl->getTemplatedDecl();
13994   else
13995     FD = cast<FunctionDecl>(D);
13996 
13997   // Do not push if it is a lambda because one is already pushed when building
13998   // the lambda in ActOnStartOfLambdaDefinition().
13999   if (!isLambdaCallOperator(FD))
14000     PushExpressionEvaluationContext(
14001         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14002                           : ExprEvalContexts.back().Context);
14003 
14004   // Check for defining attributes before the check for redefinition.
14005   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14006     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14007     FD->dropAttr<AliasAttr>();
14008     FD->setInvalidDecl();
14009   }
14010   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14011     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14012     FD->dropAttr<IFuncAttr>();
14013     FD->setInvalidDecl();
14014   }
14015 
14016   // See if this is a redefinition. If 'will have body' is already set, then
14017   // these checks were already performed when it was set.
14018   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
14019     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14020 
14021     // If we're skipping the body, we're done. Don't enter the scope.
14022     if (SkipBody && SkipBody->ShouldSkip)
14023       return D;
14024   }
14025 
14026   // Mark this function as "will have a body eventually".  This lets users to
14027   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14028   // this function.
14029   FD->setWillHaveBody();
14030 
14031   // If we are instantiating a generic lambda call operator, push
14032   // a LambdaScopeInfo onto the function stack.  But use the information
14033   // that's already been calculated (ActOnLambdaExpr) to prime the current
14034   // LambdaScopeInfo.
14035   // When the template operator is being specialized, the LambdaScopeInfo,
14036   // has to be properly restored so that tryCaptureVariable doesn't try
14037   // and capture any new variables. In addition when calculating potential
14038   // captures during transformation of nested lambdas, it is necessary to
14039   // have the LSI properly restored.
14040   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14041     assert(inTemplateInstantiation() &&
14042            "There should be an active template instantiation on the stack "
14043            "when instantiating a generic lambda!");
14044     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14045   } else {
14046     // Enter a new function scope
14047     PushFunctionScope();
14048   }
14049 
14050   // Builtin functions cannot be defined.
14051   if (unsigned BuiltinID = FD->getBuiltinID()) {
14052     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14053         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14054       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14055       FD->setInvalidDecl();
14056     }
14057   }
14058 
14059   // The return type of a function definition must be complete
14060   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14061   QualType ResultType = FD->getReturnType();
14062   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14063       !FD->isInvalidDecl() &&
14064       RequireCompleteType(FD->getLocation(), ResultType,
14065                           diag::err_func_def_incomplete_result))
14066     FD->setInvalidDecl();
14067 
14068   if (FnBodyScope)
14069     PushDeclContext(FnBodyScope, FD);
14070 
14071   // Check the validity of our function parameters
14072   CheckParmsForFunctionDef(FD->parameters(),
14073                            /*CheckParameterNames=*/true);
14074 
14075   // Add non-parameter declarations already in the function to the current
14076   // scope.
14077   if (FnBodyScope) {
14078     for (Decl *NPD : FD->decls()) {
14079       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14080       if (!NonParmDecl)
14081         continue;
14082       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14083              "parameters should not be in newly created FD yet");
14084 
14085       // If the decl has a name, make it accessible in the current scope.
14086       if (NonParmDecl->getDeclName())
14087         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14088 
14089       // Similarly, dive into enums and fish their constants out, making them
14090       // accessible in this scope.
14091       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14092         for (auto *EI : ED->enumerators())
14093           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14094       }
14095     }
14096   }
14097 
14098   // Introduce our parameters into the function scope
14099   for (auto Param : FD->parameters()) {
14100     Param->setOwningFunction(FD);
14101 
14102     // If this has an identifier, add it to the scope stack.
14103     if (Param->getIdentifier() && FnBodyScope) {
14104       CheckShadow(FnBodyScope, Param);
14105 
14106       PushOnScopeChains(Param, FnBodyScope);
14107     }
14108   }
14109 
14110   // Ensure that the function's exception specification is instantiated.
14111   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14112     ResolveExceptionSpec(D->getLocation(), FPT);
14113 
14114   // dllimport cannot be applied to non-inline function definitions.
14115   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14116       !FD->isTemplateInstantiation()) {
14117     assert(!FD->hasAttr<DLLExportAttr>());
14118     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14119     FD->setInvalidDecl();
14120     return D;
14121   }
14122   // We want to attach documentation to original Decl (which might be
14123   // a function template).
14124   ActOnDocumentableDecl(D);
14125   if (getCurLexicalContext()->isObjCContainer() &&
14126       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14127       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14128     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14129 
14130   return D;
14131 }
14132 
14133 /// Given the set of return statements within a function body,
14134 /// compute the variables that are subject to the named return value
14135 /// optimization.
14136 ///
14137 /// Each of the variables that is subject to the named return value
14138 /// optimization will be marked as NRVO variables in the AST, and any
14139 /// return statement that has a marked NRVO variable as its NRVO candidate can
14140 /// use the named return value optimization.
14141 ///
14142 /// This function applies a very simplistic algorithm for NRVO: if every return
14143 /// statement in the scope of a variable has the same NRVO candidate, that
14144 /// candidate is an NRVO variable.
14145 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14146   ReturnStmt **Returns = Scope->Returns.data();
14147 
14148   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14149     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14150       if (!NRVOCandidate->isNRVOVariable())
14151         Returns[I]->setNRVOCandidate(nullptr);
14152     }
14153   }
14154 }
14155 
14156 bool Sema::canDelayFunctionBody(const Declarator &D) {
14157   // We can't delay parsing the body of a constexpr function template (yet).
14158   if (D.getDeclSpec().hasConstexprSpecifier())
14159     return false;
14160 
14161   // We can't delay parsing the body of a function template with a deduced
14162   // return type (yet).
14163   if (D.getDeclSpec().hasAutoTypeSpec()) {
14164     // If the placeholder introduces a non-deduced trailing return type,
14165     // we can still delay parsing it.
14166     if (D.getNumTypeObjects()) {
14167       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14168       if (Outer.Kind == DeclaratorChunk::Function &&
14169           Outer.Fun.hasTrailingReturnType()) {
14170         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14171         return Ty.isNull() || !Ty->isUndeducedType();
14172       }
14173     }
14174     return false;
14175   }
14176 
14177   return true;
14178 }
14179 
14180 bool Sema::canSkipFunctionBody(Decl *D) {
14181   // We cannot skip the body of a function (or function template) which is
14182   // constexpr, since we may need to evaluate its body in order to parse the
14183   // rest of the file.
14184   // We cannot skip the body of a function with an undeduced return type,
14185   // because any callers of that function need to know the type.
14186   if (const FunctionDecl *FD = D->getAsFunction()) {
14187     if (FD->isConstexpr())
14188       return false;
14189     // We can't simply call Type::isUndeducedType here, because inside template
14190     // auto can be deduced to a dependent type, which is not considered
14191     // "undeduced".
14192     if (FD->getReturnType()->getContainedDeducedType())
14193       return false;
14194   }
14195   return Consumer.shouldSkipFunctionBody(D);
14196 }
14197 
14198 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14199   if (!Decl)
14200     return nullptr;
14201   if (FunctionDecl *FD = Decl->getAsFunction())
14202     FD->setHasSkippedBody();
14203   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14204     MD->setHasSkippedBody();
14205   return Decl;
14206 }
14207 
14208 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14209   return ActOnFinishFunctionBody(D, BodyArg, false);
14210 }
14211 
14212 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14213 /// body.
14214 class ExitFunctionBodyRAII {
14215 public:
14216   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14217   ~ExitFunctionBodyRAII() {
14218     if (!IsLambda)
14219       S.PopExpressionEvaluationContext();
14220   }
14221 
14222 private:
14223   Sema &S;
14224   bool IsLambda = false;
14225 };
14226 
14227 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14228   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14229 
14230   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14231     if (EscapeInfo.count(BD))
14232       return EscapeInfo[BD];
14233 
14234     bool R = false;
14235     const BlockDecl *CurBD = BD;
14236 
14237     do {
14238       R = !CurBD->doesNotEscape();
14239       if (R)
14240         break;
14241       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14242     } while (CurBD);
14243 
14244     return EscapeInfo[BD] = R;
14245   };
14246 
14247   // If the location where 'self' is implicitly retained is inside a escaping
14248   // block, emit a diagnostic.
14249   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14250        S.ImplicitlyRetainedSelfLocs)
14251     if (IsOrNestedInEscapingBlock(P.second))
14252       S.Diag(P.first, diag::warn_implicitly_retains_self)
14253           << FixItHint::CreateInsertion(P.first, "self->");
14254 }
14255 
14256 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14257                                     bool IsInstantiation) {
14258   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14259 
14260   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14261   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14262 
14263   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14264     CheckCompletedCoroutineBody(FD, Body);
14265 
14266   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14267   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14268   // meant to pop the context added in ActOnStartOfFunctionDef().
14269   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14270 
14271   if (FD) {
14272     FD->setBody(Body);
14273     FD->setWillHaveBody(false);
14274 
14275     if (getLangOpts().CPlusPlus14) {
14276       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14277           FD->getReturnType()->isUndeducedType()) {
14278         // If the function has a deduced result type but contains no 'return'
14279         // statements, the result type as written must be exactly 'auto', and
14280         // the deduced result type is 'void'.
14281         if (!FD->getReturnType()->getAs<AutoType>()) {
14282           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14283               << FD->getReturnType();
14284           FD->setInvalidDecl();
14285         } else {
14286           // Substitute 'void' for the 'auto' in the type.
14287           TypeLoc ResultType = getReturnTypeLoc(FD);
14288           Context.adjustDeducedFunctionResultType(
14289               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14290         }
14291       }
14292     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14293       // In C++11, we don't use 'auto' deduction rules for lambda call
14294       // operators because we don't support return type deduction.
14295       auto *LSI = getCurLambda();
14296       if (LSI->HasImplicitReturnType) {
14297         deduceClosureReturnType(*LSI);
14298 
14299         // C++11 [expr.prim.lambda]p4:
14300         //   [...] if there are no return statements in the compound-statement
14301         //   [the deduced type is] the type void
14302         QualType RetType =
14303             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14304 
14305         // Update the return type to the deduced type.
14306         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14307         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14308                                             Proto->getExtProtoInfo()));
14309       }
14310     }
14311 
14312     // If the function implicitly returns zero (like 'main') or is naked,
14313     // don't complain about missing return statements.
14314     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14315       WP.disableCheckFallThrough();
14316 
14317     // MSVC permits the use of pure specifier (=0) on function definition,
14318     // defined at class scope, warn about this non-standard construct.
14319     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14320       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14321 
14322     if (!FD->isInvalidDecl()) {
14323       // Don't diagnose unused parameters of defaulted or deleted functions.
14324       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14325         DiagnoseUnusedParameters(FD->parameters());
14326       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14327                                              FD->getReturnType(), FD);
14328 
14329       // If this is a structor, we need a vtable.
14330       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14331         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14332       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14333         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14334 
14335       // Try to apply the named return value optimization. We have to check
14336       // if we can do this here because lambdas keep return statements around
14337       // to deduce an implicit return type.
14338       if (FD->getReturnType()->isRecordType() &&
14339           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14340         computeNRVO(Body, getCurFunction());
14341     }
14342 
14343     // GNU warning -Wmissing-prototypes:
14344     //   Warn if a global function is defined without a previous
14345     //   prototype declaration. This warning is issued even if the
14346     //   definition itself provides a prototype. The aim is to detect
14347     //   global functions that fail to be declared in header files.
14348     const FunctionDecl *PossiblePrototype = nullptr;
14349     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14350       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14351 
14352       if (PossiblePrototype) {
14353         // We found a declaration that is not a prototype,
14354         // but that could be a zero-parameter prototype
14355         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14356           TypeLoc TL = TI->getTypeLoc();
14357           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14358             Diag(PossiblePrototype->getLocation(),
14359                  diag::note_declaration_not_a_prototype)
14360                 << (FD->getNumParams() != 0)
14361                 << (FD->getNumParams() == 0
14362                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14363                         : FixItHint{});
14364         }
14365       } else {
14366         // Returns true if the token beginning at this Loc is `const`.
14367         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14368                                 const LangOptions &LangOpts) {
14369           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14370           if (LocInfo.first.isInvalid())
14371             return false;
14372 
14373           bool Invalid = false;
14374           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14375           if (Invalid)
14376             return false;
14377 
14378           if (LocInfo.second > Buffer.size())
14379             return false;
14380 
14381           const char *LexStart = Buffer.data() + LocInfo.second;
14382           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14383 
14384           return StartTok.consume_front("const") &&
14385                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14386                   StartTok.startswith("/*") || StartTok.startswith("//"));
14387         };
14388 
14389         auto findBeginLoc = [&]() {
14390           // If the return type has `const` qualifier, we want to insert
14391           // `static` before `const` (and not before the typename).
14392           if ((FD->getReturnType()->isAnyPointerType() &&
14393                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14394               FD->getReturnType().isConstQualified()) {
14395             // But only do this if we can determine where the `const` is.
14396 
14397             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14398                              getLangOpts()))
14399 
14400               return FD->getBeginLoc();
14401           }
14402           return FD->getTypeSpecStartLoc();
14403         };
14404         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14405             << /* function */ 1
14406             << (FD->getStorageClass() == SC_None
14407                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14408                     : FixItHint{});
14409       }
14410 
14411       // GNU warning -Wstrict-prototypes
14412       //   Warn if K&R function is defined without a previous declaration.
14413       //   This warning is issued only if the definition itself does not provide
14414       //   a prototype. Only K&R definitions do not provide a prototype.
14415       if (!FD->hasWrittenPrototype()) {
14416         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14417         TypeLoc TL = TI->getTypeLoc();
14418         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14419         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14420       }
14421     }
14422 
14423     // Warn on CPUDispatch with an actual body.
14424     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14425       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14426         if (!CmpndBody->body_empty())
14427           Diag(CmpndBody->body_front()->getBeginLoc(),
14428                diag::warn_dispatch_body_ignored);
14429 
14430     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14431       const CXXMethodDecl *KeyFunction;
14432       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14433           MD->isVirtual() &&
14434           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14435           MD == KeyFunction->getCanonicalDecl()) {
14436         // Update the key-function state if necessary for this ABI.
14437         if (FD->isInlined() &&
14438             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14439           Context.setNonKeyFunction(MD);
14440 
14441           // If the newly-chosen key function is already defined, then we
14442           // need to mark the vtable as used retroactively.
14443           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14444           const FunctionDecl *Definition;
14445           if (KeyFunction && KeyFunction->isDefined(Definition))
14446             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14447         } else {
14448           // We just defined they key function; mark the vtable as used.
14449           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14450         }
14451       }
14452     }
14453 
14454     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14455            "Function parsing confused");
14456   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14457     assert(MD == getCurMethodDecl() && "Method parsing confused");
14458     MD->setBody(Body);
14459     if (!MD->isInvalidDecl()) {
14460       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14461                                              MD->getReturnType(), MD);
14462 
14463       if (Body)
14464         computeNRVO(Body, getCurFunction());
14465     }
14466     if (getCurFunction()->ObjCShouldCallSuper) {
14467       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14468           << MD->getSelector().getAsString();
14469       getCurFunction()->ObjCShouldCallSuper = false;
14470     }
14471     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14472       const ObjCMethodDecl *InitMethod = nullptr;
14473       bool isDesignated =
14474           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14475       assert(isDesignated && InitMethod);
14476       (void)isDesignated;
14477 
14478       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14479         auto IFace = MD->getClassInterface();
14480         if (!IFace)
14481           return false;
14482         auto SuperD = IFace->getSuperClass();
14483         if (!SuperD)
14484           return false;
14485         return SuperD->getIdentifier() ==
14486             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14487       };
14488       // Don't issue this warning for unavailable inits or direct subclasses
14489       // of NSObject.
14490       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14491         Diag(MD->getLocation(),
14492              diag::warn_objc_designated_init_missing_super_call);
14493         Diag(InitMethod->getLocation(),
14494              diag::note_objc_designated_init_marked_here);
14495       }
14496       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14497     }
14498     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14499       // Don't issue this warning for unavaialable inits.
14500       if (!MD->isUnavailable())
14501         Diag(MD->getLocation(),
14502              diag::warn_objc_secondary_init_missing_init_call);
14503       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14504     }
14505 
14506     diagnoseImplicitlyRetainedSelf(*this);
14507   } else {
14508     // Parsing the function declaration failed in some way. Pop the fake scope
14509     // we pushed on.
14510     PopFunctionScopeInfo(ActivePolicy, dcl);
14511     return nullptr;
14512   }
14513 
14514   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14515     DiagnoseUnguardedAvailabilityViolations(dcl);
14516 
14517   assert(!getCurFunction()->ObjCShouldCallSuper &&
14518          "This should only be set for ObjC methods, which should have been "
14519          "handled in the block above.");
14520 
14521   // Verify and clean out per-function state.
14522   if (Body && (!FD || !FD->isDefaulted())) {
14523     // C++ constructors that have function-try-blocks can't have return
14524     // statements in the handlers of that block. (C++ [except.handle]p14)
14525     // Verify this.
14526     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14527       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14528 
14529     // Verify that gotos and switch cases don't jump into scopes illegally.
14530     if (getCurFunction()->NeedsScopeChecking() &&
14531         !PP.isCodeCompletionEnabled())
14532       DiagnoseInvalidJumps(Body);
14533 
14534     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14535       if (!Destructor->getParent()->isDependentType())
14536         CheckDestructor(Destructor);
14537 
14538       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14539                                              Destructor->getParent());
14540     }
14541 
14542     // If any errors have occurred, clear out any temporaries that may have
14543     // been leftover. This ensures that these temporaries won't be picked up for
14544     // deletion in some later function.
14545     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14546         getDiagnostics().getSuppressAllDiagnostics()) {
14547       DiscardCleanupsInEvaluationContext();
14548     }
14549     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14550         !isa<FunctionTemplateDecl>(dcl)) {
14551       // Since the body is valid, issue any analysis-based warnings that are
14552       // enabled.
14553       ActivePolicy = &WP;
14554     }
14555 
14556     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14557         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14558       FD->setInvalidDecl();
14559 
14560     if (FD && FD->hasAttr<NakedAttr>()) {
14561       for (const Stmt *S : Body->children()) {
14562         // Allow local register variables without initializer as they don't
14563         // require prologue.
14564         bool RegisterVariables = false;
14565         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14566           for (const auto *Decl : DS->decls()) {
14567             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14568               RegisterVariables =
14569                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14570               if (!RegisterVariables)
14571                 break;
14572             }
14573           }
14574         }
14575         if (RegisterVariables)
14576           continue;
14577         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14578           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14579           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14580           FD->setInvalidDecl();
14581           break;
14582         }
14583       }
14584     }
14585 
14586     assert(ExprCleanupObjects.size() ==
14587                ExprEvalContexts.back().NumCleanupObjects &&
14588            "Leftover temporaries in function");
14589     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14590     assert(MaybeODRUseExprs.empty() &&
14591            "Leftover expressions for odr-use checking");
14592   }
14593 
14594   if (!IsInstantiation)
14595     PopDeclContext();
14596 
14597   PopFunctionScopeInfo(ActivePolicy, dcl);
14598   // If any errors have occurred, clear out any temporaries that may have
14599   // been leftover. This ensures that these temporaries won't be picked up for
14600   // deletion in some later function.
14601   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14602     DiscardCleanupsInEvaluationContext();
14603   }
14604 
14605   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14606     auto ES = getEmissionStatus(FD);
14607     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14608         ES == Sema::FunctionEmissionStatus::Unknown)
14609       DeclsToCheckForDeferredDiags.push_back(FD);
14610   }
14611 
14612   return dcl;
14613 }
14614 
14615 /// When we finish delayed parsing of an attribute, we must attach it to the
14616 /// relevant Decl.
14617 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14618                                        ParsedAttributes &Attrs) {
14619   // Always attach attributes to the underlying decl.
14620   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14621     D = TD->getTemplatedDecl();
14622   ProcessDeclAttributeList(S, D, Attrs);
14623 
14624   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14625     if (Method->isStatic())
14626       checkThisInStaticMemberFunctionAttributes(Method);
14627 }
14628 
14629 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14630 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14631 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14632                                           IdentifierInfo &II, Scope *S) {
14633   // Find the scope in which the identifier is injected and the corresponding
14634   // DeclContext.
14635   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14636   // In that case, we inject the declaration into the translation unit scope
14637   // instead.
14638   Scope *BlockScope = S;
14639   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14640     BlockScope = BlockScope->getParent();
14641 
14642   Scope *ContextScope = BlockScope;
14643   while (!ContextScope->getEntity())
14644     ContextScope = ContextScope->getParent();
14645   ContextRAII SavedContext(*this, ContextScope->getEntity());
14646 
14647   // Before we produce a declaration for an implicitly defined
14648   // function, see whether there was a locally-scoped declaration of
14649   // this name as a function or variable. If so, use that
14650   // (non-visible) declaration, and complain about it.
14651   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14652   if (ExternCPrev) {
14653     // We still need to inject the function into the enclosing block scope so
14654     // that later (non-call) uses can see it.
14655     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14656 
14657     // C89 footnote 38:
14658     //   If in fact it is not defined as having type "function returning int",
14659     //   the behavior is undefined.
14660     if (!isa<FunctionDecl>(ExternCPrev) ||
14661         !Context.typesAreCompatible(
14662             cast<FunctionDecl>(ExternCPrev)->getType(),
14663             Context.getFunctionNoProtoType(Context.IntTy))) {
14664       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14665           << ExternCPrev << !getLangOpts().C99;
14666       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14667       return ExternCPrev;
14668     }
14669   }
14670 
14671   // Extension in C99.  Legal in C90, but warn about it.
14672   unsigned diag_id;
14673   if (II.getName().startswith("__builtin_"))
14674     diag_id = diag::warn_builtin_unknown;
14675   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14676   else if (getLangOpts().OpenCL)
14677     diag_id = diag::err_opencl_implicit_function_decl;
14678   else if (getLangOpts().C99)
14679     diag_id = diag::ext_implicit_function_decl;
14680   else
14681     diag_id = diag::warn_implicit_function_decl;
14682   Diag(Loc, diag_id) << &II;
14683 
14684   // If we found a prior declaration of this function, don't bother building
14685   // another one. We've already pushed that one into scope, so there's nothing
14686   // more to do.
14687   if (ExternCPrev)
14688     return ExternCPrev;
14689 
14690   // Because typo correction is expensive, only do it if the implicit
14691   // function declaration is going to be treated as an error.
14692   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14693     TypoCorrection Corrected;
14694     DeclFilterCCC<FunctionDecl> CCC{};
14695     if (S && (Corrected =
14696                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14697                               S, nullptr, CCC, CTK_NonError)))
14698       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14699                    /*ErrorRecovery*/false);
14700   }
14701 
14702   // Set a Declarator for the implicit definition: int foo();
14703   const char *Dummy;
14704   AttributeFactory attrFactory;
14705   DeclSpec DS(attrFactory);
14706   unsigned DiagID;
14707   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14708                                   Context.getPrintingPolicy());
14709   (void)Error; // Silence warning.
14710   assert(!Error && "Error setting up implicit decl!");
14711   SourceLocation NoLoc;
14712   Declarator D(DS, DeclaratorContext::BlockContext);
14713   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14714                                              /*IsAmbiguous=*/false,
14715                                              /*LParenLoc=*/NoLoc,
14716                                              /*Params=*/nullptr,
14717                                              /*NumParams=*/0,
14718                                              /*EllipsisLoc=*/NoLoc,
14719                                              /*RParenLoc=*/NoLoc,
14720                                              /*RefQualifierIsLvalueRef=*/true,
14721                                              /*RefQualifierLoc=*/NoLoc,
14722                                              /*MutableLoc=*/NoLoc, EST_None,
14723                                              /*ESpecRange=*/SourceRange(),
14724                                              /*Exceptions=*/nullptr,
14725                                              /*ExceptionRanges=*/nullptr,
14726                                              /*NumExceptions=*/0,
14727                                              /*NoexceptExpr=*/nullptr,
14728                                              /*ExceptionSpecTokens=*/nullptr,
14729                                              /*DeclsInPrototype=*/None, Loc,
14730                                              Loc, D),
14731                 std::move(DS.getAttributes()), SourceLocation());
14732   D.SetIdentifier(&II, Loc);
14733 
14734   // Insert this function into the enclosing block scope.
14735   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14736   FD->setImplicit();
14737 
14738   AddKnownFunctionAttributes(FD);
14739 
14740   return FD;
14741 }
14742 
14743 /// If this function is a C++ replaceable global allocation function
14744 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14745 /// adds any function attributes that we know a priori based on the standard.
14746 ///
14747 /// We need to check for duplicate attributes both here and where user-written
14748 /// attributes are applied to declarations.
14749 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14750     FunctionDecl *FD) {
14751   if (FD->isInvalidDecl())
14752     return;
14753 
14754   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14755       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14756     return;
14757 
14758   Optional<unsigned> AlignmentParam;
14759   bool IsNothrow = false;
14760   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14761     return;
14762 
14763   // C++2a [basic.stc.dynamic.allocation]p4:
14764   //   An allocation function that has a non-throwing exception specification
14765   //   indicates failure by returning a null pointer value. Any other allocation
14766   //   function never returns a null pointer value and indicates failure only by
14767   //   throwing an exception [...]
14768   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14769     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14770 
14771   // C++2a [basic.stc.dynamic.allocation]p2:
14772   //   An allocation function attempts to allocate the requested amount of
14773   //   storage. [...] If the request succeeds, the value returned by a
14774   //   replaceable allocation function is a [...] pointer value p0 different
14775   //   from any previously returned value p1 [...]
14776   //
14777   // However, this particular information is being added in codegen,
14778   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14779 
14780   // C++2a [basic.stc.dynamic.allocation]p2:
14781   //   An allocation function attempts to allocate the requested amount of
14782   //   storage. If it is successful, it returns the address of the start of a
14783   //   block of storage whose length in bytes is at least as large as the
14784   //   requested size.
14785   if (!FD->hasAttr<AllocSizeAttr>()) {
14786     FD->addAttr(AllocSizeAttr::CreateImplicit(
14787         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14788         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14789   }
14790 
14791   // C++2a [basic.stc.dynamic.allocation]p3:
14792   //   For an allocation function [...], the pointer returned on a successful
14793   //   call shall represent the address of storage that is aligned as follows:
14794   //   (3.1) If the allocation function takes an argument of type
14795   //         std​::​align_­val_­t, the storage will have the alignment
14796   //         specified by the value of this argument.
14797   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14798     FD->addAttr(AllocAlignAttr::CreateImplicit(
14799         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14800   }
14801 
14802   // FIXME:
14803   // C++2a [basic.stc.dynamic.allocation]p3:
14804   //   For an allocation function [...], the pointer returned on a successful
14805   //   call shall represent the address of storage that is aligned as follows:
14806   //   (3.2) Otherwise, if the allocation function is named operator new[],
14807   //         the storage is aligned for any object that does not have
14808   //         new-extended alignment ([basic.align]) and is no larger than the
14809   //         requested size.
14810   //   (3.3) Otherwise, the storage is aligned for any object that does not
14811   //         have new-extended alignment and is of the requested size.
14812 }
14813 
14814 /// Adds any function attributes that we know a priori based on
14815 /// the declaration of this function.
14816 ///
14817 /// These attributes can apply both to implicitly-declared builtins
14818 /// (like __builtin___printf_chk) or to library-declared functions
14819 /// like NSLog or printf.
14820 ///
14821 /// We need to check for duplicate attributes both here and where user-written
14822 /// attributes are applied to declarations.
14823 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14824   if (FD->isInvalidDecl())
14825     return;
14826 
14827   // If this is a built-in function, map its builtin attributes to
14828   // actual attributes.
14829   if (unsigned BuiltinID = FD->getBuiltinID()) {
14830     // Handle printf-formatting attributes.
14831     unsigned FormatIdx;
14832     bool HasVAListArg;
14833     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14834       if (!FD->hasAttr<FormatAttr>()) {
14835         const char *fmt = "printf";
14836         unsigned int NumParams = FD->getNumParams();
14837         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14838             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14839           fmt = "NSString";
14840         FD->addAttr(FormatAttr::CreateImplicit(Context,
14841                                                &Context.Idents.get(fmt),
14842                                                FormatIdx+1,
14843                                                HasVAListArg ? 0 : FormatIdx+2,
14844                                                FD->getLocation()));
14845       }
14846     }
14847     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14848                                              HasVAListArg)) {
14849      if (!FD->hasAttr<FormatAttr>())
14850        FD->addAttr(FormatAttr::CreateImplicit(Context,
14851                                               &Context.Idents.get("scanf"),
14852                                               FormatIdx+1,
14853                                               HasVAListArg ? 0 : FormatIdx+2,
14854                                               FD->getLocation()));
14855     }
14856 
14857     // Handle automatically recognized callbacks.
14858     SmallVector<int, 4> Encoding;
14859     if (!FD->hasAttr<CallbackAttr>() &&
14860         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14861       FD->addAttr(CallbackAttr::CreateImplicit(
14862           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14863 
14864     // Mark const if we don't care about errno and that is the only thing
14865     // preventing the function from being const. This allows IRgen to use LLVM
14866     // intrinsics for such functions.
14867     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14868         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14869       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14870 
14871     // We make "fma" on some platforms const because we know it does not set
14872     // errno in those environments even though it could set errno based on the
14873     // C standard.
14874     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14875     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14876         !FD->hasAttr<ConstAttr>()) {
14877       switch (BuiltinID) {
14878       case Builtin::BI__builtin_fma:
14879       case Builtin::BI__builtin_fmaf:
14880       case Builtin::BI__builtin_fmal:
14881       case Builtin::BIfma:
14882       case Builtin::BIfmaf:
14883       case Builtin::BIfmal:
14884         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14885         break;
14886       default:
14887         break;
14888       }
14889     }
14890 
14891     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14892         !FD->hasAttr<ReturnsTwiceAttr>())
14893       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14894                                          FD->getLocation()));
14895     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14896       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14897     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14898       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14899     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14900       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14901     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14902         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14903       // Add the appropriate attribute, depending on the CUDA compilation mode
14904       // and which target the builtin belongs to. For example, during host
14905       // compilation, aux builtins are __device__, while the rest are __host__.
14906       if (getLangOpts().CUDAIsDevice !=
14907           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14908         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14909       else
14910         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14911     }
14912   }
14913 
14914   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14915 
14916   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14917   // throw, add an implicit nothrow attribute to any extern "C" function we come
14918   // across.
14919   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14920       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14921     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14922     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14923       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14924   }
14925 
14926   IdentifierInfo *Name = FD->getIdentifier();
14927   if (!Name)
14928     return;
14929   if ((!getLangOpts().CPlusPlus &&
14930        FD->getDeclContext()->isTranslationUnit()) ||
14931       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14932        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14933        LinkageSpecDecl::lang_c)) {
14934     // Okay: this could be a libc/libm/Objective-C function we know
14935     // about.
14936   } else
14937     return;
14938 
14939   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14940     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14941     // target-specific builtins, perhaps?
14942     if (!FD->hasAttr<FormatAttr>())
14943       FD->addAttr(FormatAttr::CreateImplicit(Context,
14944                                              &Context.Idents.get("printf"), 2,
14945                                              Name->isStr("vasprintf") ? 0 : 3,
14946                                              FD->getLocation()));
14947   }
14948 
14949   if (Name->isStr("__CFStringMakeConstantString")) {
14950     // We already have a __builtin___CFStringMakeConstantString,
14951     // but builds that use -fno-constant-cfstrings don't go through that.
14952     if (!FD->hasAttr<FormatArgAttr>())
14953       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14954                                                 FD->getLocation()));
14955   }
14956 }
14957 
14958 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14959                                     TypeSourceInfo *TInfo) {
14960   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14961   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14962 
14963   if (!TInfo) {
14964     assert(D.isInvalidType() && "no declarator info for valid type");
14965     TInfo = Context.getTrivialTypeSourceInfo(T);
14966   }
14967 
14968   // Scope manipulation handled by caller.
14969   TypedefDecl *NewTD =
14970       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14971                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14972 
14973   // Bail out immediately if we have an invalid declaration.
14974   if (D.isInvalidType()) {
14975     NewTD->setInvalidDecl();
14976     return NewTD;
14977   }
14978 
14979   if (D.getDeclSpec().isModulePrivateSpecified()) {
14980     if (CurContext->isFunctionOrMethod())
14981       Diag(NewTD->getLocation(), diag::err_module_private_local)
14982           << 2 << NewTD
14983           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14984           << FixItHint::CreateRemoval(
14985                  D.getDeclSpec().getModulePrivateSpecLoc());
14986     else
14987       NewTD->setModulePrivate();
14988   }
14989 
14990   // C++ [dcl.typedef]p8:
14991   //   If the typedef declaration defines an unnamed class (or
14992   //   enum), the first typedef-name declared by the declaration
14993   //   to be that class type (or enum type) is used to denote the
14994   //   class type (or enum type) for linkage purposes only.
14995   // We need to check whether the type was declared in the declaration.
14996   switch (D.getDeclSpec().getTypeSpecType()) {
14997   case TST_enum:
14998   case TST_struct:
14999   case TST_interface:
15000   case TST_union:
15001   case TST_class: {
15002     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15003     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15004     break;
15005   }
15006 
15007   default:
15008     break;
15009   }
15010 
15011   return NewTD;
15012 }
15013 
15014 /// Check that this is a valid underlying type for an enum declaration.
15015 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15016   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15017   QualType T = TI->getType();
15018 
15019   if (T->isDependentType())
15020     return false;
15021 
15022   // This doesn't use 'isIntegralType' despite the error message mentioning
15023   // integral type because isIntegralType would also allow enum types in C.
15024   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15025     if (BT->isInteger())
15026       return false;
15027 
15028   if (T->isExtIntType())
15029     return false;
15030 
15031   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15032 }
15033 
15034 /// Check whether this is a valid redeclaration of a previous enumeration.
15035 /// \return true if the redeclaration was invalid.
15036 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15037                                   QualType EnumUnderlyingTy, bool IsFixed,
15038                                   const EnumDecl *Prev) {
15039   if (IsScoped != Prev->isScoped()) {
15040     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15041       << Prev->isScoped();
15042     Diag(Prev->getLocation(), diag::note_previous_declaration);
15043     return true;
15044   }
15045 
15046   if (IsFixed && Prev->isFixed()) {
15047     if (!EnumUnderlyingTy->isDependentType() &&
15048         !Prev->getIntegerType()->isDependentType() &&
15049         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15050                                         Prev->getIntegerType())) {
15051       // TODO: Highlight the underlying type of the redeclaration.
15052       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15053         << EnumUnderlyingTy << Prev->getIntegerType();
15054       Diag(Prev->getLocation(), diag::note_previous_declaration)
15055           << Prev->getIntegerTypeRange();
15056       return true;
15057     }
15058   } else if (IsFixed != Prev->isFixed()) {
15059     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15060       << Prev->isFixed();
15061     Diag(Prev->getLocation(), diag::note_previous_declaration);
15062     return true;
15063   }
15064 
15065   return false;
15066 }
15067 
15068 /// Get diagnostic %select index for tag kind for
15069 /// redeclaration diagnostic message.
15070 /// WARNING: Indexes apply to particular diagnostics only!
15071 ///
15072 /// \returns diagnostic %select index.
15073 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15074   switch (Tag) {
15075   case TTK_Struct: return 0;
15076   case TTK_Interface: return 1;
15077   case TTK_Class:  return 2;
15078   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15079   }
15080 }
15081 
15082 /// Determine if tag kind is a class-key compatible with
15083 /// class for redeclaration (class, struct, or __interface).
15084 ///
15085 /// \returns true iff the tag kind is compatible.
15086 static bool isClassCompatTagKind(TagTypeKind Tag)
15087 {
15088   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15089 }
15090 
15091 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15092                                              TagTypeKind TTK) {
15093   if (isa<TypedefDecl>(PrevDecl))
15094     return NTK_Typedef;
15095   else if (isa<TypeAliasDecl>(PrevDecl))
15096     return NTK_TypeAlias;
15097   else if (isa<ClassTemplateDecl>(PrevDecl))
15098     return NTK_Template;
15099   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15100     return NTK_TypeAliasTemplate;
15101   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15102     return NTK_TemplateTemplateArgument;
15103   switch (TTK) {
15104   case TTK_Struct:
15105   case TTK_Interface:
15106   case TTK_Class:
15107     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15108   case TTK_Union:
15109     return NTK_NonUnion;
15110   case TTK_Enum:
15111     return NTK_NonEnum;
15112   }
15113   llvm_unreachable("invalid TTK");
15114 }
15115 
15116 /// Determine whether a tag with a given kind is acceptable
15117 /// as a redeclaration of the given tag declaration.
15118 ///
15119 /// \returns true if the new tag kind is acceptable, false otherwise.
15120 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15121                                         TagTypeKind NewTag, bool isDefinition,
15122                                         SourceLocation NewTagLoc,
15123                                         const IdentifierInfo *Name) {
15124   // C++ [dcl.type.elab]p3:
15125   //   The class-key or enum keyword present in the
15126   //   elaborated-type-specifier shall agree in kind with the
15127   //   declaration to which the name in the elaborated-type-specifier
15128   //   refers. This rule also applies to the form of
15129   //   elaborated-type-specifier that declares a class-name or
15130   //   friend class since it can be construed as referring to the
15131   //   definition of the class. Thus, in any
15132   //   elaborated-type-specifier, the enum keyword shall be used to
15133   //   refer to an enumeration (7.2), the union class-key shall be
15134   //   used to refer to a union (clause 9), and either the class or
15135   //   struct class-key shall be used to refer to a class (clause 9)
15136   //   declared using the class or struct class-key.
15137   TagTypeKind OldTag = Previous->getTagKind();
15138   if (OldTag != NewTag &&
15139       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15140     return false;
15141 
15142   // Tags are compatible, but we might still want to warn on mismatched tags.
15143   // Non-class tags can't be mismatched at this point.
15144   if (!isClassCompatTagKind(NewTag))
15145     return true;
15146 
15147   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15148   // by our warning analysis. We don't want to warn about mismatches with (eg)
15149   // declarations in system headers that are designed to be specialized, but if
15150   // a user asks us to warn, we should warn if their code contains mismatched
15151   // declarations.
15152   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15153     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15154                                       Loc);
15155   };
15156   if (IsIgnoredLoc(NewTagLoc))
15157     return true;
15158 
15159   auto IsIgnored = [&](const TagDecl *Tag) {
15160     return IsIgnoredLoc(Tag->getLocation());
15161   };
15162   while (IsIgnored(Previous)) {
15163     Previous = Previous->getPreviousDecl();
15164     if (!Previous)
15165       return true;
15166     OldTag = Previous->getTagKind();
15167   }
15168 
15169   bool isTemplate = false;
15170   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15171     isTemplate = Record->getDescribedClassTemplate();
15172 
15173   if (inTemplateInstantiation()) {
15174     if (OldTag != NewTag) {
15175       // In a template instantiation, do not offer fix-its for tag mismatches
15176       // since they usually mess up the template instead of fixing the problem.
15177       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15178         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15179         << getRedeclDiagFromTagKind(OldTag);
15180       // FIXME: Note previous location?
15181     }
15182     return true;
15183   }
15184 
15185   if (isDefinition) {
15186     // On definitions, check all previous tags and issue a fix-it for each
15187     // one that doesn't match the current tag.
15188     if (Previous->getDefinition()) {
15189       // Don't suggest fix-its for redefinitions.
15190       return true;
15191     }
15192 
15193     bool previousMismatch = false;
15194     for (const TagDecl *I : Previous->redecls()) {
15195       if (I->getTagKind() != NewTag) {
15196         // Ignore previous declarations for which the warning was disabled.
15197         if (IsIgnored(I))
15198           continue;
15199 
15200         if (!previousMismatch) {
15201           previousMismatch = true;
15202           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15203             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15204             << getRedeclDiagFromTagKind(I->getTagKind());
15205         }
15206         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15207           << getRedeclDiagFromTagKind(NewTag)
15208           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15209                TypeWithKeyword::getTagTypeKindName(NewTag));
15210       }
15211     }
15212     return true;
15213   }
15214 
15215   // Identify the prevailing tag kind: this is the kind of the definition (if
15216   // there is a non-ignored definition), or otherwise the kind of the prior
15217   // (non-ignored) declaration.
15218   const TagDecl *PrevDef = Previous->getDefinition();
15219   if (PrevDef && IsIgnored(PrevDef))
15220     PrevDef = nullptr;
15221   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15222   if (Redecl->getTagKind() != NewTag) {
15223     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15224       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15225       << getRedeclDiagFromTagKind(OldTag);
15226     Diag(Redecl->getLocation(), diag::note_previous_use);
15227 
15228     // If there is a previous definition, suggest a fix-it.
15229     if (PrevDef) {
15230       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15231         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15232         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15233              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15234     }
15235   }
15236 
15237   return true;
15238 }
15239 
15240 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15241 /// from an outer enclosing namespace or file scope inside a friend declaration.
15242 /// This should provide the commented out code in the following snippet:
15243 ///   namespace N {
15244 ///     struct X;
15245 ///     namespace M {
15246 ///       struct Y { friend struct /*N::*/ X; };
15247 ///     }
15248 ///   }
15249 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15250                                          SourceLocation NameLoc) {
15251   // While the decl is in a namespace, do repeated lookup of that name and see
15252   // if we get the same namespace back.  If we do not, continue until
15253   // translation unit scope, at which point we have a fully qualified NNS.
15254   SmallVector<IdentifierInfo *, 4> Namespaces;
15255   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15256   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15257     // This tag should be declared in a namespace, which can only be enclosed by
15258     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15259     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15260     if (!Namespace || Namespace->isAnonymousNamespace())
15261       return FixItHint();
15262     IdentifierInfo *II = Namespace->getIdentifier();
15263     Namespaces.push_back(II);
15264     NamedDecl *Lookup = SemaRef.LookupSingleName(
15265         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15266     if (Lookup == Namespace)
15267       break;
15268   }
15269 
15270   // Once we have all the namespaces, reverse them to go outermost first, and
15271   // build an NNS.
15272   SmallString<64> Insertion;
15273   llvm::raw_svector_ostream OS(Insertion);
15274   if (DC->isTranslationUnit())
15275     OS << "::";
15276   std::reverse(Namespaces.begin(), Namespaces.end());
15277   for (auto *II : Namespaces)
15278     OS << II->getName() << "::";
15279   return FixItHint::CreateInsertion(NameLoc, Insertion);
15280 }
15281 
15282 /// Determine whether a tag originally declared in context \p OldDC can
15283 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15284 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15285 /// using-declaration).
15286 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15287                                          DeclContext *NewDC) {
15288   OldDC = OldDC->getRedeclContext();
15289   NewDC = NewDC->getRedeclContext();
15290 
15291   if (OldDC->Equals(NewDC))
15292     return true;
15293 
15294   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15295   // encloses the other).
15296   if (S.getLangOpts().MSVCCompat &&
15297       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15298     return true;
15299 
15300   return false;
15301 }
15302 
15303 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15304 /// former case, Name will be non-null.  In the later case, Name will be null.
15305 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15306 /// reference/declaration/definition of a tag.
15307 ///
15308 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15309 /// trailing-type-specifier) other than one in an alias-declaration.
15310 ///
15311 /// \param SkipBody If non-null, will be set to indicate if the caller should
15312 /// skip the definition of this tag and treat it as if it were a declaration.
15313 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15314                      SourceLocation KWLoc, CXXScopeSpec &SS,
15315                      IdentifierInfo *Name, SourceLocation NameLoc,
15316                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15317                      SourceLocation ModulePrivateLoc,
15318                      MultiTemplateParamsArg TemplateParameterLists,
15319                      bool &OwnedDecl, bool &IsDependent,
15320                      SourceLocation ScopedEnumKWLoc,
15321                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15322                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15323                      SkipBodyInfo *SkipBody) {
15324   // If this is not a definition, it must have a name.
15325   IdentifierInfo *OrigName = Name;
15326   assert((Name != nullptr || TUK == TUK_Definition) &&
15327          "Nameless record must be a definition!");
15328   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15329 
15330   OwnedDecl = false;
15331   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15332   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15333 
15334   // FIXME: Check member specializations more carefully.
15335   bool isMemberSpecialization = false;
15336   bool Invalid = false;
15337 
15338   // We only need to do this matching if we have template parameters
15339   // or a scope specifier, which also conveniently avoids this work
15340   // for non-C++ cases.
15341   if (TemplateParameterLists.size() > 0 ||
15342       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15343     if (TemplateParameterList *TemplateParams =
15344             MatchTemplateParametersToScopeSpecifier(
15345                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15346                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15347       if (Kind == TTK_Enum) {
15348         Diag(KWLoc, diag::err_enum_template);
15349         return nullptr;
15350       }
15351 
15352       if (TemplateParams->size() > 0) {
15353         // This is a declaration or definition of a class template (which may
15354         // be a member of another template).
15355 
15356         if (Invalid)
15357           return nullptr;
15358 
15359         OwnedDecl = false;
15360         DeclResult Result = CheckClassTemplate(
15361             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15362             AS, ModulePrivateLoc,
15363             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15364             TemplateParameterLists.data(), SkipBody);
15365         return Result.get();
15366       } else {
15367         // The "template<>" header is extraneous.
15368         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15369           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15370         isMemberSpecialization = true;
15371       }
15372     }
15373 
15374     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15375         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15376       return nullptr;
15377   }
15378 
15379   // Figure out the underlying type if this a enum declaration. We need to do
15380   // this early, because it's needed to detect if this is an incompatible
15381   // redeclaration.
15382   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15383   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15384 
15385   if (Kind == TTK_Enum) {
15386     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15387       // No underlying type explicitly specified, or we failed to parse the
15388       // type, default to int.
15389       EnumUnderlying = Context.IntTy.getTypePtr();
15390     } else if (UnderlyingType.get()) {
15391       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15392       // integral type; any cv-qualification is ignored.
15393       TypeSourceInfo *TI = nullptr;
15394       GetTypeFromParser(UnderlyingType.get(), &TI);
15395       EnumUnderlying = TI;
15396 
15397       if (CheckEnumUnderlyingType(TI))
15398         // Recover by falling back to int.
15399         EnumUnderlying = Context.IntTy.getTypePtr();
15400 
15401       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15402                                           UPPC_FixedUnderlyingType))
15403         EnumUnderlying = Context.IntTy.getTypePtr();
15404 
15405     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15406       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15407       // of 'int'. However, if this is an unfixed forward declaration, don't set
15408       // the underlying type unless the user enables -fms-compatibility. This
15409       // makes unfixed forward declared enums incomplete and is more conforming.
15410       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15411         EnumUnderlying = Context.IntTy.getTypePtr();
15412     }
15413   }
15414 
15415   DeclContext *SearchDC = CurContext;
15416   DeclContext *DC = CurContext;
15417   bool isStdBadAlloc = false;
15418   bool isStdAlignValT = false;
15419 
15420   RedeclarationKind Redecl = forRedeclarationInCurContext();
15421   if (TUK == TUK_Friend || TUK == TUK_Reference)
15422     Redecl = NotForRedeclaration;
15423 
15424   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15425   /// implemented asks for structural equivalence checking, the returned decl
15426   /// here is passed back to the parser, allowing the tag body to be parsed.
15427   auto createTagFromNewDecl = [&]() -> TagDecl * {
15428     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15429     // If there is an identifier, use the location of the identifier as the
15430     // location of the decl, otherwise use the location of the struct/union
15431     // keyword.
15432     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15433     TagDecl *New = nullptr;
15434 
15435     if (Kind == TTK_Enum) {
15436       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15437                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15438       // If this is an undefined enum, bail.
15439       if (TUK != TUK_Definition && !Invalid)
15440         return nullptr;
15441       if (EnumUnderlying) {
15442         EnumDecl *ED = cast<EnumDecl>(New);
15443         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15444           ED->setIntegerTypeSourceInfo(TI);
15445         else
15446           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15447         ED->setPromotionType(ED->getIntegerType());
15448       }
15449     } else { // struct/union
15450       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15451                                nullptr);
15452     }
15453 
15454     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15455       // Add alignment attributes if necessary; these attributes are checked
15456       // when the ASTContext lays out the structure.
15457       //
15458       // It is important for implementing the correct semantics that this
15459       // happen here (in ActOnTag). The #pragma pack stack is
15460       // maintained as a result of parser callbacks which can occur at
15461       // many points during the parsing of a struct declaration (because
15462       // the #pragma tokens are effectively skipped over during the
15463       // parsing of the struct).
15464       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15465         AddAlignmentAttributesForRecord(RD);
15466         AddMsStructLayoutForRecord(RD);
15467       }
15468     }
15469     New->setLexicalDeclContext(CurContext);
15470     return New;
15471   };
15472 
15473   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15474   if (Name && SS.isNotEmpty()) {
15475     // We have a nested-name tag ('struct foo::bar').
15476 
15477     // Check for invalid 'foo::'.
15478     if (SS.isInvalid()) {
15479       Name = nullptr;
15480       goto CreateNewDecl;
15481     }
15482 
15483     // If this is a friend or a reference to a class in a dependent
15484     // context, don't try to make a decl for it.
15485     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15486       DC = computeDeclContext(SS, false);
15487       if (!DC) {
15488         IsDependent = true;
15489         return nullptr;
15490       }
15491     } else {
15492       DC = computeDeclContext(SS, true);
15493       if (!DC) {
15494         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15495           << SS.getRange();
15496         return nullptr;
15497       }
15498     }
15499 
15500     if (RequireCompleteDeclContext(SS, DC))
15501       return nullptr;
15502 
15503     SearchDC = DC;
15504     // Look-up name inside 'foo::'.
15505     LookupQualifiedName(Previous, DC);
15506 
15507     if (Previous.isAmbiguous())
15508       return nullptr;
15509 
15510     if (Previous.empty()) {
15511       // Name lookup did not find anything. However, if the
15512       // nested-name-specifier refers to the current instantiation,
15513       // and that current instantiation has any dependent base
15514       // classes, we might find something at instantiation time: treat
15515       // this as a dependent elaborated-type-specifier.
15516       // But this only makes any sense for reference-like lookups.
15517       if (Previous.wasNotFoundInCurrentInstantiation() &&
15518           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15519         IsDependent = true;
15520         return nullptr;
15521       }
15522 
15523       // A tag 'foo::bar' must already exist.
15524       Diag(NameLoc, diag::err_not_tag_in_scope)
15525         << Kind << Name << DC << SS.getRange();
15526       Name = nullptr;
15527       Invalid = true;
15528       goto CreateNewDecl;
15529     }
15530   } else if (Name) {
15531     // C++14 [class.mem]p14:
15532     //   If T is the name of a class, then each of the following shall have a
15533     //   name different from T:
15534     //    -- every member of class T that is itself a type
15535     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15536         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15537       return nullptr;
15538 
15539     // If this is a named struct, check to see if there was a previous forward
15540     // declaration or definition.
15541     // FIXME: We're looking into outer scopes here, even when we
15542     // shouldn't be. Doing so can result in ambiguities that we
15543     // shouldn't be diagnosing.
15544     LookupName(Previous, S);
15545 
15546     // When declaring or defining a tag, ignore ambiguities introduced
15547     // by types using'ed into this scope.
15548     if (Previous.isAmbiguous() &&
15549         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15550       LookupResult::Filter F = Previous.makeFilter();
15551       while (F.hasNext()) {
15552         NamedDecl *ND = F.next();
15553         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15554                 SearchDC->getRedeclContext()))
15555           F.erase();
15556       }
15557       F.done();
15558     }
15559 
15560     // C++11 [namespace.memdef]p3:
15561     //   If the name in a friend declaration is neither qualified nor
15562     //   a template-id and the declaration is a function or an
15563     //   elaborated-type-specifier, the lookup to determine whether
15564     //   the entity has been previously declared shall not consider
15565     //   any scopes outside the innermost enclosing namespace.
15566     //
15567     // MSVC doesn't implement the above rule for types, so a friend tag
15568     // declaration may be a redeclaration of a type declared in an enclosing
15569     // scope.  They do implement this rule for friend functions.
15570     //
15571     // Does it matter that this should be by scope instead of by
15572     // semantic context?
15573     if (!Previous.empty() && TUK == TUK_Friend) {
15574       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15575       LookupResult::Filter F = Previous.makeFilter();
15576       bool FriendSawTagOutsideEnclosingNamespace = false;
15577       while (F.hasNext()) {
15578         NamedDecl *ND = F.next();
15579         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15580         if (DC->isFileContext() &&
15581             !EnclosingNS->Encloses(ND->getDeclContext())) {
15582           if (getLangOpts().MSVCCompat)
15583             FriendSawTagOutsideEnclosingNamespace = true;
15584           else
15585             F.erase();
15586         }
15587       }
15588       F.done();
15589 
15590       // Diagnose this MSVC extension in the easy case where lookup would have
15591       // unambiguously found something outside the enclosing namespace.
15592       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15593         NamedDecl *ND = Previous.getFoundDecl();
15594         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15595             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15596       }
15597     }
15598 
15599     // Note:  there used to be some attempt at recovery here.
15600     if (Previous.isAmbiguous())
15601       return nullptr;
15602 
15603     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15604       // FIXME: This makes sure that we ignore the contexts associated
15605       // with C structs, unions, and enums when looking for a matching
15606       // tag declaration or definition. See the similar lookup tweak
15607       // in Sema::LookupName; is there a better way to deal with this?
15608       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15609         SearchDC = SearchDC->getParent();
15610     }
15611   }
15612 
15613   if (Previous.isSingleResult() &&
15614       Previous.getFoundDecl()->isTemplateParameter()) {
15615     // Maybe we will complain about the shadowed template parameter.
15616     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15617     // Just pretend that we didn't see the previous declaration.
15618     Previous.clear();
15619   }
15620 
15621   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15622       DC->Equals(getStdNamespace())) {
15623     if (Name->isStr("bad_alloc")) {
15624       // This is a declaration of or a reference to "std::bad_alloc".
15625       isStdBadAlloc = true;
15626 
15627       // If std::bad_alloc has been implicitly declared (but made invisible to
15628       // name lookup), fill in this implicit declaration as the previous
15629       // declaration, so that the declarations get chained appropriately.
15630       if (Previous.empty() && StdBadAlloc)
15631         Previous.addDecl(getStdBadAlloc());
15632     } else if (Name->isStr("align_val_t")) {
15633       isStdAlignValT = true;
15634       if (Previous.empty() && StdAlignValT)
15635         Previous.addDecl(getStdAlignValT());
15636     }
15637   }
15638 
15639   // If we didn't find a previous declaration, and this is a reference
15640   // (or friend reference), move to the correct scope.  In C++, we
15641   // also need to do a redeclaration lookup there, just in case
15642   // there's a shadow friend decl.
15643   if (Name && Previous.empty() &&
15644       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15645     if (Invalid) goto CreateNewDecl;
15646     assert(SS.isEmpty());
15647 
15648     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15649       // C++ [basic.scope.pdecl]p5:
15650       //   -- for an elaborated-type-specifier of the form
15651       //
15652       //          class-key identifier
15653       //
15654       //      if the elaborated-type-specifier is used in the
15655       //      decl-specifier-seq or parameter-declaration-clause of a
15656       //      function defined in namespace scope, the identifier is
15657       //      declared as a class-name in the namespace that contains
15658       //      the declaration; otherwise, except as a friend
15659       //      declaration, the identifier is declared in the smallest
15660       //      non-class, non-function-prototype scope that contains the
15661       //      declaration.
15662       //
15663       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15664       // C structs and unions.
15665       //
15666       // It is an error in C++ to declare (rather than define) an enum
15667       // type, including via an elaborated type specifier.  We'll
15668       // diagnose that later; for now, declare the enum in the same
15669       // scope as we would have picked for any other tag type.
15670       //
15671       // GNU C also supports this behavior as part of its incomplete
15672       // enum types extension, while GNU C++ does not.
15673       //
15674       // Find the context where we'll be declaring the tag.
15675       // FIXME: We would like to maintain the current DeclContext as the
15676       // lexical context,
15677       SearchDC = getTagInjectionContext(SearchDC);
15678 
15679       // Find the scope where we'll be declaring the tag.
15680       S = getTagInjectionScope(S, getLangOpts());
15681     } else {
15682       assert(TUK == TUK_Friend);
15683       // C++ [namespace.memdef]p3:
15684       //   If a friend declaration in a non-local class first declares a
15685       //   class or function, the friend class or function is a member of
15686       //   the innermost enclosing namespace.
15687       SearchDC = SearchDC->getEnclosingNamespaceContext();
15688     }
15689 
15690     // In C++, we need to do a redeclaration lookup to properly
15691     // diagnose some problems.
15692     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15693     // hidden declaration so that we don't get ambiguity errors when using a
15694     // type declared by an elaborated-type-specifier.  In C that is not correct
15695     // and we should instead merge compatible types found by lookup.
15696     if (getLangOpts().CPlusPlus) {
15697       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15698       LookupQualifiedName(Previous, SearchDC);
15699     } else {
15700       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15701       LookupName(Previous, S);
15702     }
15703   }
15704 
15705   // If we have a known previous declaration to use, then use it.
15706   if (Previous.empty() && SkipBody && SkipBody->Previous)
15707     Previous.addDecl(SkipBody->Previous);
15708 
15709   if (!Previous.empty()) {
15710     NamedDecl *PrevDecl = Previous.getFoundDecl();
15711     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15712 
15713     // It's okay to have a tag decl in the same scope as a typedef
15714     // which hides a tag decl in the same scope.  Finding this
15715     // insanity with a redeclaration lookup can only actually happen
15716     // in C++.
15717     //
15718     // This is also okay for elaborated-type-specifiers, which is
15719     // technically forbidden by the current standard but which is
15720     // okay according to the likely resolution of an open issue;
15721     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15722     if (getLangOpts().CPlusPlus) {
15723       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15724         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15725           TagDecl *Tag = TT->getDecl();
15726           if (Tag->getDeclName() == Name &&
15727               Tag->getDeclContext()->getRedeclContext()
15728                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15729             PrevDecl = Tag;
15730             Previous.clear();
15731             Previous.addDecl(Tag);
15732             Previous.resolveKind();
15733           }
15734         }
15735       }
15736     }
15737 
15738     // If this is a redeclaration of a using shadow declaration, it must
15739     // declare a tag in the same context. In MSVC mode, we allow a
15740     // redefinition if either context is within the other.
15741     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15742       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15743       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15744           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15745           !(OldTag && isAcceptableTagRedeclContext(
15746                           *this, OldTag->getDeclContext(), SearchDC))) {
15747         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15748         Diag(Shadow->getTargetDecl()->getLocation(),
15749              diag::note_using_decl_target);
15750         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15751             << 0;
15752         // Recover by ignoring the old declaration.
15753         Previous.clear();
15754         goto CreateNewDecl;
15755       }
15756     }
15757 
15758     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15759       // If this is a use of a previous tag, or if the tag is already declared
15760       // in the same scope (so that the definition/declaration completes or
15761       // rementions the tag), reuse the decl.
15762       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15763           isDeclInScope(DirectPrevDecl, SearchDC, S,
15764                         SS.isNotEmpty() || isMemberSpecialization)) {
15765         // Make sure that this wasn't declared as an enum and now used as a
15766         // struct or something similar.
15767         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15768                                           TUK == TUK_Definition, KWLoc,
15769                                           Name)) {
15770           bool SafeToContinue
15771             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15772                Kind != TTK_Enum);
15773           if (SafeToContinue)
15774             Diag(KWLoc, diag::err_use_with_wrong_tag)
15775               << Name
15776               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15777                                               PrevTagDecl->getKindName());
15778           else
15779             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15780           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15781 
15782           if (SafeToContinue)
15783             Kind = PrevTagDecl->getTagKind();
15784           else {
15785             // Recover by making this an anonymous redefinition.
15786             Name = nullptr;
15787             Previous.clear();
15788             Invalid = true;
15789           }
15790         }
15791 
15792         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15793           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15794           if (TUK == TUK_Reference || TUK == TUK_Friend)
15795             return PrevTagDecl;
15796 
15797           QualType EnumUnderlyingTy;
15798           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15799             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15800           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15801             EnumUnderlyingTy = QualType(T, 0);
15802 
15803           // All conflicts with previous declarations are recovered by
15804           // returning the previous declaration, unless this is a definition,
15805           // in which case we want the caller to bail out.
15806           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15807                                      ScopedEnum, EnumUnderlyingTy,
15808                                      IsFixed, PrevEnum))
15809             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15810         }
15811 
15812         // C++11 [class.mem]p1:
15813         //   A member shall not be declared twice in the member-specification,
15814         //   except that a nested class or member class template can be declared
15815         //   and then later defined.
15816         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15817             S->isDeclScope(PrevDecl)) {
15818           Diag(NameLoc, diag::ext_member_redeclared);
15819           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15820         }
15821 
15822         if (!Invalid) {
15823           // If this is a use, just return the declaration we found, unless
15824           // we have attributes.
15825           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15826             if (!Attrs.empty()) {
15827               // FIXME: Diagnose these attributes. For now, we create a new
15828               // declaration to hold them.
15829             } else if (TUK == TUK_Reference &&
15830                        (PrevTagDecl->getFriendObjectKind() ==
15831                             Decl::FOK_Undeclared ||
15832                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15833                        SS.isEmpty()) {
15834               // This declaration is a reference to an existing entity, but
15835               // has different visibility from that entity: it either makes
15836               // a friend visible or it makes a type visible in a new module.
15837               // In either case, create a new declaration. We only do this if
15838               // the declaration would have meant the same thing if no prior
15839               // declaration were found, that is, if it was found in the same
15840               // scope where we would have injected a declaration.
15841               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15842                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15843                 return PrevTagDecl;
15844               // This is in the injected scope, create a new declaration in
15845               // that scope.
15846               S = getTagInjectionScope(S, getLangOpts());
15847             } else {
15848               return PrevTagDecl;
15849             }
15850           }
15851 
15852           // Diagnose attempts to redefine a tag.
15853           if (TUK == TUK_Definition) {
15854             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15855               // If we're defining a specialization and the previous definition
15856               // is from an implicit instantiation, don't emit an error
15857               // here; we'll catch this in the general case below.
15858               bool IsExplicitSpecializationAfterInstantiation = false;
15859               if (isMemberSpecialization) {
15860                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15861                   IsExplicitSpecializationAfterInstantiation =
15862                     RD->getTemplateSpecializationKind() !=
15863                     TSK_ExplicitSpecialization;
15864                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15865                   IsExplicitSpecializationAfterInstantiation =
15866                     ED->getTemplateSpecializationKind() !=
15867                     TSK_ExplicitSpecialization;
15868               }
15869 
15870               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15871               // not keep more that one definition around (merge them). However,
15872               // ensure the decl passes the structural compatibility check in
15873               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15874               NamedDecl *Hidden = nullptr;
15875               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15876                 // There is a definition of this tag, but it is not visible. We
15877                 // explicitly make use of C++'s one definition rule here, and
15878                 // assume that this definition is identical to the hidden one
15879                 // we already have. Make the existing definition visible and
15880                 // use it in place of this one.
15881                 if (!getLangOpts().CPlusPlus) {
15882                   // Postpone making the old definition visible until after we
15883                   // complete parsing the new one and do the structural
15884                   // comparison.
15885                   SkipBody->CheckSameAsPrevious = true;
15886                   SkipBody->New = createTagFromNewDecl();
15887                   SkipBody->Previous = Def;
15888                   return Def;
15889                 } else {
15890                   SkipBody->ShouldSkip = true;
15891                   SkipBody->Previous = Def;
15892                   makeMergedDefinitionVisible(Hidden);
15893                   // Carry on and handle it like a normal definition. We'll
15894                   // skip starting the definitiion later.
15895                 }
15896               } else if (!IsExplicitSpecializationAfterInstantiation) {
15897                 // A redeclaration in function prototype scope in C isn't
15898                 // visible elsewhere, so merely issue a warning.
15899                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15900                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15901                 else
15902                   Diag(NameLoc, diag::err_redefinition) << Name;
15903                 notePreviousDefinition(Def,
15904                                        NameLoc.isValid() ? NameLoc : KWLoc);
15905                 // If this is a redefinition, recover by making this
15906                 // struct be anonymous, which will make any later
15907                 // references get the previous definition.
15908                 Name = nullptr;
15909                 Previous.clear();
15910                 Invalid = true;
15911               }
15912             } else {
15913               // If the type is currently being defined, complain
15914               // about a nested redefinition.
15915               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15916               if (TD->isBeingDefined()) {
15917                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15918                 Diag(PrevTagDecl->getLocation(),
15919                      diag::note_previous_definition);
15920                 Name = nullptr;
15921                 Previous.clear();
15922                 Invalid = true;
15923               }
15924             }
15925 
15926             // Okay, this is definition of a previously declared or referenced
15927             // tag. We're going to create a new Decl for it.
15928           }
15929 
15930           // Okay, we're going to make a redeclaration.  If this is some kind
15931           // of reference, make sure we build the redeclaration in the same DC
15932           // as the original, and ignore the current access specifier.
15933           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15934             SearchDC = PrevTagDecl->getDeclContext();
15935             AS = AS_none;
15936           }
15937         }
15938         // If we get here we have (another) forward declaration or we
15939         // have a definition.  Just create a new decl.
15940 
15941       } else {
15942         // If we get here, this is a definition of a new tag type in a nested
15943         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15944         // new decl/type.  We set PrevDecl to NULL so that the entities
15945         // have distinct types.
15946         Previous.clear();
15947       }
15948       // If we get here, we're going to create a new Decl. If PrevDecl
15949       // is non-NULL, it's a definition of the tag declared by
15950       // PrevDecl. If it's NULL, we have a new definition.
15951 
15952     // Otherwise, PrevDecl is not a tag, but was found with tag
15953     // lookup.  This is only actually possible in C++, where a few
15954     // things like templates still live in the tag namespace.
15955     } else {
15956       // Use a better diagnostic if an elaborated-type-specifier
15957       // found the wrong kind of type on the first
15958       // (non-redeclaration) lookup.
15959       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15960           !Previous.isForRedeclaration()) {
15961         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15962         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15963                                                        << Kind;
15964         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15965         Invalid = true;
15966 
15967       // Otherwise, only diagnose if the declaration is in scope.
15968       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15969                                 SS.isNotEmpty() || isMemberSpecialization)) {
15970         // do nothing
15971 
15972       // Diagnose implicit declarations introduced by elaborated types.
15973       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15974         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15975         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15976         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15977         Invalid = true;
15978 
15979       // Otherwise it's a declaration.  Call out a particularly common
15980       // case here.
15981       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15982         unsigned Kind = 0;
15983         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15984         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15985           << Name << Kind << TND->getUnderlyingType();
15986         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15987         Invalid = true;
15988 
15989       // Otherwise, diagnose.
15990       } else {
15991         // The tag name clashes with something else in the target scope,
15992         // issue an error and recover by making this tag be anonymous.
15993         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15994         notePreviousDefinition(PrevDecl, NameLoc);
15995         Name = nullptr;
15996         Invalid = true;
15997       }
15998 
15999       // The existing declaration isn't relevant to us; we're in a
16000       // new scope, so clear out the previous declaration.
16001       Previous.clear();
16002     }
16003   }
16004 
16005 CreateNewDecl:
16006 
16007   TagDecl *PrevDecl = nullptr;
16008   if (Previous.isSingleResult())
16009     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16010 
16011   // If there is an identifier, use the location of the identifier as the
16012   // location of the decl, otherwise use the location of the struct/union
16013   // keyword.
16014   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16015 
16016   // Otherwise, create a new declaration. If there is a previous
16017   // declaration of the same entity, the two will be linked via
16018   // PrevDecl.
16019   TagDecl *New;
16020 
16021   if (Kind == TTK_Enum) {
16022     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16023     // enum X { A, B, C } D;    D should chain to X.
16024     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16025                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16026                            ScopedEnumUsesClassTag, IsFixed);
16027 
16028     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16029       StdAlignValT = cast<EnumDecl>(New);
16030 
16031     // If this is an undefined enum, warn.
16032     if (TUK != TUK_Definition && !Invalid) {
16033       TagDecl *Def;
16034       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16035         // C++0x: 7.2p2: opaque-enum-declaration.
16036         // Conflicts are diagnosed above. Do nothing.
16037       }
16038       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16039         Diag(Loc, diag::ext_forward_ref_enum_def)
16040           << New;
16041         Diag(Def->getLocation(), diag::note_previous_definition);
16042       } else {
16043         unsigned DiagID = diag::ext_forward_ref_enum;
16044         if (getLangOpts().MSVCCompat)
16045           DiagID = diag::ext_ms_forward_ref_enum;
16046         else if (getLangOpts().CPlusPlus)
16047           DiagID = diag::err_forward_ref_enum;
16048         Diag(Loc, DiagID);
16049       }
16050     }
16051 
16052     if (EnumUnderlying) {
16053       EnumDecl *ED = cast<EnumDecl>(New);
16054       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16055         ED->setIntegerTypeSourceInfo(TI);
16056       else
16057         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16058       ED->setPromotionType(ED->getIntegerType());
16059       assert(ED->isComplete() && "enum with type should be complete");
16060     }
16061   } else {
16062     // struct/union/class
16063 
16064     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16065     // struct X { int A; } D;    D should chain to X.
16066     if (getLangOpts().CPlusPlus) {
16067       // FIXME: Look for a way to use RecordDecl for simple structs.
16068       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16069                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16070 
16071       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16072         StdBadAlloc = cast<CXXRecordDecl>(New);
16073     } else
16074       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16075                                cast_or_null<RecordDecl>(PrevDecl));
16076   }
16077 
16078   // C++11 [dcl.type]p3:
16079   //   A type-specifier-seq shall not define a class or enumeration [...].
16080   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16081       TUK == TUK_Definition) {
16082     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16083       << Context.getTagDeclType(New);
16084     Invalid = true;
16085   }
16086 
16087   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16088       DC->getDeclKind() == Decl::Enum) {
16089     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16090       << Context.getTagDeclType(New);
16091     Invalid = true;
16092   }
16093 
16094   // Maybe add qualifier info.
16095   if (SS.isNotEmpty()) {
16096     if (SS.isSet()) {
16097       // If this is either a declaration or a definition, check the
16098       // nested-name-specifier against the current context.
16099       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16100           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16101                                        isMemberSpecialization))
16102         Invalid = true;
16103 
16104       New->setQualifierInfo(SS.getWithLocInContext(Context));
16105       if (TemplateParameterLists.size() > 0) {
16106         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16107       }
16108     }
16109     else
16110       Invalid = true;
16111   }
16112 
16113   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16114     // Add alignment attributes if necessary; these attributes are checked when
16115     // the ASTContext lays out the structure.
16116     //
16117     // It is important for implementing the correct semantics that this
16118     // happen here (in ActOnTag). The #pragma pack stack is
16119     // maintained as a result of parser callbacks which can occur at
16120     // many points during the parsing of a struct declaration (because
16121     // the #pragma tokens are effectively skipped over during the
16122     // parsing of the struct).
16123     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16124       AddAlignmentAttributesForRecord(RD);
16125       AddMsStructLayoutForRecord(RD);
16126     }
16127   }
16128 
16129   if (ModulePrivateLoc.isValid()) {
16130     if (isMemberSpecialization)
16131       Diag(New->getLocation(), diag::err_module_private_specialization)
16132         << 2
16133         << FixItHint::CreateRemoval(ModulePrivateLoc);
16134     // __module_private__ does not apply to local classes. However, we only
16135     // diagnose this as an error when the declaration specifiers are
16136     // freestanding. Here, we just ignore the __module_private__.
16137     else if (!SearchDC->isFunctionOrMethod())
16138       New->setModulePrivate();
16139   }
16140 
16141   // If this is a specialization of a member class (of a class template),
16142   // check the specialization.
16143   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16144     Invalid = true;
16145 
16146   // If we're declaring or defining a tag in function prototype scope in C,
16147   // note that this type can only be used within the function and add it to
16148   // the list of decls to inject into the function definition scope.
16149   if ((Name || Kind == TTK_Enum) &&
16150       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16151     if (getLangOpts().CPlusPlus) {
16152       // C++ [dcl.fct]p6:
16153       //   Types shall not be defined in return or parameter types.
16154       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16155         Diag(Loc, diag::err_type_defined_in_param_type)
16156             << Name;
16157         Invalid = true;
16158       }
16159     } else if (!PrevDecl) {
16160       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16161     }
16162   }
16163 
16164   if (Invalid)
16165     New->setInvalidDecl();
16166 
16167   // Set the lexical context. If the tag has a C++ scope specifier, the
16168   // lexical context will be different from the semantic context.
16169   New->setLexicalDeclContext(CurContext);
16170 
16171   // Mark this as a friend decl if applicable.
16172   // In Microsoft mode, a friend declaration also acts as a forward
16173   // declaration so we always pass true to setObjectOfFriendDecl to make
16174   // the tag name visible.
16175   if (TUK == TUK_Friend)
16176     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16177 
16178   // Set the access specifier.
16179   if (!Invalid && SearchDC->isRecord())
16180     SetMemberAccessSpecifier(New, PrevDecl, AS);
16181 
16182   if (PrevDecl)
16183     CheckRedeclarationModuleOwnership(New, PrevDecl);
16184 
16185   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16186     New->startDefinition();
16187 
16188   ProcessDeclAttributeList(S, New, Attrs);
16189   AddPragmaAttributes(S, New);
16190 
16191   // If this has an identifier, add it to the scope stack.
16192   if (TUK == TUK_Friend) {
16193     // We might be replacing an existing declaration in the lookup tables;
16194     // if so, borrow its access specifier.
16195     if (PrevDecl)
16196       New->setAccess(PrevDecl->getAccess());
16197 
16198     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16199     DC->makeDeclVisibleInContext(New);
16200     if (Name) // can be null along some error paths
16201       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16202         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16203   } else if (Name) {
16204     S = getNonFieldDeclScope(S);
16205     PushOnScopeChains(New, S, true);
16206   } else {
16207     CurContext->addDecl(New);
16208   }
16209 
16210   // If this is the C FILE type, notify the AST context.
16211   if (IdentifierInfo *II = New->getIdentifier())
16212     if (!New->isInvalidDecl() &&
16213         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16214         II->isStr("FILE"))
16215       Context.setFILEDecl(New);
16216 
16217   if (PrevDecl)
16218     mergeDeclAttributes(New, PrevDecl);
16219 
16220   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16221     inferGslOwnerPointerAttribute(CXXRD);
16222 
16223   // If there's a #pragma GCC visibility in scope, set the visibility of this
16224   // record.
16225   AddPushedVisibilityAttribute(New);
16226 
16227   if (isMemberSpecialization && !New->isInvalidDecl())
16228     CompleteMemberSpecialization(New, Previous);
16229 
16230   OwnedDecl = true;
16231   // In C++, don't return an invalid declaration. We can't recover well from
16232   // the cases where we make the type anonymous.
16233   if (Invalid && getLangOpts().CPlusPlus) {
16234     if (New->isBeingDefined())
16235       if (auto RD = dyn_cast<RecordDecl>(New))
16236         RD->completeDefinition();
16237     return nullptr;
16238   } else if (SkipBody && SkipBody->ShouldSkip) {
16239     return SkipBody->Previous;
16240   } else {
16241     return New;
16242   }
16243 }
16244 
16245 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16246   AdjustDeclIfTemplate(TagD);
16247   TagDecl *Tag = cast<TagDecl>(TagD);
16248 
16249   // Enter the tag context.
16250   PushDeclContext(S, Tag);
16251 
16252   ActOnDocumentableDecl(TagD);
16253 
16254   // If there's a #pragma GCC visibility in scope, set the visibility of this
16255   // record.
16256   AddPushedVisibilityAttribute(Tag);
16257 }
16258 
16259 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16260                                     SkipBodyInfo &SkipBody) {
16261   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16262     return false;
16263 
16264   // Make the previous decl visible.
16265   makeMergedDefinitionVisible(SkipBody.Previous);
16266   return true;
16267 }
16268 
16269 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16270   assert(isa<ObjCContainerDecl>(IDecl) &&
16271          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16272   DeclContext *OCD = cast<DeclContext>(IDecl);
16273   assert(OCD->getLexicalParent() == CurContext &&
16274       "The next DeclContext should be lexically contained in the current one.");
16275   CurContext = OCD;
16276   return IDecl;
16277 }
16278 
16279 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16280                                            SourceLocation FinalLoc,
16281                                            bool IsFinalSpelledSealed,
16282                                            SourceLocation LBraceLoc) {
16283   AdjustDeclIfTemplate(TagD);
16284   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16285 
16286   FieldCollector->StartClass();
16287 
16288   if (!Record->getIdentifier())
16289     return;
16290 
16291   if (FinalLoc.isValid())
16292     Record->addAttr(FinalAttr::Create(
16293         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16294         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16295 
16296   // C++ [class]p2:
16297   //   [...] The class-name is also inserted into the scope of the
16298   //   class itself; this is known as the injected-class-name. For
16299   //   purposes of access checking, the injected-class-name is treated
16300   //   as if it were a public member name.
16301   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16302       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16303       Record->getLocation(), Record->getIdentifier(),
16304       /*PrevDecl=*/nullptr,
16305       /*DelayTypeCreation=*/true);
16306   Context.getTypeDeclType(InjectedClassName, Record);
16307   InjectedClassName->setImplicit();
16308   InjectedClassName->setAccess(AS_public);
16309   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16310       InjectedClassName->setDescribedClassTemplate(Template);
16311   PushOnScopeChains(InjectedClassName, S);
16312   assert(InjectedClassName->isInjectedClassName() &&
16313          "Broken injected-class-name");
16314 }
16315 
16316 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16317                                     SourceRange BraceRange) {
16318   AdjustDeclIfTemplate(TagD);
16319   TagDecl *Tag = cast<TagDecl>(TagD);
16320   Tag->setBraceRange(BraceRange);
16321 
16322   // Make sure we "complete" the definition even it is invalid.
16323   if (Tag->isBeingDefined()) {
16324     assert(Tag->isInvalidDecl() && "We should already have completed it");
16325     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16326       RD->completeDefinition();
16327   }
16328 
16329   if (isa<CXXRecordDecl>(Tag)) {
16330     FieldCollector->FinishClass();
16331   }
16332 
16333   // Exit this scope of this tag's definition.
16334   PopDeclContext();
16335 
16336   if (getCurLexicalContext()->isObjCContainer() &&
16337       Tag->getDeclContext()->isFileContext())
16338     Tag->setTopLevelDeclInObjCContainer();
16339 
16340   // Notify the consumer that we've defined a tag.
16341   if (!Tag->isInvalidDecl())
16342     Consumer.HandleTagDeclDefinition(Tag);
16343 }
16344 
16345 void Sema::ActOnObjCContainerFinishDefinition() {
16346   // Exit this scope of this interface definition.
16347   PopDeclContext();
16348 }
16349 
16350 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16351   assert(DC == CurContext && "Mismatch of container contexts");
16352   OriginalLexicalContext = DC;
16353   ActOnObjCContainerFinishDefinition();
16354 }
16355 
16356 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16357   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16358   OriginalLexicalContext = nullptr;
16359 }
16360 
16361 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16362   AdjustDeclIfTemplate(TagD);
16363   TagDecl *Tag = cast<TagDecl>(TagD);
16364   Tag->setInvalidDecl();
16365 
16366   // Make sure we "complete" the definition even it is invalid.
16367   if (Tag->isBeingDefined()) {
16368     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16369       RD->completeDefinition();
16370   }
16371 
16372   // We're undoing ActOnTagStartDefinition here, not
16373   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16374   // the FieldCollector.
16375 
16376   PopDeclContext();
16377 }
16378 
16379 // Note that FieldName may be null for anonymous bitfields.
16380 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16381                                 IdentifierInfo *FieldName,
16382                                 QualType FieldTy, bool IsMsStruct,
16383                                 Expr *BitWidth, bool *ZeroWidth) {
16384   assert(BitWidth);
16385   if (BitWidth->containsErrors())
16386     return ExprError();
16387 
16388   // Default to true; that shouldn't confuse checks for emptiness
16389   if (ZeroWidth)
16390     *ZeroWidth = true;
16391 
16392   // C99 6.7.2.1p4 - verify the field type.
16393   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16394   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16395     // Handle incomplete and sizeless types with a specific error.
16396     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16397                                  diag::err_field_incomplete_or_sizeless))
16398       return ExprError();
16399     if (FieldName)
16400       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16401         << FieldName << FieldTy << BitWidth->getSourceRange();
16402     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16403       << FieldTy << BitWidth->getSourceRange();
16404   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16405                                              UPPC_BitFieldWidth))
16406     return ExprError();
16407 
16408   // If the bit-width is type- or value-dependent, don't try to check
16409   // it now.
16410   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16411     return BitWidth;
16412 
16413   llvm::APSInt Value;
16414   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16415   if (ICE.isInvalid())
16416     return ICE;
16417   BitWidth = ICE.get();
16418 
16419   if (Value != 0 && ZeroWidth)
16420     *ZeroWidth = false;
16421 
16422   // Zero-width bitfield is ok for anonymous field.
16423   if (Value == 0 && FieldName)
16424     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16425 
16426   if (Value.isSigned() && Value.isNegative()) {
16427     if (FieldName)
16428       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16429                << FieldName << Value.toString(10);
16430     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16431       << Value.toString(10);
16432   }
16433 
16434   if (!FieldTy->isDependentType()) {
16435     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16436     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16437     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16438 
16439     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16440     // ABI.
16441     bool CStdConstraintViolation =
16442         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16443     bool MSBitfieldViolation =
16444         Value.ugt(TypeStorageSize) &&
16445         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16446     if (CStdConstraintViolation || MSBitfieldViolation) {
16447       unsigned DiagWidth =
16448           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16449       if (FieldName)
16450         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16451                << FieldName << (unsigned)Value.getZExtValue()
16452                << !CStdConstraintViolation << DiagWidth;
16453 
16454       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16455              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16456              << DiagWidth;
16457     }
16458 
16459     // Warn on types where the user might conceivably expect to get all
16460     // specified bits as value bits: that's all integral types other than
16461     // 'bool'.
16462     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16463       if (FieldName)
16464         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16465             << FieldName << (unsigned)Value.getZExtValue()
16466             << (unsigned)TypeWidth;
16467       else
16468         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16469             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16470     }
16471   }
16472 
16473   return BitWidth;
16474 }
16475 
16476 /// ActOnField - Each field of a C struct/union is passed into this in order
16477 /// to create a FieldDecl object for it.
16478 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16479                        Declarator &D, Expr *BitfieldWidth) {
16480   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16481                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16482                                /*InitStyle=*/ICIS_NoInit, AS_public);
16483   return Res;
16484 }
16485 
16486 /// HandleField - Analyze a field of a C struct or a C++ data member.
16487 ///
16488 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16489                              SourceLocation DeclStart,
16490                              Declarator &D, Expr *BitWidth,
16491                              InClassInitStyle InitStyle,
16492                              AccessSpecifier AS) {
16493   if (D.isDecompositionDeclarator()) {
16494     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16495     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16496       << Decomp.getSourceRange();
16497     return nullptr;
16498   }
16499 
16500   IdentifierInfo *II = D.getIdentifier();
16501   SourceLocation Loc = DeclStart;
16502   if (II) Loc = D.getIdentifierLoc();
16503 
16504   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16505   QualType T = TInfo->getType();
16506   if (getLangOpts().CPlusPlus) {
16507     CheckExtraCXXDefaultArguments(D);
16508 
16509     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16510                                         UPPC_DataMemberType)) {
16511       D.setInvalidType();
16512       T = Context.IntTy;
16513       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16514     }
16515   }
16516 
16517   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16518 
16519   if (D.getDeclSpec().isInlineSpecified())
16520     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16521         << getLangOpts().CPlusPlus17;
16522   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16523     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16524          diag::err_invalid_thread)
16525       << DeclSpec::getSpecifierName(TSCS);
16526 
16527   // Check to see if this name was declared as a member previously
16528   NamedDecl *PrevDecl = nullptr;
16529   LookupResult Previous(*this, II, Loc, LookupMemberName,
16530                         ForVisibleRedeclaration);
16531   LookupName(Previous, S);
16532   switch (Previous.getResultKind()) {
16533     case LookupResult::Found:
16534     case LookupResult::FoundUnresolvedValue:
16535       PrevDecl = Previous.getAsSingle<NamedDecl>();
16536       break;
16537 
16538     case LookupResult::FoundOverloaded:
16539       PrevDecl = Previous.getRepresentativeDecl();
16540       break;
16541 
16542     case LookupResult::NotFound:
16543     case LookupResult::NotFoundInCurrentInstantiation:
16544     case LookupResult::Ambiguous:
16545       break;
16546   }
16547   Previous.suppressDiagnostics();
16548 
16549   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16550     // Maybe we will complain about the shadowed template parameter.
16551     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16552     // Just pretend that we didn't see the previous declaration.
16553     PrevDecl = nullptr;
16554   }
16555 
16556   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16557     PrevDecl = nullptr;
16558 
16559   bool Mutable
16560     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16561   SourceLocation TSSL = D.getBeginLoc();
16562   FieldDecl *NewFD
16563     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16564                      TSSL, AS, PrevDecl, &D);
16565 
16566   if (NewFD->isInvalidDecl())
16567     Record->setInvalidDecl();
16568 
16569   if (D.getDeclSpec().isModulePrivateSpecified())
16570     NewFD->setModulePrivate();
16571 
16572   if (NewFD->isInvalidDecl() && PrevDecl) {
16573     // Don't introduce NewFD into scope; there's already something
16574     // with the same name in the same scope.
16575   } else if (II) {
16576     PushOnScopeChains(NewFD, S);
16577   } else
16578     Record->addDecl(NewFD);
16579 
16580   return NewFD;
16581 }
16582 
16583 /// Build a new FieldDecl and check its well-formedness.
16584 ///
16585 /// This routine builds a new FieldDecl given the fields name, type,
16586 /// record, etc. \p PrevDecl should refer to any previous declaration
16587 /// with the same name and in the same scope as the field to be
16588 /// created.
16589 ///
16590 /// \returns a new FieldDecl.
16591 ///
16592 /// \todo The Declarator argument is a hack. It will be removed once
16593 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16594                                 TypeSourceInfo *TInfo,
16595                                 RecordDecl *Record, SourceLocation Loc,
16596                                 bool Mutable, Expr *BitWidth,
16597                                 InClassInitStyle InitStyle,
16598                                 SourceLocation TSSL,
16599                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16600                                 Declarator *D) {
16601   IdentifierInfo *II = Name.getAsIdentifierInfo();
16602   bool InvalidDecl = false;
16603   if (D) InvalidDecl = D->isInvalidType();
16604 
16605   // If we receive a broken type, recover by assuming 'int' and
16606   // marking this declaration as invalid.
16607   if (T.isNull() || T->containsErrors()) {
16608     InvalidDecl = true;
16609     T = Context.IntTy;
16610   }
16611 
16612   QualType EltTy = Context.getBaseElementType(T);
16613   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16614     if (RequireCompleteSizedType(Loc, EltTy,
16615                                  diag::err_field_incomplete_or_sizeless)) {
16616       // Fields of incomplete type force their record to be invalid.
16617       Record->setInvalidDecl();
16618       InvalidDecl = true;
16619     } else {
16620       NamedDecl *Def;
16621       EltTy->isIncompleteType(&Def);
16622       if (Def && Def->isInvalidDecl()) {
16623         Record->setInvalidDecl();
16624         InvalidDecl = true;
16625       }
16626     }
16627   }
16628 
16629   // TR 18037 does not allow fields to be declared with address space
16630   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16631       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16632     Diag(Loc, diag::err_field_with_address_space);
16633     Record->setInvalidDecl();
16634     InvalidDecl = true;
16635   }
16636 
16637   if (LangOpts.OpenCL) {
16638     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16639     // used as structure or union field: image, sampler, event or block types.
16640     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16641         T->isBlockPointerType()) {
16642       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16643       Record->setInvalidDecl();
16644       InvalidDecl = true;
16645     }
16646     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16647     if (BitWidth) {
16648       Diag(Loc, diag::err_opencl_bitfields);
16649       InvalidDecl = true;
16650     }
16651   }
16652 
16653   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16654   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16655       T.hasQualifiers()) {
16656     InvalidDecl = true;
16657     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16658   }
16659 
16660   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16661   // than a variably modified type.
16662   if (!InvalidDecl && T->isVariablyModifiedType()) {
16663     bool SizeIsNegative;
16664     llvm::APSInt Oversized;
16665 
16666     TypeSourceInfo *FixedTInfo =
16667       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16668                                                     SizeIsNegative,
16669                                                     Oversized);
16670     if (FixedTInfo) {
16671       Diag(Loc, diag::warn_illegal_constant_array_size);
16672       TInfo = FixedTInfo;
16673       T = FixedTInfo->getType();
16674     } else {
16675       if (SizeIsNegative)
16676         Diag(Loc, diag::err_typecheck_negative_array_size);
16677       else if (Oversized.getBoolValue())
16678         Diag(Loc, diag::err_array_too_large)
16679           << Oversized.toString(10);
16680       else
16681         Diag(Loc, diag::err_typecheck_field_variable_size);
16682       InvalidDecl = true;
16683     }
16684   }
16685 
16686   // Fields can not have abstract class types
16687   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16688                                              diag::err_abstract_type_in_decl,
16689                                              AbstractFieldType))
16690     InvalidDecl = true;
16691 
16692   bool ZeroWidth = false;
16693   if (InvalidDecl)
16694     BitWidth = nullptr;
16695   // If this is declared as a bit-field, check the bit-field.
16696   if (BitWidth) {
16697     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16698                               &ZeroWidth).get();
16699     if (!BitWidth) {
16700       InvalidDecl = true;
16701       BitWidth = nullptr;
16702       ZeroWidth = false;
16703     }
16704 
16705     // Only data members can have in-class initializers.
16706     if (BitWidth && !II && InitStyle) {
16707       Diag(Loc, diag::err_anon_bitfield_init);
16708       InvalidDecl = true;
16709       BitWidth = nullptr;
16710       ZeroWidth = false;
16711     }
16712   }
16713 
16714   // Check that 'mutable' is consistent with the type of the declaration.
16715   if (!InvalidDecl && Mutable) {
16716     unsigned DiagID = 0;
16717     if (T->isReferenceType())
16718       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16719                                         : diag::err_mutable_reference;
16720     else if (T.isConstQualified())
16721       DiagID = diag::err_mutable_const;
16722 
16723     if (DiagID) {
16724       SourceLocation ErrLoc = Loc;
16725       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16726         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16727       Diag(ErrLoc, DiagID);
16728       if (DiagID != diag::ext_mutable_reference) {
16729         Mutable = false;
16730         InvalidDecl = true;
16731       }
16732     }
16733   }
16734 
16735   // C++11 [class.union]p8 (DR1460):
16736   //   At most one variant member of a union may have a
16737   //   brace-or-equal-initializer.
16738   if (InitStyle != ICIS_NoInit)
16739     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16740 
16741   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16742                                        BitWidth, Mutable, InitStyle);
16743   if (InvalidDecl)
16744     NewFD->setInvalidDecl();
16745 
16746   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16747     Diag(Loc, diag::err_duplicate_member) << II;
16748     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16749     NewFD->setInvalidDecl();
16750   }
16751 
16752   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16753     if (Record->isUnion()) {
16754       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16755         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16756         if (RDecl->getDefinition()) {
16757           // C++ [class.union]p1: An object of a class with a non-trivial
16758           // constructor, a non-trivial copy constructor, a non-trivial
16759           // destructor, or a non-trivial copy assignment operator
16760           // cannot be a member of a union, nor can an array of such
16761           // objects.
16762           if (CheckNontrivialField(NewFD))
16763             NewFD->setInvalidDecl();
16764         }
16765       }
16766 
16767       // C++ [class.union]p1: If a union contains a member of reference type,
16768       // the program is ill-formed, except when compiling with MSVC extensions
16769       // enabled.
16770       if (EltTy->isReferenceType()) {
16771         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16772                                     diag::ext_union_member_of_reference_type :
16773                                     diag::err_union_member_of_reference_type)
16774           << NewFD->getDeclName() << EltTy;
16775         if (!getLangOpts().MicrosoftExt)
16776           NewFD->setInvalidDecl();
16777       }
16778     }
16779   }
16780 
16781   // FIXME: We need to pass in the attributes given an AST
16782   // representation, not a parser representation.
16783   if (D) {
16784     // FIXME: The current scope is almost... but not entirely... correct here.
16785     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16786 
16787     if (NewFD->hasAttrs())
16788       CheckAlignasUnderalignment(NewFD);
16789   }
16790 
16791   // In auto-retain/release, infer strong retension for fields of
16792   // retainable type.
16793   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16794     NewFD->setInvalidDecl();
16795 
16796   if (T.isObjCGCWeak())
16797     Diag(Loc, diag::warn_attribute_weak_on_field);
16798 
16799   NewFD->setAccess(AS);
16800   return NewFD;
16801 }
16802 
16803 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16804   assert(FD);
16805   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16806 
16807   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16808     return false;
16809 
16810   QualType EltTy = Context.getBaseElementType(FD->getType());
16811   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16812     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16813     if (RDecl->getDefinition()) {
16814       // We check for copy constructors before constructors
16815       // because otherwise we'll never get complaints about
16816       // copy constructors.
16817 
16818       CXXSpecialMember member = CXXInvalid;
16819       // We're required to check for any non-trivial constructors. Since the
16820       // implicit default constructor is suppressed if there are any
16821       // user-declared constructors, we just need to check that there is a
16822       // trivial default constructor and a trivial copy constructor. (We don't
16823       // worry about move constructors here, since this is a C++98 check.)
16824       if (RDecl->hasNonTrivialCopyConstructor())
16825         member = CXXCopyConstructor;
16826       else if (!RDecl->hasTrivialDefaultConstructor())
16827         member = CXXDefaultConstructor;
16828       else if (RDecl->hasNonTrivialCopyAssignment())
16829         member = CXXCopyAssignment;
16830       else if (RDecl->hasNonTrivialDestructor())
16831         member = CXXDestructor;
16832 
16833       if (member != CXXInvalid) {
16834         if (!getLangOpts().CPlusPlus11 &&
16835             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16836           // Objective-C++ ARC: it is an error to have a non-trivial field of
16837           // a union. However, system headers in Objective-C programs
16838           // occasionally have Objective-C lifetime objects within unions,
16839           // and rather than cause the program to fail, we make those
16840           // members unavailable.
16841           SourceLocation Loc = FD->getLocation();
16842           if (getSourceManager().isInSystemHeader(Loc)) {
16843             if (!FD->hasAttr<UnavailableAttr>())
16844               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16845                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16846             return false;
16847           }
16848         }
16849 
16850         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16851                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16852                diag::err_illegal_union_or_anon_struct_member)
16853           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16854         DiagnoseNontrivial(RDecl, member);
16855         return !getLangOpts().CPlusPlus11;
16856       }
16857     }
16858   }
16859 
16860   return false;
16861 }
16862 
16863 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16864 ///  AST enum value.
16865 static ObjCIvarDecl::AccessControl
16866 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16867   switch (ivarVisibility) {
16868   default: llvm_unreachable("Unknown visitibility kind");
16869   case tok::objc_private: return ObjCIvarDecl::Private;
16870   case tok::objc_public: return ObjCIvarDecl::Public;
16871   case tok::objc_protected: return ObjCIvarDecl::Protected;
16872   case tok::objc_package: return ObjCIvarDecl::Package;
16873   }
16874 }
16875 
16876 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16877 /// in order to create an IvarDecl object for it.
16878 Decl *Sema::ActOnIvar(Scope *S,
16879                                 SourceLocation DeclStart,
16880                                 Declarator &D, Expr *BitfieldWidth,
16881                                 tok::ObjCKeywordKind Visibility) {
16882 
16883   IdentifierInfo *II = D.getIdentifier();
16884   Expr *BitWidth = (Expr*)BitfieldWidth;
16885   SourceLocation Loc = DeclStart;
16886   if (II) Loc = D.getIdentifierLoc();
16887 
16888   // FIXME: Unnamed fields can be handled in various different ways, for
16889   // example, unnamed unions inject all members into the struct namespace!
16890 
16891   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16892   QualType T = TInfo->getType();
16893 
16894   if (BitWidth) {
16895     // 6.7.2.1p3, 6.7.2.1p4
16896     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16897     if (!BitWidth)
16898       D.setInvalidType();
16899   } else {
16900     // Not a bitfield.
16901 
16902     // validate II.
16903 
16904   }
16905   if (T->isReferenceType()) {
16906     Diag(Loc, diag::err_ivar_reference_type);
16907     D.setInvalidType();
16908   }
16909   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16910   // than a variably modified type.
16911   else if (T->isVariablyModifiedType()) {
16912     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16913     D.setInvalidType();
16914   }
16915 
16916   // Get the visibility (access control) for this ivar.
16917   ObjCIvarDecl::AccessControl ac =
16918     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16919                                         : ObjCIvarDecl::None;
16920   // Must set ivar's DeclContext to its enclosing interface.
16921   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16922   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16923     return nullptr;
16924   ObjCContainerDecl *EnclosingContext;
16925   if (ObjCImplementationDecl *IMPDecl =
16926       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16927     if (LangOpts.ObjCRuntime.isFragile()) {
16928     // Case of ivar declared in an implementation. Context is that of its class.
16929       EnclosingContext = IMPDecl->getClassInterface();
16930       assert(EnclosingContext && "Implementation has no class interface!");
16931     }
16932     else
16933       EnclosingContext = EnclosingDecl;
16934   } else {
16935     if (ObjCCategoryDecl *CDecl =
16936         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16937       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16938         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16939         return nullptr;
16940       }
16941     }
16942     EnclosingContext = EnclosingDecl;
16943   }
16944 
16945   // Construct the decl.
16946   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16947                                              DeclStart, Loc, II, T,
16948                                              TInfo, ac, (Expr *)BitfieldWidth);
16949 
16950   if (II) {
16951     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16952                                            ForVisibleRedeclaration);
16953     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16954         && !isa<TagDecl>(PrevDecl)) {
16955       Diag(Loc, diag::err_duplicate_member) << II;
16956       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16957       NewID->setInvalidDecl();
16958     }
16959   }
16960 
16961   // Process attributes attached to the ivar.
16962   ProcessDeclAttributes(S, NewID, D);
16963 
16964   if (D.isInvalidType())
16965     NewID->setInvalidDecl();
16966 
16967   // In ARC, infer 'retaining' for ivars of retainable type.
16968   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16969     NewID->setInvalidDecl();
16970 
16971   if (D.getDeclSpec().isModulePrivateSpecified())
16972     NewID->setModulePrivate();
16973 
16974   if (II) {
16975     // FIXME: When interfaces are DeclContexts, we'll need to add
16976     // these to the interface.
16977     S->AddDecl(NewID);
16978     IdResolver.AddDecl(NewID);
16979   }
16980 
16981   if (LangOpts.ObjCRuntime.isNonFragile() &&
16982       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16983     Diag(Loc, diag::warn_ivars_in_interface);
16984 
16985   return NewID;
16986 }
16987 
16988 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16989 /// class and class extensions. For every class \@interface and class
16990 /// extension \@interface, if the last ivar is a bitfield of any type,
16991 /// then add an implicit `char :0` ivar to the end of that interface.
16992 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16993                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16994   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16995     return;
16996 
16997   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16998   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16999 
17000   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17001     return;
17002   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17003   if (!ID) {
17004     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17005       if (!CD->IsClassExtension())
17006         return;
17007     }
17008     // No need to add this to end of @implementation.
17009     else
17010       return;
17011   }
17012   // All conditions are met. Add a new bitfield to the tail end of ivars.
17013   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17014   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17015 
17016   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17017                               DeclLoc, DeclLoc, nullptr,
17018                               Context.CharTy,
17019                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17020                                                                DeclLoc),
17021                               ObjCIvarDecl::Private, BW,
17022                               true);
17023   AllIvarDecls.push_back(Ivar);
17024 }
17025 
17026 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17027                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17028                        SourceLocation RBrac,
17029                        const ParsedAttributesView &Attrs) {
17030   assert(EnclosingDecl && "missing record or interface decl");
17031 
17032   // If this is an Objective-C @implementation or category and we have
17033   // new fields here we should reset the layout of the interface since
17034   // it will now change.
17035   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17036     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17037     switch (DC->getKind()) {
17038     default: break;
17039     case Decl::ObjCCategory:
17040       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17041       break;
17042     case Decl::ObjCImplementation:
17043       Context.
17044         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17045       break;
17046     }
17047   }
17048 
17049   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17050   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17051 
17052   // Start counting up the number of named members; make sure to include
17053   // members of anonymous structs and unions in the total.
17054   unsigned NumNamedMembers = 0;
17055   if (Record) {
17056     for (const auto *I : Record->decls()) {
17057       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17058         if (IFD->getDeclName())
17059           ++NumNamedMembers;
17060     }
17061   }
17062 
17063   // Verify that all the fields are okay.
17064   SmallVector<FieldDecl*, 32> RecFields;
17065 
17066   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17067        i != end; ++i) {
17068     FieldDecl *FD = cast<FieldDecl>(*i);
17069 
17070     // Get the type for the field.
17071     const Type *FDTy = FD->getType().getTypePtr();
17072 
17073     if (!FD->isAnonymousStructOrUnion()) {
17074       // Remember all fields written by the user.
17075       RecFields.push_back(FD);
17076     }
17077 
17078     // If the field is already invalid for some reason, don't emit more
17079     // diagnostics about it.
17080     if (FD->isInvalidDecl()) {
17081       EnclosingDecl->setInvalidDecl();
17082       continue;
17083     }
17084 
17085     // C99 6.7.2.1p2:
17086     //   A structure or union shall not contain a member with
17087     //   incomplete or function type (hence, a structure shall not
17088     //   contain an instance of itself, but may contain a pointer to
17089     //   an instance of itself), except that the last member of a
17090     //   structure with more than one named member may have incomplete
17091     //   array type; such a structure (and any union containing,
17092     //   possibly recursively, a member that is such a structure)
17093     //   shall not be a member of a structure or an element of an
17094     //   array.
17095     bool IsLastField = (i + 1 == Fields.end());
17096     if (FDTy->isFunctionType()) {
17097       // Field declared as a function.
17098       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17099         << FD->getDeclName();
17100       FD->setInvalidDecl();
17101       EnclosingDecl->setInvalidDecl();
17102       continue;
17103     } else if (FDTy->isIncompleteArrayType() &&
17104                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17105       if (Record) {
17106         // Flexible array member.
17107         // Microsoft and g++ is more permissive regarding flexible array.
17108         // It will accept flexible array in union and also
17109         // as the sole element of a struct/class.
17110         unsigned DiagID = 0;
17111         if (!Record->isUnion() && !IsLastField) {
17112           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17113             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17114           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17115           FD->setInvalidDecl();
17116           EnclosingDecl->setInvalidDecl();
17117           continue;
17118         } else if (Record->isUnion())
17119           DiagID = getLangOpts().MicrosoftExt
17120                        ? diag::ext_flexible_array_union_ms
17121                        : getLangOpts().CPlusPlus
17122                              ? diag::ext_flexible_array_union_gnu
17123                              : diag::err_flexible_array_union;
17124         else if (NumNamedMembers < 1)
17125           DiagID = getLangOpts().MicrosoftExt
17126                        ? diag::ext_flexible_array_empty_aggregate_ms
17127                        : getLangOpts().CPlusPlus
17128                              ? diag::ext_flexible_array_empty_aggregate_gnu
17129                              : diag::err_flexible_array_empty_aggregate;
17130 
17131         if (DiagID)
17132           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17133                                           << Record->getTagKind();
17134         // While the layout of types that contain virtual bases is not specified
17135         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17136         // virtual bases after the derived members.  This would make a flexible
17137         // array member declared at the end of an object not adjacent to the end
17138         // of the type.
17139         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17140           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17141               << FD->getDeclName() << Record->getTagKind();
17142         if (!getLangOpts().C99)
17143           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17144             << FD->getDeclName() << Record->getTagKind();
17145 
17146         // If the element type has a non-trivial destructor, we would not
17147         // implicitly destroy the elements, so disallow it for now.
17148         //
17149         // FIXME: GCC allows this. We should probably either implicitly delete
17150         // the destructor of the containing class, or just allow this.
17151         QualType BaseElem = Context.getBaseElementType(FD->getType());
17152         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17153           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17154             << FD->getDeclName() << FD->getType();
17155           FD->setInvalidDecl();
17156           EnclosingDecl->setInvalidDecl();
17157           continue;
17158         }
17159         // Okay, we have a legal flexible array member at the end of the struct.
17160         Record->setHasFlexibleArrayMember(true);
17161       } else {
17162         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17163         // unless they are followed by another ivar. That check is done
17164         // elsewhere, after synthesized ivars are known.
17165       }
17166     } else if (!FDTy->isDependentType() &&
17167                RequireCompleteSizedType(
17168                    FD->getLocation(), FD->getType(),
17169                    diag::err_field_incomplete_or_sizeless)) {
17170       // Incomplete type
17171       FD->setInvalidDecl();
17172       EnclosingDecl->setInvalidDecl();
17173       continue;
17174     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17175       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17176         // A type which contains a flexible array member is considered to be a
17177         // flexible array member.
17178         Record->setHasFlexibleArrayMember(true);
17179         if (!Record->isUnion()) {
17180           // If this is a struct/class and this is not the last element, reject
17181           // it.  Note that GCC supports variable sized arrays in the middle of
17182           // structures.
17183           if (!IsLastField)
17184             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17185               << FD->getDeclName() << FD->getType();
17186           else {
17187             // We support flexible arrays at the end of structs in
17188             // other structs as an extension.
17189             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17190               << FD->getDeclName();
17191           }
17192         }
17193       }
17194       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17195           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17196                                  diag::err_abstract_type_in_decl,
17197                                  AbstractIvarType)) {
17198         // Ivars can not have abstract class types
17199         FD->setInvalidDecl();
17200       }
17201       if (Record && FDTTy->getDecl()->hasObjectMember())
17202         Record->setHasObjectMember(true);
17203       if (Record && FDTTy->getDecl()->hasVolatileMember())
17204         Record->setHasVolatileMember(true);
17205     } else if (FDTy->isObjCObjectType()) {
17206       /// A field cannot be an Objective-c object
17207       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17208         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17209       QualType T = Context.getObjCObjectPointerType(FD->getType());
17210       FD->setType(T);
17211     } else if (Record && Record->isUnion() &&
17212                FD->getType().hasNonTrivialObjCLifetime() &&
17213                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17214                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17215                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17216                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17217       // For backward compatibility, fields of C unions declared in system
17218       // headers that have non-trivial ObjC ownership qualifications are marked
17219       // as unavailable unless the qualifier is explicit and __strong. This can
17220       // break ABI compatibility between programs compiled with ARC and MRR, but
17221       // is a better option than rejecting programs using those unions under
17222       // ARC.
17223       FD->addAttr(UnavailableAttr::CreateImplicit(
17224           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17225           FD->getLocation()));
17226     } else if (getLangOpts().ObjC &&
17227                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17228                !Record->hasObjectMember()) {
17229       if (FD->getType()->isObjCObjectPointerType() ||
17230           FD->getType().isObjCGCStrong())
17231         Record->setHasObjectMember(true);
17232       else if (Context.getAsArrayType(FD->getType())) {
17233         QualType BaseType = Context.getBaseElementType(FD->getType());
17234         if (BaseType->isRecordType() &&
17235             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17236           Record->setHasObjectMember(true);
17237         else if (BaseType->isObjCObjectPointerType() ||
17238                  BaseType.isObjCGCStrong())
17239                Record->setHasObjectMember(true);
17240       }
17241     }
17242 
17243     if (Record && !getLangOpts().CPlusPlus &&
17244         !shouldIgnoreForRecordTriviality(FD)) {
17245       QualType FT = FD->getType();
17246       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17247         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17248         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17249             Record->isUnion())
17250           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17251       }
17252       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17253       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17254         Record->setNonTrivialToPrimitiveCopy(true);
17255         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17256           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17257       }
17258       if (FT.isDestructedType()) {
17259         Record->setNonTrivialToPrimitiveDestroy(true);
17260         Record->setParamDestroyedInCallee(true);
17261         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17262           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17263       }
17264 
17265       if (const auto *RT = FT->getAs<RecordType>()) {
17266         if (RT->getDecl()->getArgPassingRestrictions() ==
17267             RecordDecl::APK_CanNeverPassInRegs)
17268           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17269       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17270         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17271     }
17272 
17273     if (Record && FD->getType().isVolatileQualified())
17274       Record->setHasVolatileMember(true);
17275     // Keep track of the number of named members.
17276     if (FD->getIdentifier())
17277       ++NumNamedMembers;
17278   }
17279 
17280   // Okay, we successfully defined 'Record'.
17281   if (Record) {
17282     bool Completed = false;
17283     if (CXXRecord) {
17284       if (!CXXRecord->isInvalidDecl()) {
17285         // Set access bits correctly on the directly-declared conversions.
17286         for (CXXRecordDecl::conversion_iterator
17287                I = CXXRecord->conversion_begin(),
17288                E = CXXRecord->conversion_end(); I != E; ++I)
17289           I.setAccess((*I)->getAccess());
17290       }
17291 
17292       // Add any implicitly-declared members to this class.
17293       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17294 
17295       if (!CXXRecord->isDependentType()) {
17296         if (!CXXRecord->isInvalidDecl()) {
17297           // If we have virtual base classes, we may end up finding multiple
17298           // final overriders for a given virtual function. Check for this
17299           // problem now.
17300           if (CXXRecord->getNumVBases()) {
17301             CXXFinalOverriderMap FinalOverriders;
17302             CXXRecord->getFinalOverriders(FinalOverriders);
17303 
17304             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17305                                              MEnd = FinalOverriders.end();
17306                  M != MEnd; ++M) {
17307               for (OverridingMethods::iterator SO = M->second.begin(),
17308                                             SOEnd = M->second.end();
17309                    SO != SOEnd; ++SO) {
17310                 assert(SO->second.size() > 0 &&
17311                        "Virtual function without overriding functions?");
17312                 if (SO->second.size() == 1)
17313                   continue;
17314 
17315                 // C++ [class.virtual]p2:
17316                 //   In a derived class, if a virtual member function of a base
17317                 //   class subobject has more than one final overrider the
17318                 //   program is ill-formed.
17319                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17320                   << (const NamedDecl *)M->first << Record;
17321                 Diag(M->first->getLocation(),
17322                      diag::note_overridden_virtual_function);
17323                 for (OverridingMethods::overriding_iterator
17324                           OM = SO->second.begin(),
17325                        OMEnd = SO->second.end();
17326                      OM != OMEnd; ++OM)
17327                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17328                     << (const NamedDecl *)M->first << OM->Method->getParent();
17329 
17330                 Record->setInvalidDecl();
17331               }
17332             }
17333             CXXRecord->completeDefinition(&FinalOverriders);
17334             Completed = true;
17335           }
17336         }
17337       }
17338     }
17339 
17340     if (!Completed)
17341       Record->completeDefinition();
17342 
17343     // Handle attributes before checking the layout.
17344     ProcessDeclAttributeList(S, Record, Attrs);
17345 
17346     // We may have deferred checking for a deleted destructor. Check now.
17347     if (CXXRecord) {
17348       auto *Dtor = CXXRecord->getDestructor();
17349       if (Dtor && Dtor->isImplicit() &&
17350           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17351         CXXRecord->setImplicitDestructorIsDeleted();
17352         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17353       }
17354     }
17355 
17356     if (Record->hasAttrs()) {
17357       CheckAlignasUnderalignment(Record);
17358 
17359       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17360         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17361                                            IA->getRange(), IA->getBestCase(),
17362                                            IA->getInheritanceModel());
17363     }
17364 
17365     // Check if the structure/union declaration is a type that can have zero
17366     // size in C. For C this is a language extension, for C++ it may cause
17367     // compatibility problems.
17368     bool CheckForZeroSize;
17369     if (!getLangOpts().CPlusPlus) {
17370       CheckForZeroSize = true;
17371     } else {
17372       // For C++ filter out types that cannot be referenced in C code.
17373       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17374       CheckForZeroSize =
17375           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17376           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17377           CXXRecord->isCLike();
17378     }
17379     if (CheckForZeroSize) {
17380       bool ZeroSize = true;
17381       bool IsEmpty = true;
17382       unsigned NonBitFields = 0;
17383       for (RecordDecl::field_iterator I = Record->field_begin(),
17384                                       E = Record->field_end();
17385            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17386         IsEmpty = false;
17387         if (I->isUnnamedBitfield()) {
17388           if (!I->isZeroLengthBitField(Context))
17389             ZeroSize = false;
17390         } else {
17391           ++NonBitFields;
17392           QualType FieldType = I->getType();
17393           if (FieldType->isIncompleteType() ||
17394               !Context.getTypeSizeInChars(FieldType).isZero())
17395             ZeroSize = false;
17396         }
17397       }
17398 
17399       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17400       // allowed in C++, but warn if its declaration is inside
17401       // extern "C" block.
17402       if (ZeroSize) {
17403         Diag(RecLoc, getLangOpts().CPlusPlus ?
17404                          diag::warn_zero_size_struct_union_in_extern_c :
17405                          diag::warn_zero_size_struct_union_compat)
17406           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17407       }
17408 
17409       // Structs without named members are extension in C (C99 6.7.2.1p7),
17410       // but are accepted by GCC.
17411       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17412         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17413                                diag::ext_no_named_members_in_struct_union)
17414           << Record->isUnion();
17415       }
17416     }
17417   } else {
17418     ObjCIvarDecl **ClsFields =
17419       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17420     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17421       ID->setEndOfDefinitionLoc(RBrac);
17422       // Add ivar's to class's DeclContext.
17423       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17424         ClsFields[i]->setLexicalDeclContext(ID);
17425         ID->addDecl(ClsFields[i]);
17426       }
17427       // Must enforce the rule that ivars in the base classes may not be
17428       // duplicates.
17429       if (ID->getSuperClass())
17430         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17431     } else if (ObjCImplementationDecl *IMPDecl =
17432                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17433       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17434       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17435         // Ivar declared in @implementation never belongs to the implementation.
17436         // Only it is in implementation's lexical context.
17437         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17438       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17439       IMPDecl->setIvarLBraceLoc(LBrac);
17440       IMPDecl->setIvarRBraceLoc(RBrac);
17441     } else if (ObjCCategoryDecl *CDecl =
17442                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17443       // case of ivars in class extension; all other cases have been
17444       // reported as errors elsewhere.
17445       // FIXME. Class extension does not have a LocEnd field.
17446       // CDecl->setLocEnd(RBrac);
17447       // Add ivar's to class extension's DeclContext.
17448       // Diagnose redeclaration of private ivars.
17449       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17450       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17451         if (IDecl) {
17452           if (const ObjCIvarDecl *ClsIvar =
17453               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17454             Diag(ClsFields[i]->getLocation(),
17455                  diag::err_duplicate_ivar_declaration);
17456             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17457             continue;
17458           }
17459           for (const auto *Ext : IDecl->known_extensions()) {
17460             if (const ObjCIvarDecl *ClsExtIvar
17461                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17462               Diag(ClsFields[i]->getLocation(),
17463                    diag::err_duplicate_ivar_declaration);
17464               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17465               continue;
17466             }
17467           }
17468         }
17469         ClsFields[i]->setLexicalDeclContext(CDecl);
17470         CDecl->addDecl(ClsFields[i]);
17471       }
17472       CDecl->setIvarLBraceLoc(LBrac);
17473       CDecl->setIvarRBraceLoc(RBrac);
17474     }
17475   }
17476 }
17477 
17478 /// Determine whether the given integral value is representable within
17479 /// the given type T.
17480 static bool isRepresentableIntegerValue(ASTContext &Context,
17481                                         llvm::APSInt &Value,
17482                                         QualType T) {
17483   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17484          "Integral type required!");
17485   unsigned BitWidth = Context.getIntWidth(T);
17486 
17487   if (Value.isUnsigned() || Value.isNonNegative()) {
17488     if (T->isSignedIntegerOrEnumerationType())
17489       --BitWidth;
17490     return Value.getActiveBits() <= BitWidth;
17491   }
17492   return Value.getMinSignedBits() <= BitWidth;
17493 }
17494 
17495 // Given an integral type, return the next larger integral type
17496 // (or a NULL type of no such type exists).
17497 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17498   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17499   // enum checking below.
17500   assert((T->isIntegralType(Context) ||
17501          T->isEnumeralType()) && "Integral type required!");
17502   const unsigned NumTypes = 4;
17503   QualType SignedIntegralTypes[NumTypes] = {
17504     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17505   };
17506   QualType UnsignedIntegralTypes[NumTypes] = {
17507     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17508     Context.UnsignedLongLongTy
17509   };
17510 
17511   unsigned BitWidth = Context.getTypeSize(T);
17512   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17513                                                         : UnsignedIntegralTypes;
17514   for (unsigned I = 0; I != NumTypes; ++I)
17515     if (Context.getTypeSize(Types[I]) > BitWidth)
17516       return Types[I];
17517 
17518   return QualType();
17519 }
17520 
17521 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17522                                           EnumConstantDecl *LastEnumConst,
17523                                           SourceLocation IdLoc,
17524                                           IdentifierInfo *Id,
17525                                           Expr *Val) {
17526   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17527   llvm::APSInt EnumVal(IntWidth);
17528   QualType EltTy;
17529 
17530   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17531     Val = nullptr;
17532 
17533   if (Val)
17534     Val = DefaultLvalueConversion(Val).get();
17535 
17536   if (Val) {
17537     if (Enum->isDependentType() || Val->isTypeDependent())
17538       EltTy = Context.DependentTy;
17539     else {
17540       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17541         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17542         // constant-expression in the enumerator-definition shall be a converted
17543         // constant expression of the underlying type.
17544         EltTy = Enum->getIntegerType();
17545         ExprResult Converted =
17546           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17547                                            CCEK_Enumerator);
17548         if (Converted.isInvalid())
17549           Val = nullptr;
17550         else
17551           Val = Converted.get();
17552       } else if (!Val->isValueDependent() &&
17553                  !(Val = VerifyIntegerConstantExpression(Val,
17554                                                          &EnumVal).get())) {
17555         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17556       } else {
17557         if (Enum->isComplete()) {
17558           EltTy = Enum->getIntegerType();
17559 
17560           // In Obj-C and Microsoft mode, require the enumeration value to be
17561           // representable in the underlying type of the enumeration. In C++11,
17562           // we perform a non-narrowing conversion as part of converted constant
17563           // expression checking.
17564           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17565             if (Context.getTargetInfo()
17566                     .getTriple()
17567                     .isWindowsMSVCEnvironment()) {
17568               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17569             } else {
17570               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17571             }
17572           }
17573 
17574           // Cast to the underlying type.
17575           Val = ImpCastExprToType(Val, EltTy,
17576                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17577                                                          : CK_IntegralCast)
17578                     .get();
17579         } else if (getLangOpts().CPlusPlus) {
17580           // C++11 [dcl.enum]p5:
17581           //   If the underlying type is not fixed, the type of each enumerator
17582           //   is the type of its initializing value:
17583           //     - If an initializer is specified for an enumerator, the
17584           //       initializing value has the same type as the expression.
17585           EltTy = Val->getType();
17586         } else {
17587           // C99 6.7.2.2p2:
17588           //   The expression that defines the value of an enumeration constant
17589           //   shall be an integer constant expression that has a value
17590           //   representable as an int.
17591 
17592           // Complain if the value is not representable in an int.
17593           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17594             Diag(IdLoc, diag::ext_enum_value_not_int)
17595               << EnumVal.toString(10) << Val->getSourceRange()
17596               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17597           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17598             // Force the type of the expression to 'int'.
17599             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17600           }
17601           EltTy = Val->getType();
17602         }
17603       }
17604     }
17605   }
17606 
17607   if (!Val) {
17608     if (Enum->isDependentType())
17609       EltTy = Context.DependentTy;
17610     else if (!LastEnumConst) {
17611       // C++0x [dcl.enum]p5:
17612       //   If the underlying type is not fixed, the type of each enumerator
17613       //   is the type of its initializing value:
17614       //     - If no initializer is specified for the first enumerator, the
17615       //       initializing value has an unspecified integral type.
17616       //
17617       // GCC uses 'int' for its unspecified integral type, as does
17618       // C99 6.7.2.2p3.
17619       if (Enum->isFixed()) {
17620         EltTy = Enum->getIntegerType();
17621       }
17622       else {
17623         EltTy = Context.IntTy;
17624       }
17625     } else {
17626       // Assign the last value + 1.
17627       EnumVal = LastEnumConst->getInitVal();
17628       ++EnumVal;
17629       EltTy = LastEnumConst->getType();
17630 
17631       // Check for overflow on increment.
17632       if (EnumVal < LastEnumConst->getInitVal()) {
17633         // C++0x [dcl.enum]p5:
17634         //   If the underlying type is not fixed, the type of each enumerator
17635         //   is the type of its initializing value:
17636         //
17637         //     - Otherwise the type of the initializing value is the same as
17638         //       the type of the initializing value of the preceding enumerator
17639         //       unless the incremented value is not representable in that type,
17640         //       in which case the type is an unspecified integral type
17641         //       sufficient to contain the incremented value. If no such type
17642         //       exists, the program is ill-formed.
17643         QualType T = getNextLargerIntegralType(Context, EltTy);
17644         if (T.isNull() || Enum->isFixed()) {
17645           // There is no integral type larger enough to represent this
17646           // value. Complain, then allow the value to wrap around.
17647           EnumVal = LastEnumConst->getInitVal();
17648           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17649           ++EnumVal;
17650           if (Enum->isFixed())
17651             // When the underlying type is fixed, this is ill-formed.
17652             Diag(IdLoc, diag::err_enumerator_wrapped)
17653               << EnumVal.toString(10)
17654               << EltTy;
17655           else
17656             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17657               << EnumVal.toString(10);
17658         } else {
17659           EltTy = T;
17660         }
17661 
17662         // Retrieve the last enumerator's value, extent that type to the
17663         // type that is supposed to be large enough to represent the incremented
17664         // value, then increment.
17665         EnumVal = LastEnumConst->getInitVal();
17666         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17667         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17668         ++EnumVal;
17669 
17670         // If we're not in C++, diagnose the overflow of enumerator values,
17671         // which in C99 means that the enumerator value is not representable in
17672         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17673         // permits enumerator values that are representable in some larger
17674         // integral type.
17675         if (!getLangOpts().CPlusPlus && !T.isNull())
17676           Diag(IdLoc, diag::warn_enum_value_overflow);
17677       } else if (!getLangOpts().CPlusPlus &&
17678                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17679         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17680         Diag(IdLoc, diag::ext_enum_value_not_int)
17681           << EnumVal.toString(10) << 1;
17682       }
17683     }
17684   }
17685 
17686   if (!EltTy->isDependentType()) {
17687     // Make the enumerator value match the signedness and size of the
17688     // enumerator's type.
17689     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17690     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17691   }
17692 
17693   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17694                                   Val, EnumVal);
17695 }
17696 
17697 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17698                                                 SourceLocation IILoc) {
17699   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17700       !getLangOpts().CPlusPlus)
17701     return SkipBodyInfo();
17702 
17703   // We have an anonymous enum definition. Look up the first enumerator to
17704   // determine if we should merge the definition with an existing one and
17705   // skip the body.
17706   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17707                                          forRedeclarationInCurContext());
17708   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17709   if (!PrevECD)
17710     return SkipBodyInfo();
17711 
17712   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17713   NamedDecl *Hidden;
17714   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17715     SkipBodyInfo Skip;
17716     Skip.Previous = Hidden;
17717     return Skip;
17718   }
17719 
17720   return SkipBodyInfo();
17721 }
17722 
17723 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17724                               SourceLocation IdLoc, IdentifierInfo *Id,
17725                               const ParsedAttributesView &Attrs,
17726                               SourceLocation EqualLoc, Expr *Val) {
17727   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17728   EnumConstantDecl *LastEnumConst =
17729     cast_or_null<EnumConstantDecl>(lastEnumConst);
17730 
17731   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17732   // we find one that is.
17733   S = getNonFieldDeclScope(S);
17734 
17735   // Verify that there isn't already something declared with this name in this
17736   // scope.
17737   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17738   LookupName(R, S);
17739   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17740 
17741   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17742     // Maybe we will complain about the shadowed template parameter.
17743     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17744     // Just pretend that we didn't see the previous declaration.
17745     PrevDecl = nullptr;
17746   }
17747 
17748   // C++ [class.mem]p15:
17749   // If T is the name of a class, then each of the following shall have a name
17750   // different from T:
17751   // - every enumerator of every member of class T that is an unscoped
17752   // enumerated type
17753   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17754     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17755                             DeclarationNameInfo(Id, IdLoc));
17756 
17757   EnumConstantDecl *New =
17758     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17759   if (!New)
17760     return nullptr;
17761 
17762   if (PrevDecl) {
17763     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17764       // Check for other kinds of shadowing not already handled.
17765       CheckShadow(New, PrevDecl, R);
17766     }
17767 
17768     // When in C++, we may get a TagDecl with the same name; in this case the
17769     // enum constant will 'hide' the tag.
17770     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17771            "Received TagDecl when not in C++!");
17772     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17773       if (isa<EnumConstantDecl>(PrevDecl))
17774         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17775       else
17776         Diag(IdLoc, diag::err_redefinition) << Id;
17777       notePreviousDefinition(PrevDecl, IdLoc);
17778       return nullptr;
17779     }
17780   }
17781 
17782   // Process attributes.
17783   ProcessDeclAttributeList(S, New, Attrs);
17784   AddPragmaAttributes(S, New);
17785 
17786   // Register this decl in the current scope stack.
17787   New->setAccess(TheEnumDecl->getAccess());
17788   PushOnScopeChains(New, S);
17789 
17790   ActOnDocumentableDecl(New);
17791 
17792   return New;
17793 }
17794 
17795 // Returns true when the enum initial expression does not trigger the
17796 // duplicate enum warning.  A few common cases are exempted as follows:
17797 // Element2 = Element1
17798 // Element2 = Element1 + 1
17799 // Element2 = Element1 - 1
17800 // Where Element2 and Element1 are from the same enum.
17801 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17802   Expr *InitExpr = ECD->getInitExpr();
17803   if (!InitExpr)
17804     return true;
17805   InitExpr = InitExpr->IgnoreImpCasts();
17806 
17807   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17808     if (!BO->isAdditiveOp())
17809       return true;
17810     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17811     if (!IL)
17812       return true;
17813     if (IL->getValue() != 1)
17814       return true;
17815 
17816     InitExpr = BO->getLHS();
17817   }
17818 
17819   // This checks if the elements are from the same enum.
17820   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17821   if (!DRE)
17822     return true;
17823 
17824   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17825   if (!EnumConstant)
17826     return true;
17827 
17828   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17829       Enum)
17830     return true;
17831 
17832   return false;
17833 }
17834 
17835 // Emits a warning when an element is implicitly set a value that
17836 // a previous element has already been set to.
17837 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17838                                         EnumDecl *Enum, QualType EnumType) {
17839   // Avoid anonymous enums
17840   if (!Enum->getIdentifier())
17841     return;
17842 
17843   // Only check for small enums.
17844   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17845     return;
17846 
17847   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17848     return;
17849 
17850   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17851   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17852 
17853   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17854 
17855   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17856   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17857 
17858   // Use int64_t as a key to avoid needing special handling for map keys.
17859   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17860     llvm::APSInt Val = D->getInitVal();
17861     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17862   };
17863 
17864   DuplicatesVector DupVector;
17865   ValueToVectorMap EnumMap;
17866 
17867   // Populate the EnumMap with all values represented by enum constants without
17868   // an initializer.
17869   for (auto *Element : Elements) {
17870     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17871 
17872     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17873     // this constant.  Skip this enum since it may be ill-formed.
17874     if (!ECD) {
17875       return;
17876     }
17877 
17878     // Constants with initalizers are handled in the next loop.
17879     if (ECD->getInitExpr())
17880       continue;
17881 
17882     // Duplicate values are handled in the next loop.
17883     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17884   }
17885 
17886   if (EnumMap.size() == 0)
17887     return;
17888 
17889   // Create vectors for any values that has duplicates.
17890   for (auto *Element : Elements) {
17891     // The last loop returned if any constant was null.
17892     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17893     if (!ValidDuplicateEnum(ECD, Enum))
17894       continue;
17895 
17896     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17897     if (Iter == EnumMap.end())
17898       continue;
17899 
17900     DeclOrVector& Entry = Iter->second;
17901     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17902       // Ensure constants are different.
17903       if (D == ECD)
17904         continue;
17905 
17906       // Create new vector and push values onto it.
17907       auto Vec = std::make_unique<ECDVector>();
17908       Vec->push_back(D);
17909       Vec->push_back(ECD);
17910 
17911       // Update entry to point to the duplicates vector.
17912       Entry = Vec.get();
17913 
17914       // Store the vector somewhere we can consult later for quick emission of
17915       // diagnostics.
17916       DupVector.emplace_back(std::move(Vec));
17917       continue;
17918     }
17919 
17920     ECDVector *Vec = Entry.get<ECDVector*>();
17921     // Make sure constants are not added more than once.
17922     if (*Vec->begin() == ECD)
17923       continue;
17924 
17925     Vec->push_back(ECD);
17926   }
17927 
17928   // Emit diagnostics.
17929   for (const auto &Vec : DupVector) {
17930     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17931 
17932     // Emit warning for one enum constant.
17933     auto *FirstECD = Vec->front();
17934     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17935       << FirstECD << FirstECD->getInitVal().toString(10)
17936       << FirstECD->getSourceRange();
17937 
17938     // Emit one note for each of the remaining enum constants with
17939     // the same value.
17940     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17941       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17942         << ECD << ECD->getInitVal().toString(10)
17943         << ECD->getSourceRange();
17944   }
17945 }
17946 
17947 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17948                              bool AllowMask) const {
17949   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17950   assert(ED->isCompleteDefinition() && "expected enum definition");
17951 
17952   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17953   llvm::APInt &FlagBits = R.first->second;
17954 
17955   if (R.second) {
17956     for (auto *E : ED->enumerators()) {
17957       const auto &EVal = E->getInitVal();
17958       // Only single-bit enumerators introduce new flag values.
17959       if (EVal.isPowerOf2())
17960         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17961     }
17962   }
17963 
17964   // A value is in a flag enum if either its bits are a subset of the enum's
17965   // flag bits (the first condition) or we are allowing masks and the same is
17966   // true of its complement (the second condition). When masks are allowed, we
17967   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17968   //
17969   // While it's true that any value could be used as a mask, the assumption is
17970   // that a mask will have all of the insignificant bits set. Anything else is
17971   // likely a logic error.
17972   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17973   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17974 }
17975 
17976 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17977                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17978                          const ParsedAttributesView &Attrs) {
17979   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17980   QualType EnumType = Context.getTypeDeclType(Enum);
17981 
17982   ProcessDeclAttributeList(S, Enum, Attrs);
17983 
17984   if (Enum->isDependentType()) {
17985     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17986       EnumConstantDecl *ECD =
17987         cast_or_null<EnumConstantDecl>(Elements[i]);
17988       if (!ECD) continue;
17989 
17990       ECD->setType(EnumType);
17991     }
17992 
17993     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17994     return;
17995   }
17996 
17997   // TODO: If the result value doesn't fit in an int, it must be a long or long
17998   // long value.  ISO C does not support this, but GCC does as an extension,
17999   // emit a warning.
18000   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18001   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18002   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18003 
18004   // Verify that all the values are okay, compute the size of the values, and
18005   // reverse the list.
18006   unsigned NumNegativeBits = 0;
18007   unsigned NumPositiveBits = 0;
18008 
18009   // Keep track of whether all elements have type int.
18010   bool AllElementsInt = true;
18011 
18012   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18013     EnumConstantDecl *ECD =
18014       cast_or_null<EnumConstantDecl>(Elements[i]);
18015     if (!ECD) continue;  // Already issued a diagnostic.
18016 
18017     const llvm::APSInt &InitVal = ECD->getInitVal();
18018 
18019     // Keep track of the size of positive and negative values.
18020     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18021       NumPositiveBits = std::max(NumPositiveBits,
18022                                  (unsigned)InitVal.getActiveBits());
18023     else
18024       NumNegativeBits = std::max(NumNegativeBits,
18025                                  (unsigned)InitVal.getMinSignedBits());
18026 
18027     // Keep track of whether every enum element has type int (very common).
18028     if (AllElementsInt)
18029       AllElementsInt = ECD->getType() == Context.IntTy;
18030   }
18031 
18032   // Figure out the type that should be used for this enum.
18033   QualType BestType;
18034   unsigned BestWidth;
18035 
18036   // C++0x N3000 [conv.prom]p3:
18037   //   An rvalue of an unscoped enumeration type whose underlying
18038   //   type is not fixed can be converted to an rvalue of the first
18039   //   of the following types that can represent all the values of
18040   //   the enumeration: int, unsigned int, long int, unsigned long
18041   //   int, long long int, or unsigned long long int.
18042   // C99 6.4.4.3p2:
18043   //   An identifier declared as an enumeration constant has type int.
18044   // The C99 rule is modified by a gcc extension
18045   QualType BestPromotionType;
18046 
18047   bool Packed = Enum->hasAttr<PackedAttr>();
18048   // -fshort-enums is the equivalent to specifying the packed attribute on all
18049   // enum definitions.
18050   if (LangOpts.ShortEnums)
18051     Packed = true;
18052 
18053   // If the enum already has a type because it is fixed or dictated by the
18054   // target, promote that type instead of analyzing the enumerators.
18055   if (Enum->isComplete()) {
18056     BestType = Enum->getIntegerType();
18057     if (BestType->isPromotableIntegerType())
18058       BestPromotionType = Context.getPromotedIntegerType(BestType);
18059     else
18060       BestPromotionType = BestType;
18061 
18062     BestWidth = Context.getIntWidth(BestType);
18063   }
18064   else if (NumNegativeBits) {
18065     // If there is a negative value, figure out the smallest integer type (of
18066     // int/long/longlong) that fits.
18067     // If it's packed, check also if it fits a char or a short.
18068     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18069       BestType = Context.SignedCharTy;
18070       BestWidth = CharWidth;
18071     } else if (Packed && NumNegativeBits <= ShortWidth &&
18072                NumPositiveBits < ShortWidth) {
18073       BestType = Context.ShortTy;
18074       BestWidth = ShortWidth;
18075     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18076       BestType = Context.IntTy;
18077       BestWidth = IntWidth;
18078     } else {
18079       BestWidth = Context.getTargetInfo().getLongWidth();
18080 
18081       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18082         BestType = Context.LongTy;
18083       } else {
18084         BestWidth = Context.getTargetInfo().getLongLongWidth();
18085 
18086         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18087           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18088         BestType = Context.LongLongTy;
18089       }
18090     }
18091     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18092   } else {
18093     // If there is no negative value, figure out the smallest type that fits
18094     // all of the enumerator values.
18095     // If it's packed, check also if it fits a char or a short.
18096     if (Packed && NumPositiveBits <= CharWidth) {
18097       BestType = Context.UnsignedCharTy;
18098       BestPromotionType = Context.IntTy;
18099       BestWidth = CharWidth;
18100     } else if (Packed && NumPositiveBits <= ShortWidth) {
18101       BestType = Context.UnsignedShortTy;
18102       BestPromotionType = Context.IntTy;
18103       BestWidth = ShortWidth;
18104     } else if (NumPositiveBits <= IntWidth) {
18105       BestType = Context.UnsignedIntTy;
18106       BestWidth = IntWidth;
18107       BestPromotionType
18108         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18109                            ? Context.UnsignedIntTy : Context.IntTy;
18110     } else if (NumPositiveBits <=
18111                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18112       BestType = Context.UnsignedLongTy;
18113       BestPromotionType
18114         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18115                            ? Context.UnsignedLongTy : Context.LongTy;
18116     } else {
18117       BestWidth = Context.getTargetInfo().getLongLongWidth();
18118       assert(NumPositiveBits <= BestWidth &&
18119              "How could an initializer get larger than ULL?");
18120       BestType = Context.UnsignedLongLongTy;
18121       BestPromotionType
18122         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18123                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18124     }
18125   }
18126 
18127   // Loop over all of the enumerator constants, changing their types to match
18128   // the type of the enum if needed.
18129   for (auto *D : Elements) {
18130     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18131     if (!ECD) continue;  // Already issued a diagnostic.
18132 
18133     // Standard C says the enumerators have int type, but we allow, as an
18134     // extension, the enumerators to be larger than int size.  If each
18135     // enumerator value fits in an int, type it as an int, otherwise type it the
18136     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18137     // that X has type 'int', not 'unsigned'.
18138 
18139     // Determine whether the value fits into an int.
18140     llvm::APSInt InitVal = ECD->getInitVal();
18141 
18142     // If it fits into an integer type, force it.  Otherwise force it to match
18143     // the enum decl type.
18144     QualType NewTy;
18145     unsigned NewWidth;
18146     bool NewSign;
18147     if (!getLangOpts().CPlusPlus &&
18148         !Enum->isFixed() &&
18149         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18150       NewTy = Context.IntTy;
18151       NewWidth = IntWidth;
18152       NewSign = true;
18153     } else if (ECD->getType() == BestType) {
18154       // Already the right type!
18155       if (getLangOpts().CPlusPlus)
18156         // C++ [dcl.enum]p4: Following the closing brace of an
18157         // enum-specifier, each enumerator has the type of its
18158         // enumeration.
18159         ECD->setType(EnumType);
18160       continue;
18161     } else {
18162       NewTy = BestType;
18163       NewWidth = BestWidth;
18164       NewSign = BestType->isSignedIntegerOrEnumerationType();
18165     }
18166 
18167     // Adjust the APSInt value.
18168     InitVal = InitVal.extOrTrunc(NewWidth);
18169     InitVal.setIsSigned(NewSign);
18170     ECD->setInitVal(InitVal);
18171 
18172     // Adjust the Expr initializer and type.
18173     if (ECD->getInitExpr() &&
18174         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18175       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
18176                                                 CK_IntegralCast,
18177                                                 ECD->getInitExpr(),
18178                                                 /*base paths*/ nullptr,
18179                                                 VK_RValue));
18180     if (getLangOpts().CPlusPlus)
18181       // C++ [dcl.enum]p4: Following the closing brace of an
18182       // enum-specifier, each enumerator has the type of its
18183       // enumeration.
18184       ECD->setType(EnumType);
18185     else
18186       ECD->setType(NewTy);
18187   }
18188 
18189   Enum->completeDefinition(BestType, BestPromotionType,
18190                            NumPositiveBits, NumNegativeBits);
18191 
18192   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18193 
18194   if (Enum->isClosedFlag()) {
18195     for (Decl *D : Elements) {
18196       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18197       if (!ECD) continue;  // Already issued a diagnostic.
18198 
18199       llvm::APSInt InitVal = ECD->getInitVal();
18200       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18201           !IsValueInFlagEnum(Enum, InitVal, true))
18202         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18203           << ECD << Enum;
18204     }
18205   }
18206 
18207   // Now that the enum type is defined, ensure it's not been underaligned.
18208   if (Enum->hasAttrs())
18209     CheckAlignasUnderalignment(Enum);
18210 }
18211 
18212 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18213                                   SourceLocation StartLoc,
18214                                   SourceLocation EndLoc) {
18215   StringLiteral *AsmString = cast<StringLiteral>(expr);
18216 
18217   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18218                                                    AsmString, StartLoc,
18219                                                    EndLoc);
18220   CurContext->addDecl(New);
18221   return New;
18222 }
18223 
18224 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18225                                       IdentifierInfo* AliasName,
18226                                       SourceLocation PragmaLoc,
18227                                       SourceLocation NameLoc,
18228                                       SourceLocation AliasNameLoc) {
18229   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18230                                          LookupOrdinaryName);
18231   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18232                            AttributeCommonInfo::AS_Pragma);
18233   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18234       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18235 
18236   // If a declaration that:
18237   // 1) declares a function or a variable
18238   // 2) has external linkage
18239   // already exists, add a label attribute to it.
18240   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18241     if (isDeclExternC(PrevDecl))
18242       PrevDecl->addAttr(Attr);
18243     else
18244       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18245           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18246   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18247   } else
18248     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18249 }
18250 
18251 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18252                              SourceLocation PragmaLoc,
18253                              SourceLocation NameLoc) {
18254   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18255 
18256   if (PrevDecl) {
18257     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18258   } else {
18259     (void)WeakUndeclaredIdentifiers.insert(
18260       std::pair<IdentifierInfo*,WeakInfo>
18261         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18262   }
18263 }
18264 
18265 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18266                                 IdentifierInfo* AliasName,
18267                                 SourceLocation PragmaLoc,
18268                                 SourceLocation NameLoc,
18269                                 SourceLocation AliasNameLoc) {
18270   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18271                                     LookupOrdinaryName);
18272   WeakInfo W = WeakInfo(Name, NameLoc);
18273 
18274   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18275     if (!PrevDecl->hasAttr<AliasAttr>())
18276       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18277         DeclApplyPragmaWeak(TUScope, ND, W);
18278   } else {
18279     (void)WeakUndeclaredIdentifiers.insert(
18280       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18281   }
18282 }
18283 
18284 Decl *Sema::getObjCDeclContext() const {
18285   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18286 }
18287 
18288 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18289                                                      bool Final) {
18290   // SYCL functions can be template, so we check if they have appropriate
18291   // attribute prior to checking if it is a template.
18292   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18293     return FunctionEmissionStatus::Emitted;
18294 
18295   // Templates are emitted when they're instantiated.
18296   if (FD->isDependentContext())
18297     return FunctionEmissionStatus::TemplateDiscarded;
18298 
18299   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18300   if (LangOpts.OpenMPIsDevice) {
18301     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18302         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18303     if (DevTy.hasValue()) {
18304       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18305         OMPES = FunctionEmissionStatus::OMPDiscarded;
18306       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18307                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18308         OMPES = FunctionEmissionStatus::Emitted;
18309       }
18310     }
18311   } else if (LangOpts.OpenMP) {
18312     // In OpenMP 4.5 all the functions are host functions.
18313     if (LangOpts.OpenMP <= 45) {
18314       OMPES = FunctionEmissionStatus::Emitted;
18315     } else {
18316       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18317           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18318       // In OpenMP 5.0 or above, DevTy may be changed later by
18319       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18320       // having no value does not imply host. The emission status will be
18321       // checked again at the end of compilation unit.
18322       if (DevTy.hasValue()) {
18323         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18324           OMPES = FunctionEmissionStatus::OMPDiscarded;
18325         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18326                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18327           OMPES = FunctionEmissionStatus::Emitted;
18328       } else if (Final)
18329         OMPES = FunctionEmissionStatus::Emitted;
18330     }
18331   }
18332   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18333       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18334     return OMPES;
18335 
18336   if (LangOpts.CUDA) {
18337     // When compiling for device, host functions are never emitted.  Similarly,
18338     // when compiling for host, device and global functions are never emitted.
18339     // (Technically, we do emit a host-side stub for global functions, but this
18340     // doesn't count for our purposes here.)
18341     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18342     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18343       return FunctionEmissionStatus::CUDADiscarded;
18344     if (!LangOpts.CUDAIsDevice &&
18345         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18346       return FunctionEmissionStatus::CUDADiscarded;
18347 
18348     // Check whether this function is externally visible -- if so, it's
18349     // known-emitted.
18350     //
18351     // We have to check the GVA linkage of the function's *definition* -- if we
18352     // only have a declaration, we don't know whether or not the function will
18353     // be emitted, because (say) the definition could include "inline".
18354     FunctionDecl *Def = FD->getDefinition();
18355 
18356     if (Def &&
18357         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18358         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18359       return FunctionEmissionStatus::Emitted;
18360   }
18361 
18362   // Otherwise, the function is known-emitted if it's in our set of
18363   // known-emitted functions.
18364   return FunctionEmissionStatus::Unknown;
18365 }
18366 
18367 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18368   // Host-side references to a __global__ function refer to the stub, so the
18369   // function itself is never emitted and therefore should not be marked.
18370   // If we have host fn calls kernel fn calls host+device, the HD function
18371   // does not get instantiated on the host. We model this by omitting at the
18372   // call to the kernel from the callgraph. This ensures that, when compiling
18373   // for host, only HD functions actually called from the host get marked as
18374   // known-emitted.
18375   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18376          IdentifyCUDATarget(Callee) == CFT_Global;
18377 }
18378