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/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
110     return std::make_unique<TypeNameValidatorCCC>(*this);
111   }
112 
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119 
120 } // end anonymous namespace
121 
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146 
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154 
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157 
158   default:
159     break;
160   }
161 
162   return false;
163 }
164 
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172 
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229 
230   return FoundTypeDecl;
231 }
232 
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251 
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256 
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261 
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264 
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272 
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293 
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302 
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316 
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321 
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327 
328       return nullptr;
329     }
330 
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335 
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347 
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360 
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369 
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419 
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430 
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442 
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453 
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459 
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464 
465   assert(IIDecl && "Didn't find decl");
466 
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479 
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481 
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493 
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499 
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509 
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519 
520   return ParsedType::make(T);
521 }
522 
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539 
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554 
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559 
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577 
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586 
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588 
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594 
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602 
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623 
624   return DeclSpec::TST_unspecified;
625 }
626 
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645 
646     const Type *Ty = SS->getScopeRep()->getAsType();
647 
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656 
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668 
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706 
707       if (!CanRecover)
708         return;
709 
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723 
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738 
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741 
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754 
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766 
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772 
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776 
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780 
781   return false;
782 }
783 
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796 
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800 
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804 
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808 
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813 
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818 
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823 
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837 
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840 
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847 
848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
849                                             IdentifierInfo *&Name,
850                                             SourceLocation NameLoc,
851                                             const Token &NextToken,
852                                             CorrectionCandidateCallback *CCC) {
853   DeclarationNameInfo NameInfo(Name, NameLoc);
854   ObjCMethodDecl *CurMethod = getCurMethodDecl();
855 
856   assert(NextToken.isNot(tok::coloncolon) &&
857          "parse nested name specifiers before calling ClassifyName");
858   if (getLangOpts().CPlusPlus && SS.isSet() &&
859       isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   if (SS.isInvalid())
871     return NameClassification::Error();
872 
873   // For unqualified lookup in a class template in MSVC mode, look into
874   // dependent base classes where the primary class template is known.
875   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
876     if (ParsedType TypeInBase =
877             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
878       return TypeInBase;
879   }
880 
881   // Perform lookup for Objective-C instance variables (including automatically
882   // synthesized instance variables), if we're in an Objective-C method.
883   // FIXME: This lookup really, really needs to be folded in to the normal
884   // unqualified lookup mechanism.
885   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
886     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
887     if (Ivar.isInvalid())
888       return NameClassification::Error();
889     if (Ivar.isUsable())
890       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
891 
892     // We defer builtin creation until after ivar lookup inside ObjC methods.
893     if (Result.empty())
894       LookupBuiltin(Result);
895   }
896 
897   bool SecondTry = false;
898   bool IsFilteredTemplateName = false;
899 
900 Corrected:
901   switch (Result.getResultKind()) {
902   case LookupResult::NotFound:
903     // If an unqualified-id is followed by a '(', then we have a function
904     // call.
905     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
906       // In C++, this is an ADL-only call.
907       // FIXME: Reference?
908       if (getLangOpts().CPlusPlus)
909         return NameClassification::UndeclaredNonType();
910 
911       // C90 6.3.2.2:
912       //   If the expression that precedes the parenthesized argument list in a
913       //   function call consists solely of an identifier, and if no
914       //   declaration is visible for this identifier, the identifier is
915       //   implicitly declared exactly as if, in the innermost block containing
916       //   the function call, the declaration
917       //
918       //     extern int identifier ();
919       //
920       //   appeared.
921       //
922       // We also allow this in C99 as an extension.
923       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
924         return NameClassification::NonType(D);
925     }
926 
927     if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
928       // In C++20 onwards, this could be an ADL-only call to a function
929       // template, and we're required to assume that this is a template name.
930       //
931       // FIXME: Find a way to still do typo correction in this case.
932       TemplateName Template =
933           Context.getAssumedTemplateName(NameInfo.getName());
934       return NameClassification::UndeclaredTemplate(Template);
935     }
936 
937     // In C, we first see whether there is a tag type by the same name, in
938     // which case it's likely that the user just forgot to write "enum",
939     // "struct", or "union".
940     if (!getLangOpts().CPlusPlus && !SecondTry &&
941         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
942       break;
943     }
944 
945     // Perform typo correction to determine if there is another name that is
946     // close to this name.
947     if (!SecondTry && CCC) {
948       SecondTry = true;
949       if (TypoCorrection Corrected =
950               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
951                           &SS, *CCC, CTK_ErrorRecovery)) {
952         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
953         unsigned QualifiedDiag = diag::err_no_member_suggest;
954 
955         NamedDecl *FirstDecl = Corrected.getFoundDecl();
956         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
957         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
958             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
959           UnqualifiedDiag = diag::err_no_template_suggest;
960           QualifiedDiag = diag::err_no_member_template_suggest;
961         } else if (UnderlyingFirstDecl &&
962                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
963                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
964                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
965           UnqualifiedDiag = diag::err_unknown_typename_suggest;
966           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
967         }
968 
969         if (SS.isEmpty()) {
970           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
971         } else {// FIXME: is this even reachable? Test it.
972           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
973           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
974                                   Name->getName().equals(CorrectedStr);
975           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
976                                     << Name << computeDeclContext(SS, false)
977                                     << DroppedSpecifier << SS.getRange());
978         }
979 
980         // Update the name, so that the caller has the new name.
981         Name = Corrected.getCorrectionAsIdentifierInfo();
982 
983         // Typo correction corrected to a keyword.
984         if (Corrected.isKeyword())
985           return Name;
986 
987         // Also update the LookupResult...
988         // FIXME: This should probably go away at some point
989         Result.clear();
990         Result.setLookupName(Corrected.getCorrection());
991         if (FirstDecl)
992           Result.addDecl(FirstDecl);
993 
994         // If we found an Objective-C instance variable, let
995         // LookupInObjCMethod build the appropriate expression to
996         // reference the ivar.
997         // FIXME: This is a gross hack.
998         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
999           DeclResult R =
1000               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1001           if (R.isInvalid())
1002             return NameClassification::Error();
1003           if (R.isUsable())
1004             return NameClassification::NonType(Ivar);
1005         }
1006 
1007         goto Corrected;
1008       }
1009     }
1010 
1011     // We failed to correct; just fall through and let the parser deal with it.
1012     Result.suppressDiagnostics();
1013     return NameClassification::Unknown();
1014 
1015   case LookupResult::NotFoundInCurrentInstantiation: {
1016     // We performed name lookup into the current instantiation, and there were
1017     // dependent bases, so we treat this result the same way as any other
1018     // dependent nested-name-specifier.
1019 
1020     // C++ [temp.res]p2:
1021     //   A name used in a template declaration or definition and that is
1022     //   dependent on a template-parameter is assumed not to name a type
1023     //   unless the applicable name lookup finds a type name or the name is
1024     //   qualified by the keyword typename.
1025     //
1026     // FIXME: If the next token is '<', we might want to ask the parser to
1027     // perform some heroics to see if we actually have a
1028     // template-argument-list, which would indicate a missing 'template'
1029     // keyword here.
1030     return NameClassification::DependentNonType();
1031   }
1032 
1033   case LookupResult::Found:
1034   case LookupResult::FoundOverloaded:
1035   case LookupResult::FoundUnresolvedValue:
1036     break;
1037 
1038   case LookupResult::Ambiguous:
1039     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1040         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1041                                       /*AllowDependent=*/false)) {
1042       // C++ [temp.local]p3:
1043       //   A lookup that finds an injected-class-name (10.2) can result in an
1044       //   ambiguity in certain cases (for example, if it is found in more than
1045       //   one base class). If all of the injected-class-names that are found
1046       //   refer to specializations of the same class template, and if the name
1047       //   is followed by a template-argument-list, the reference refers to the
1048       //   class template itself and not a specialization thereof, and is not
1049       //   ambiguous.
1050       //
1051       // This filtering can make an ambiguous result into an unambiguous one,
1052       // so try again after filtering out template names.
1053       FilterAcceptableTemplateNames(Result);
1054       if (!Result.isAmbiguous()) {
1055         IsFilteredTemplateName = true;
1056         break;
1057       }
1058     }
1059 
1060     // Diagnose the ambiguity and return an error.
1061     return NameClassification::Error();
1062   }
1063 
1064   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1065       (IsFilteredTemplateName ||
1066        hasAnyAcceptableTemplateNames(
1067            Result, /*AllowFunctionTemplates=*/true,
1068            /*AllowDependent=*/false,
1069            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1070                getLangOpts().CPlusPlus2a))) {
1071     // C++ [temp.names]p3:
1072     //   After name lookup (3.4) finds that a name is a template-name or that
1073     //   an operator-function-id or a literal- operator-id refers to a set of
1074     //   overloaded functions any member of which is a function template if
1075     //   this is followed by a <, the < is always taken as the delimiter of a
1076     //   template-argument-list and never as the less-than operator.
1077     // C++2a [temp.names]p2:
1078     //   A name is also considered to refer to a template if it is an
1079     //   unqualified-id followed by a < and name lookup finds either one
1080     //   or more functions or finds nothing.
1081     if (!IsFilteredTemplateName)
1082       FilterAcceptableTemplateNames(Result);
1083 
1084     bool IsFunctionTemplate;
1085     bool IsVarTemplate;
1086     TemplateName Template;
1087     if (Result.end() - Result.begin() > 1) {
1088       IsFunctionTemplate = true;
1089       Template = Context.getOverloadedTemplateName(Result.begin(),
1090                                                    Result.end());
1091     } else if (!Result.empty()) {
1092       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1093           *Result.begin(), /*AllowFunctionTemplates=*/true,
1094           /*AllowDependent=*/false));
1095       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1096       IsVarTemplate = isa<VarTemplateDecl>(TD);
1097 
1098       if (SS.isNotEmpty())
1099         Template =
1100             Context.getQualifiedTemplateName(SS.getScopeRep(),
1101                                              /*TemplateKeyword=*/false, TD);
1102       else
1103         Template = TemplateName(TD);
1104     } else {
1105       // All results were non-template functions. This is a function template
1106       // name.
1107       IsFunctionTemplate = true;
1108       Template = Context.getAssumedTemplateName(NameInfo.getName());
1109     }
1110 
1111     if (IsFunctionTemplate) {
1112       // Function templates always go through overload resolution, at which
1113       // point we'll perform the various checks (e.g., accessibility) we need
1114       // to based on which function we selected.
1115       Result.suppressDiagnostics();
1116 
1117       return NameClassification::FunctionTemplate(Template);
1118     }
1119 
1120     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1121                          : NameClassification::TypeTemplate(Template);
1122   }
1123 
1124   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1125   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1126     DiagnoseUseOfDecl(Type, NameLoc);
1127     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1128     QualType T = Context.getTypeDeclType(Type);
1129     if (SS.isNotEmpty())
1130       return buildNestedType(*this, SS, T, NameLoc);
1131     return ParsedType::make(T);
1132   }
1133 
1134   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1135   if (!Class) {
1136     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1137     if (ObjCCompatibleAliasDecl *Alias =
1138             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1139       Class = Alias->getClassInterface();
1140   }
1141 
1142   if (Class) {
1143     DiagnoseUseOfDecl(Class, NameLoc);
1144 
1145     if (NextToken.is(tok::period)) {
1146       // Interface. <something> is parsed as a property reference expression.
1147       // Just return "unknown" as a fall-through for now.
1148       Result.suppressDiagnostics();
1149       return NameClassification::Unknown();
1150     }
1151 
1152     QualType T = Context.getObjCInterfaceType(Class);
1153     return ParsedType::make(T);
1154   }
1155 
1156   // We can have a type template here if we're classifying a template argument.
1157   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1158       !isa<VarTemplateDecl>(FirstDecl))
1159     return NameClassification::TypeTemplate(
1160         TemplateName(cast<TemplateDecl>(FirstDecl)));
1161 
1162   // Check for a tag type hidden by a non-type decl in a few cases where it
1163   // seems likely a type is wanted instead of the non-type that was found.
1164   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1165   if ((NextToken.is(tok::identifier) ||
1166        (NextIsOp &&
1167         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1168       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1169     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1170     DiagnoseUseOfDecl(Type, NameLoc);
1171     QualType T = Context.getTypeDeclType(Type);
1172     if (SS.isNotEmpty())
1173       return buildNestedType(*this, SS, T, NameLoc);
1174     return ParsedType::make(T);
1175   }
1176 
1177   // FIXME: This is context-dependent. We need to defer building the member
1178   // expression until the classification is consumed.
1179   if (FirstDecl->isCXXClassMember())
1180     return NameClassification::ContextIndependentExpr(
1181         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1182                                         S));
1183 
1184   // If we already know which single declaration is referenced, just annotate
1185   // that declaration directly.
1186   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1187   if (Result.isSingleResult() && !ADL)
1188     return NameClassification::NonType(Result.getRepresentativeDecl());
1189 
1190   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1191   // context in which we performed classification, so it's safe to do now.
1192   return NameClassification::ContextIndependentExpr(
1193       BuildDeclarationNameExpr(SS, Result, ADL));
1194 }
1195 
1196 ExprResult
1197 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1198                                              SourceLocation NameLoc) {
1199   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1200   CXXScopeSpec SS;
1201   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1202   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1203 }
1204 
1205 ExprResult
1206 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1207                                             IdentifierInfo *Name,
1208                                             SourceLocation NameLoc,
1209                                             bool IsAddressOfOperand) {
1210   DeclarationNameInfo NameInfo(Name, NameLoc);
1211   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1212                                     NameInfo, IsAddressOfOperand,
1213                                     /*TemplateArgs=*/nullptr);
1214 }
1215 
1216 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1217                                               NamedDecl *Found,
1218                                               SourceLocation NameLoc,
1219                                               const Token &NextToken) {
1220   if (getCurMethodDecl() && SS.isEmpty())
1221     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1222       return BuildIvarRefExpr(S, NameLoc, Ivar);
1223 
1224   // Reconstruct the lookup result.
1225   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1226   Result.addDecl(Found);
1227   Result.resolveKind();
1228 
1229   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1230   return BuildDeclarationNameExpr(SS, Result, ADL);
1231 }
1232 
1233 Sema::TemplateNameKindForDiagnostics
1234 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1235   auto *TD = Name.getAsTemplateDecl();
1236   if (!TD)
1237     return TemplateNameKindForDiagnostics::DependentTemplate;
1238   if (isa<ClassTemplateDecl>(TD))
1239     return TemplateNameKindForDiagnostics::ClassTemplate;
1240   if (isa<FunctionTemplateDecl>(TD))
1241     return TemplateNameKindForDiagnostics::FunctionTemplate;
1242   if (isa<VarTemplateDecl>(TD))
1243     return TemplateNameKindForDiagnostics::VarTemplate;
1244   if (isa<TypeAliasTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::AliasTemplate;
1246   if (isa<TemplateTemplateParmDecl>(TD))
1247     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1248   if (isa<ConceptDecl>(TD))
1249     return TemplateNameKindForDiagnostics::Concept;
1250   return TemplateNameKindForDiagnostics::DependentTemplate;
1251 }
1252 
1253 // Determines the context to return to after temporarily entering a
1254 // context.  This depends in an unnecessarily complicated way on the
1255 // exact ordering of callbacks from the parser.
1256 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1257 
1258   // Functions defined inline within classes aren't parsed until we've
1259   // finished parsing the top-level class, so the top-level class is
1260   // the context we'll need to return to.
1261   // A Lambda call operator whose parent is a class must not be treated
1262   // as an inline member function.  A Lambda can be used legally
1263   // either as an in-class member initializer or a default argument.  These
1264   // are parsed once the class has been marked complete and so the containing
1265   // context would be the nested class (when the lambda is defined in one);
1266   // If the class is not complete, then the lambda is being used in an
1267   // ill-formed fashion (such as to specify the width of a bit-field, or
1268   // in an array-bound) - in which case we still want to return the
1269   // lexically containing DC (which could be a nested class).
1270   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1271     DC = DC->getLexicalParent();
1272 
1273     // A function not defined within a class will always return to its
1274     // lexical context.
1275     if (!isa<CXXRecordDecl>(DC))
1276       return DC;
1277 
1278     // A C++ inline method/friend is parsed *after* the topmost class
1279     // it was declared in is fully parsed ("complete");  the topmost
1280     // class is the context we need to return to.
1281     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1282       DC = RD;
1283 
1284     // Return the declaration context of the topmost class the inline method is
1285     // declared in.
1286     return DC;
1287   }
1288 
1289   return DC->getLexicalParent();
1290 }
1291 
1292 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1293   assert(getContainingDC(DC) == CurContext &&
1294       "The next DeclContext should be lexically contained in the current one.");
1295   CurContext = DC;
1296   S->setEntity(DC);
1297 }
1298 
1299 void Sema::PopDeclContext() {
1300   assert(CurContext && "DeclContext imbalance!");
1301 
1302   CurContext = getContainingDC(CurContext);
1303   assert(CurContext && "Popped translation unit!");
1304 }
1305 
1306 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1307                                                                     Decl *D) {
1308   // Unlike PushDeclContext, the context to which we return is not necessarily
1309   // the containing DC of TD, because the new context will be some pre-existing
1310   // TagDecl definition instead of a fresh one.
1311   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1312   CurContext = cast<TagDecl>(D)->getDefinition();
1313   assert(CurContext && "skipping definition of undefined tag");
1314   // Start lookups from the parent of the current context; we don't want to look
1315   // into the pre-existing complete definition.
1316   S->setEntity(CurContext->getLookupParent());
1317   return Result;
1318 }
1319 
1320 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1321   CurContext = static_cast<decltype(CurContext)>(Context);
1322 }
1323 
1324 /// EnterDeclaratorContext - Used when we must lookup names in the context
1325 /// of a declarator's nested name specifier.
1326 ///
1327 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1328   // C++0x [basic.lookup.unqual]p13:
1329   //   A name used in the definition of a static data member of class
1330   //   X (after the qualified-id of the static member) is looked up as
1331   //   if the name was used in a member function of X.
1332   // C++0x [basic.lookup.unqual]p14:
1333   //   If a variable member of a namespace is defined outside of the
1334   //   scope of its namespace then any name used in the definition of
1335   //   the variable member (after the declarator-id) is looked up as
1336   //   if the definition of the variable member occurred in its
1337   //   namespace.
1338   // Both of these imply that we should push a scope whose context
1339   // is the semantic context of the declaration.  We can't use
1340   // PushDeclContext here because that context is not necessarily
1341   // lexically contained in the current context.  Fortunately,
1342   // the containing scope should have the appropriate information.
1343 
1344   assert(!S->getEntity() && "scope already has entity");
1345 
1346 #ifndef NDEBUG
1347   Scope *Ancestor = S->getParent();
1348   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1349   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1350 #endif
1351 
1352   CurContext = DC;
1353   S->setEntity(DC);
1354 }
1355 
1356 void Sema::ExitDeclaratorContext(Scope *S) {
1357   assert(S->getEntity() == CurContext && "Context imbalance!");
1358 
1359   // Switch back to the lexical context.  The safety of this is
1360   // enforced by an assert in EnterDeclaratorContext.
1361   Scope *Ancestor = S->getParent();
1362   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1363   CurContext = Ancestor->getEntity();
1364 
1365   // We don't need to do anything with the scope, which is going to
1366   // disappear.
1367 }
1368 
1369 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1370   // We assume that the caller has already called
1371   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1372   FunctionDecl *FD = D->getAsFunction();
1373   if (!FD)
1374     return;
1375 
1376   // Same implementation as PushDeclContext, but enters the context
1377   // from the lexical parent, rather than the top-level class.
1378   assert(CurContext == FD->getLexicalParent() &&
1379     "The next DeclContext should be lexically contained in the current one.");
1380   CurContext = FD;
1381   S->setEntity(CurContext);
1382 
1383   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1384     ParmVarDecl *Param = FD->getParamDecl(P);
1385     // If the parameter has an identifier, then add it to the scope
1386     if (Param->getIdentifier()) {
1387       S->AddDecl(Param);
1388       IdResolver.AddDecl(Param);
1389     }
1390   }
1391 }
1392 
1393 void Sema::ActOnExitFunctionContext() {
1394   // Same implementation as PopDeclContext, but returns to the lexical parent,
1395   // rather than the top-level class.
1396   assert(CurContext && "DeclContext imbalance!");
1397   CurContext = CurContext->getLexicalParent();
1398   assert(CurContext && "Popped translation unit!");
1399 }
1400 
1401 /// Determine whether we allow overloading of the function
1402 /// PrevDecl with another declaration.
1403 ///
1404 /// This routine determines whether overloading is possible, not
1405 /// whether some new function is actually an overload. It will return
1406 /// true in C++ (where we can always provide overloads) or, as an
1407 /// extension, in C when the previous function is already an
1408 /// overloaded function declaration or has the "overloadable"
1409 /// attribute.
1410 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1411                                        ASTContext &Context,
1412                                        const FunctionDecl *New) {
1413   if (Context.getLangOpts().CPlusPlus)
1414     return true;
1415 
1416   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1417     return true;
1418 
1419   return Previous.getResultKind() == LookupResult::Found &&
1420          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1421           New->hasAttr<OverloadableAttr>());
1422 }
1423 
1424 /// Add this decl to the scope shadowed decl chains.
1425 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1426   // Move up the scope chain until we find the nearest enclosing
1427   // non-transparent context. The declaration will be introduced into this
1428   // scope.
1429   while (S->getEntity() && S->getEntity()->isTransparentContext())
1430     S = S->getParent();
1431 
1432   // Add scoped declarations into their context, so that they can be
1433   // found later. Declarations without a context won't be inserted
1434   // into any context.
1435   if (AddToContext)
1436     CurContext->addDecl(D);
1437 
1438   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1439   // are function-local declarations.
1440   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1441       !D->getDeclContext()->getRedeclContext()->Equals(
1442         D->getLexicalDeclContext()->getRedeclContext()) &&
1443       !D->getLexicalDeclContext()->isFunctionOrMethod())
1444     return;
1445 
1446   // Template instantiations should also not be pushed into scope.
1447   if (isa<FunctionDecl>(D) &&
1448       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1449     return;
1450 
1451   // If this replaces anything in the current scope,
1452   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1453                                IEnd = IdResolver.end();
1454   for (; I != IEnd; ++I) {
1455     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1456       S->RemoveDecl(*I);
1457       IdResolver.RemoveDecl(*I);
1458 
1459       // Should only need to replace one decl.
1460       break;
1461     }
1462   }
1463 
1464   S->AddDecl(D);
1465 
1466   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1467     // Implicitly-generated labels may end up getting generated in an order that
1468     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1469     // the label at the appropriate place in the identifier chain.
1470     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1471       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1472       if (IDC == CurContext) {
1473         if (!S->isDeclScope(*I))
1474           continue;
1475       } else if (IDC->Encloses(CurContext))
1476         break;
1477     }
1478 
1479     IdResolver.InsertDeclAfter(I, D);
1480   } else {
1481     IdResolver.AddDecl(D);
1482   }
1483 }
1484 
1485 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1486                          bool AllowInlineNamespace) {
1487   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1488 }
1489 
1490 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1491   DeclContext *TargetDC = DC->getPrimaryContext();
1492   do {
1493     if (DeclContext *ScopeDC = S->getEntity())
1494       if (ScopeDC->getPrimaryContext() == TargetDC)
1495         return S;
1496   } while ((S = S->getParent()));
1497 
1498   return nullptr;
1499 }
1500 
1501 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1502                                             DeclContext*,
1503                                             ASTContext&);
1504 
1505 /// Filters out lookup results that don't fall within the given scope
1506 /// as determined by isDeclInScope.
1507 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1508                                 bool ConsiderLinkage,
1509                                 bool AllowInlineNamespace) {
1510   LookupResult::Filter F = R.makeFilter();
1511   while (F.hasNext()) {
1512     NamedDecl *D = F.next();
1513 
1514     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1515       continue;
1516 
1517     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1518       continue;
1519 
1520     F.erase();
1521   }
1522 
1523   F.done();
1524 }
1525 
1526 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1527 /// have compatible owning modules.
1528 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1529   // FIXME: The Modules TS is not clear about how friend declarations are
1530   // to be treated. It's not meaningful to have different owning modules for
1531   // linkage in redeclarations of the same entity, so for now allow the
1532   // redeclaration and change the owning modules to match.
1533   if (New->getFriendObjectKind() &&
1534       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1535     New->setLocalOwningModule(Old->getOwningModule());
1536     makeMergedDefinitionVisible(New);
1537     return false;
1538   }
1539 
1540   Module *NewM = New->getOwningModule();
1541   Module *OldM = Old->getOwningModule();
1542 
1543   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1544     NewM = NewM->Parent;
1545   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1546     OldM = OldM->Parent;
1547 
1548   if (NewM == OldM)
1549     return false;
1550 
1551   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1552   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1553   if (NewIsModuleInterface || OldIsModuleInterface) {
1554     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1555     //   if a declaration of D [...] appears in the purview of a module, all
1556     //   other such declarations shall appear in the purview of the same module
1557     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1558       << New
1559       << NewIsModuleInterface
1560       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1561       << OldIsModuleInterface
1562       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1563     Diag(Old->getLocation(), diag::note_previous_declaration);
1564     New->setInvalidDecl();
1565     return true;
1566   }
1567 
1568   return false;
1569 }
1570 
1571 static bool isUsingDecl(NamedDecl *D) {
1572   return isa<UsingShadowDecl>(D) ||
1573          isa<UnresolvedUsingTypenameDecl>(D) ||
1574          isa<UnresolvedUsingValueDecl>(D);
1575 }
1576 
1577 /// Removes using shadow declarations from the lookup results.
1578 static void RemoveUsingDecls(LookupResult &R) {
1579   LookupResult::Filter F = R.makeFilter();
1580   while (F.hasNext())
1581     if (isUsingDecl(F.next()))
1582       F.erase();
1583 
1584   F.done();
1585 }
1586 
1587 /// Check for this common pattern:
1588 /// @code
1589 /// class S {
1590 ///   S(const S&); // DO NOT IMPLEMENT
1591 ///   void operator=(const S&); // DO NOT IMPLEMENT
1592 /// };
1593 /// @endcode
1594 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1595   // FIXME: Should check for private access too but access is set after we get
1596   // the decl here.
1597   if (D->doesThisDeclarationHaveABody())
1598     return false;
1599 
1600   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1601     return CD->isCopyConstructor();
1602   return D->isCopyAssignmentOperator();
1603 }
1604 
1605 // We need this to handle
1606 //
1607 // typedef struct {
1608 //   void *foo() { return 0; }
1609 // } A;
1610 //
1611 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1612 // for example. If 'A', foo will have external linkage. If we have '*A',
1613 // foo will have no linkage. Since we can't know until we get to the end
1614 // of the typedef, this function finds out if D might have non-external linkage.
1615 // Callers should verify at the end of the TU if it D has external linkage or
1616 // not.
1617 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1618   const DeclContext *DC = D->getDeclContext();
1619   while (!DC->isTranslationUnit()) {
1620     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1621       if (!RD->hasNameForLinkage())
1622         return true;
1623     }
1624     DC = DC->getParent();
1625   }
1626 
1627   return !D->isExternallyVisible();
1628 }
1629 
1630 // FIXME: This needs to be refactored; some other isInMainFile users want
1631 // these semantics.
1632 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1633   if (S.TUKind != TU_Complete)
1634     return false;
1635   return S.SourceMgr.isInMainFile(Loc);
1636 }
1637 
1638 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1639   assert(D);
1640 
1641   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1642     return false;
1643 
1644   // Ignore all entities declared within templates, and out-of-line definitions
1645   // of members of class templates.
1646   if (D->getDeclContext()->isDependentContext() ||
1647       D->getLexicalDeclContext()->isDependentContext())
1648     return false;
1649 
1650   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1652       return false;
1653     // A non-out-of-line declaration of a member specialization was implicitly
1654     // instantiated; it's the out-of-line declaration that we're interested in.
1655     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1656         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1657       return false;
1658 
1659     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1660       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1661         return false;
1662     } else {
1663       // 'static inline' functions are defined in headers; don't warn.
1664       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1665         return false;
1666     }
1667 
1668     if (FD->doesThisDeclarationHaveABody() &&
1669         Context.DeclMustBeEmitted(FD))
1670       return false;
1671   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1672     // Constants and utility variables are defined in headers with internal
1673     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1674     // like "inline".)
1675     if (!isMainFileLoc(*this, VD->getLocation()))
1676       return false;
1677 
1678     if (Context.DeclMustBeEmitted(VD))
1679       return false;
1680 
1681     if (VD->isStaticDataMember() &&
1682         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1683       return false;
1684     if (VD->isStaticDataMember() &&
1685         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1686         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1687       return false;
1688 
1689     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1690       return false;
1691   } else {
1692     return false;
1693   }
1694 
1695   // Only warn for unused decls internal to the translation unit.
1696   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1697   // for inline functions defined in the main source file, for instance.
1698   return mightHaveNonExternalLinkage(D);
1699 }
1700 
1701 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1702   if (!D)
1703     return;
1704 
1705   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1706     const FunctionDecl *First = FD->getFirstDecl();
1707     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1708       return; // First should already be in the vector.
1709   }
1710 
1711   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1712     const VarDecl *First = VD->getFirstDecl();
1713     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1714       return; // First should already be in the vector.
1715   }
1716 
1717   if (ShouldWarnIfUnusedFileScopedDecl(D))
1718     UnusedFileScopedDecls.push_back(D);
1719 }
1720 
1721 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1722   if (D->isInvalidDecl())
1723     return false;
1724 
1725   bool Referenced = false;
1726   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1727     // For a decomposition declaration, warn if none of the bindings are
1728     // referenced, instead of if the variable itself is referenced (which
1729     // it is, by the bindings' expressions).
1730     for (auto *BD : DD->bindings()) {
1731       if (BD->isReferenced()) {
1732         Referenced = true;
1733         break;
1734       }
1735     }
1736   } else if (!D->getDeclName()) {
1737     return false;
1738   } else if (D->isReferenced() || D->isUsed()) {
1739     Referenced = true;
1740   }
1741 
1742   if (Referenced || D->hasAttr<UnusedAttr>() ||
1743       D->hasAttr<ObjCPreciseLifetimeAttr>())
1744     return false;
1745 
1746   if (isa<LabelDecl>(D))
1747     return true;
1748 
1749   // Except for labels, we only care about unused decls that are local to
1750   // functions.
1751   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1752   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1753     // For dependent types, the diagnostic is deferred.
1754     WithinFunction =
1755         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1756   if (!WithinFunction)
1757     return false;
1758 
1759   if (isa<TypedefNameDecl>(D))
1760     return true;
1761 
1762   // White-list anything that isn't a local variable.
1763   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1764     return false;
1765 
1766   // Types of valid local variables should be complete, so this should succeed.
1767   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1768 
1769     // White-list anything with an __attribute__((unused)) type.
1770     const auto *Ty = VD->getType().getTypePtr();
1771 
1772     // Only look at the outermost level of typedef.
1773     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1774       if (TT->getDecl()->hasAttr<UnusedAttr>())
1775         return false;
1776     }
1777 
1778     // If we failed to complete the type for some reason, or if the type is
1779     // dependent, don't diagnose the variable.
1780     if (Ty->isIncompleteType() || Ty->isDependentType())
1781       return false;
1782 
1783     // Look at the element type to ensure that the warning behaviour is
1784     // consistent for both scalars and arrays.
1785     Ty = Ty->getBaseElementTypeUnsafe();
1786 
1787     if (const TagType *TT = Ty->getAs<TagType>()) {
1788       const TagDecl *Tag = TT->getDecl();
1789       if (Tag->hasAttr<UnusedAttr>())
1790         return false;
1791 
1792       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1793         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1794           return false;
1795 
1796         if (const Expr *Init = VD->getInit()) {
1797           if (const ExprWithCleanups *Cleanups =
1798                   dyn_cast<ExprWithCleanups>(Init))
1799             Init = Cleanups->getSubExpr();
1800           const CXXConstructExpr *Construct =
1801             dyn_cast<CXXConstructExpr>(Init);
1802           if (Construct && !Construct->isElidable()) {
1803             CXXConstructorDecl *CD = Construct->getConstructor();
1804             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1805                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1806               return false;
1807           }
1808 
1809           // Suppress the warning if we don't know how this is constructed, and
1810           // it could possibly be non-trivial constructor.
1811           if (Init->isTypeDependent())
1812             for (const CXXConstructorDecl *Ctor : RD->ctors())
1813               if (!Ctor->isTrivial())
1814                 return false;
1815         }
1816       }
1817     }
1818 
1819     // TODO: __attribute__((unused)) templates?
1820   }
1821 
1822   return true;
1823 }
1824 
1825 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1826                                      FixItHint &Hint) {
1827   if (isa<LabelDecl>(D)) {
1828     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1829         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1830         true);
1831     if (AfterColon.isInvalid())
1832       return;
1833     Hint = FixItHint::CreateRemoval(
1834         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1835   }
1836 }
1837 
1838 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1839   if (D->getTypeForDecl()->isDependentType())
1840     return;
1841 
1842   for (auto *TmpD : D->decls()) {
1843     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1844       DiagnoseUnusedDecl(T);
1845     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1846       DiagnoseUnusedNestedTypedefs(R);
1847   }
1848 }
1849 
1850 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1851 /// unless they are marked attr(unused).
1852 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1853   if (!ShouldDiagnoseUnusedDecl(D))
1854     return;
1855 
1856   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1857     // typedefs can be referenced later on, so the diagnostics are emitted
1858     // at end-of-translation-unit.
1859     UnusedLocalTypedefNameCandidates.insert(TD);
1860     return;
1861   }
1862 
1863   FixItHint Hint;
1864   GenerateFixForUnusedDecl(D, Context, Hint);
1865 
1866   unsigned DiagID;
1867   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1868     DiagID = diag::warn_unused_exception_param;
1869   else if (isa<LabelDecl>(D))
1870     DiagID = diag::warn_unused_label;
1871   else
1872     DiagID = diag::warn_unused_variable;
1873 
1874   Diag(D->getLocation(), DiagID) << D << Hint;
1875 }
1876 
1877 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1878   // Verify that we have no forward references left.  If so, there was a goto
1879   // or address of a label taken, but no definition of it.  Label fwd
1880   // definitions are indicated with a null substmt which is also not a resolved
1881   // MS inline assembly label name.
1882   bool Diagnose = false;
1883   if (L->isMSAsmLabel())
1884     Diagnose = !L->isResolvedMSAsmLabel();
1885   else
1886     Diagnose = L->getStmt() == nullptr;
1887   if (Diagnose)
1888     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1889 }
1890 
1891 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1892   S->mergeNRVOIntoParent();
1893 
1894   if (S->decl_empty()) return;
1895   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1896          "Scope shouldn't contain decls!");
1897 
1898   for (auto *TmpD : S->decls()) {
1899     assert(TmpD && "This decl didn't get pushed??");
1900 
1901     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1902     NamedDecl *D = cast<NamedDecl>(TmpD);
1903 
1904     // Diagnose unused variables in this scope.
1905     if (!S->hasUnrecoverableErrorOccurred()) {
1906       DiagnoseUnusedDecl(D);
1907       if (const auto *RD = dyn_cast<RecordDecl>(D))
1908         DiagnoseUnusedNestedTypedefs(RD);
1909     }
1910 
1911     if (!D->getDeclName()) continue;
1912 
1913     // If this was a forward reference to a label, verify it was defined.
1914     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1915       CheckPoppedLabel(LD, *this);
1916 
1917     // Remove this name from our lexical scope, and warn on it if we haven't
1918     // already.
1919     IdResolver.RemoveDecl(D);
1920     auto ShadowI = ShadowingDecls.find(D);
1921     if (ShadowI != ShadowingDecls.end()) {
1922       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1923         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1924             << D << FD << FD->getParent();
1925         Diag(FD->getLocation(), diag::note_previous_declaration);
1926       }
1927       ShadowingDecls.erase(ShadowI);
1928     }
1929   }
1930 }
1931 
1932 /// Look for an Objective-C class in the translation unit.
1933 ///
1934 /// \param Id The name of the Objective-C class we're looking for. If
1935 /// typo-correction fixes this name, the Id will be updated
1936 /// to the fixed name.
1937 ///
1938 /// \param IdLoc The location of the name in the translation unit.
1939 ///
1940 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1941 /// if there is no class with the given name.
1942 ///
1943 /// \returns The declaration of the named Objective-C class, or NULL if the
1944 /// class could not be found.
1945 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1946                                               SourceLocation IdLoc,
1947                                               bool DoTypoCorrection) {
1948   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1949   // creation from this context.
1950   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1951 
1952   if (!IDecl && DoTypoCorrection) {
1953     // Perform typo correction at the given location, but only if we
1954     // find an Objective-C class name.
1955     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1956     if (TypoCorrection C =
1957             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1958                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1959       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1960       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1961       Id = IDecl->getIdentifier();
1962     }
1963   }
1964   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1965   // This routine must always return a class definition, if any.
1966   if (Def && Def->getDefinition())
1967       Def = Def->getDefinition();
1968   return Def;
1969 }
1970 
1971 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1972 /// from S, where a non-field would be declared. This routine copes
1973 /// with the difference between C and C++ scoping rules in structs and
1974 /// unions. For example, the following code is well-formed in C but
1975 /// ill-formed in C++:
1976 /// @code
1977 /// struct S6 {
1978 ///   enum { BAR } e;
1979 /// };
1980 ///
1981 /// void test_S6() {
1982 ///   struct S6 a;
1983 ///   a.e = BAR;
1984 /// }
1985 /// @endcode
1986 /// For the declaration of BAR, this routine will return a different
1987 /// scope. The scope S will be the scope of the unnamed enumeration
1988 /// within S6. In C++, this routine will return the scope associated
1989 /// with S6, because the enumeration's scope is a transparent
1990 /// context but structures can contain non-field names. In C, this
1991 /// routine will return the translation unit scope, since the
1992 /// enumeration's scope is a transparent context and structures cannot
1993 /// contain non-field names.
1994 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1995   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1996          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1997          (S->isClassScope() && !getLangOpts().CPlusPlus))
1998     S = S->getParent();
1999   return S;
2000 }
2001 
2002 /// Looks up the declaration of "struct objc_super" and
2003 /// saves it for later use in building builtin declaration of
2004 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2005 /// pre-existing declaration exists no action takes place.
2006 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2007                                         IdentifierInfo *II) {
2008   if (!II->isStr("objc_msgSendSuper"))
2009     return;
2010   ASTContext &Context = ThisSema.Context;
2011 
2012   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2013                       SourceLocation(), Sema::LookupTagName);
2014   ThisSema.LookupName(Result, S);
2015   if (Result.getResultKind() == LookupResult::Found)
2016     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2017       Context.setObjCSuperType(Context.getTagDeclType(TD));
2018 }
2019 
2020 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2021                                ASTContext::GetBuiltinTypeError Error) {
2022   switch (Error) {
2023   case ASTContext::GE_None:
2024     return "";
2025   case ASTContext::GE_Missing_type:
2026     return BuiltinInfo.getHeaderName(ID);
2027   case ASTContext::GE_Missing_stdio:
2028     return "stdio.h";
2029   case ASTContext::GE_Missing_setjmp:
2030     return "setjmp.h";
2031   case ASTContext::GE_Missing_ucontext:
2032     return "ucontext.h";
2033   }
2034   llvm_unreachable("unhandled error kind");
2035 }
2036 
2037 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2038 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2039 /// if we're creating this built-in in anticipation of redeclaring the
2040 /// built-in.
2041 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2042                                      Scope *S, bool ForRedeclaration,
2043                                      SourceLocation Loc) {
2044   LookupPredefedObjCSuperType(*this, S, II);
2045 
2046   ASTContext::GetBuiltinTypeError Error;
2047   QualType R = Context.GetBuiltinType(ID, Error);
2048   if (Error) {
2049     if (!ForRedeclaration)
2050       return nullptr;
2051 
2052     // If we have a builtin without an associated type we should not emit a
2053     // warning when we were not able to find a type for it.
2054     if (Error == ASTContext::GE_Missing_type)
2055       return nullptr;
2056 
2057     // If we could not find a type for setjmp it is because the jmp_buf type was
2058     // not defined prior to the setjmp declaration.
2059     if (Error == ASTContext::GE_Missing_setjmp) {
2060       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2061           << Context.BuiltinInfo.getName(ID);
2062       return nullptr;
2063     }
2064 
2065     // Generally, we emit a warning that the declaration requires the
2066     // appropriate header.
2067     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2068         << getHeaderName(Context.BuiltinInfo, ID, Error)
2069         << Context.BuiltinInfo.getName(ID);
2070     return nullptr;
2071   }
2072 
2073   if (!ForRedeclaration &&
2074       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2075        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2076     Diag(Loc, diag::ext_implicit_lib_function_decl)
2077         << Context.BuiltinInfo.getName(ID) << R;
2078     if (Context.BuiltinInfo.getHeaderName(ID) &&
2079         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2080       Diag(Loc, diag::note_include_header_or_declare)
2081           << Context.BuiltinInfo.getHeaderName(ID)
2082           << Context.BuiltinInfo.getName(ID);
2083   }
2084 
2085   if (R.isNull())
2086     return nullptr;
2087 
2088   DeclContext *Parent = Context.getTranslationUnitDecl();
2089   if (getLangOpts().CPlusPlus) {
2090     LinkageSpecDecl *CLinkageDecl =
2091         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2092                                 LinkageSpecDecl::lang_c, false);
2093     CLinkageDecl->setImplicit();
2094     Parent->addDecl(CLinkageDecl);
2095     Parent = CLinkageDecl;
2096   }
2097 
2098   FunctionDecl *New = FunctionDecl::Create(Context,
2099                                            Parent,
2100                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2101                                            SC_Extern,
2102                                            false,
2103                                            R->isFunctionProtoType());
2104   New->setImplicit();
2105 
2106   // Create Decl objects for each parameter, adding them to the
2107   // FunctionDecl.
2108   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2109     SmallVector<ParmVarDecl*, 16> Params;
2110     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2111       ParmVarDecl *parm =
2112           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2113                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2114                               SC_None, nullptr);
2115       parm->setScopeInfo(0, i);
2116       Params.push_back(parm);
2117     }
2118     New->setParams(Params);
2119   }
2120 
2121   AddKnownFunctionAttributes(New);
2122   RegisterLocallyScopedExternCDecl(New, S);
2123 
2124   // TUScope is the translation-unit scope to insert this function into.
2125   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2126   // relate Scopes to DeclContexts, and probably eliminate CurContext
2127   // entirely, but we're not there yet.
2128   DeclContext *SavedContext = CurContext;
2129   CurContext = Parent;
2130   PushOnScopeChains(New, TUScope);
2131   CurContext = SavedContext;
2132   return New;
2133 }
2134 
2135 /// Typedef declarations don't have linkage, but they still denote the same
2136 /// entity if their types are the same.
2137 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2138 /// isSameEntity.
2139 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2140                                                      TypedefNameDecl *Decl,
2141                                                      LookupResult &Previous) {
2142   // This is only interesting when modules are enabled.
2143   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2144     return;
2145 
2146   // Empty sets are uninteresting.
2147   if (Previous.empty())
2148     return;
2149 
2150   LookupResult::Filter Filter = Previous.makeFilter();
2151   while (Filter.hasNext()) {
2152     NamedDecl *Old = Filter.next();
2153 
2154     // Non-hidden declarations are never ignored.
2155     if (S.isVisible(Old))
2156       continue;
2157 
2158     // Declarations of the same entity are not ignored, even if they have
2159     // different linkages.
2160     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2161       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2162                                 Decl->getUnderlyingType()))
2163         continue;
2164 
2165       // If both declarations give a tag declaration a typedef name for linkage
2166       // purposes, then they declare the same entity.
2167       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2168           Decl->getAnonDeclWithTypedefName())
2169         continue;
2170     }
2171 
2172     Filter.erase();
2173   }
2174 
2175   Filter.done();
2176 }
2177 
2178 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2179   QualType OldType;
2180   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2181     OldType = OldTypedef->getUnderlyingType();
2182   else
2183     OldType = Context.getTypeDeclType(Old);
2184   QualType NewType = New->getUnderlyingType();
2185 
2186   if (NewType->isVariablyModifiedType()) {
2187     // Must not redefine a typedef with a variably-modified type.
2188     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2189     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2190       << Kind << NewType;
2191     if (Old->getLocation().isValid())
2192       notePreviousDefinition(Old, New->getLocation());
2193     New->setInvalidDecl();
2194     return true;
2195   }
2196 
2197   if (OldType != NewType &&
2198       !OldType->isDependentType() &&
2199       !NewType->isDependentType() &&
2200       !Context.hasSameType(OldType, NewType)) {
2201     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2202     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2203       << Kind << NewType << OldType;
2204     if (Old->getLocation().isValid())
2205       notePreviousDefinition(Old, New->getLocation());
2206     New->setInvalidDecl();
2207     return true;
2208   }
2209   return false;
2210 }
2211 
2212 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2213 /// same name and scope as a previous declaration 'Old'.  Figure out
2214 /// how to resolve this situation, merging decls or emitting
2215 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2216 ///
2217 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2218                                 LookupResult &OldDecls) {
2219   // If the new decl is known invalid already, don't bother doing any
2220   // merging checks.
2221   if (New->isInvalidDecl()) return;
2222 
2223   // Allow multiple definitions for ObjC built-in typedefs.
2224   // FIXME: Verify the underlying types are equivalent!
2225   if (getLangOpts().ObjC) {
2226     const IdentifierInfo *TypeID = New->getIdentifier();
2227     switch (TypeID->getLength()) {
2228     default: break;
2229     case 2:
2230       {
2231         if (!TypeID->isStr("id"))
2232           break;
2233         QualType T = New->getUnderlyingType();
2234         if (!T->isPointerType())
2235           break;
2236         if (!T->isVoidPointerType()) {
2237           QualType PT = T->castAs<PointerType>()->getPointeeType();
2238           if (!PT->isStructureType())
2239             break;
2240         }
2241         Context.setObjCIdRedefinitionType(T);
2242         // Install the built-in type for 'id', ignoring the current definition.
2243         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2244         return;
2245       }
2246     case 5:
2247       if (!TypeID->isStr("Class"))
2248         break;
2249       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2250       // Install the built-in type for 'Class', ignoring the current definition.
2251       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2252       return;
2253     case 3:
2254       if (!TypeID->isStr("SEL"))
2255         break;
2256       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2257       // Install the built-in type for 'SEL', ignoring the current definition.
2258       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2259       return;
2260     }
2261     // Fall through - the typedef name was not a builtin type.
2262   }
2263 
2264   // Verify the old decl was also a type.
2265   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2266   if (!Old) {
2267     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2268       << New->getDeclName();
2269 
2270     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2271     if (OldD->getLocation().isValid())
2272       notePreviousDefinition(OldD, New->getLocation());
2273 
2274     return New->setInvalidDecl();
2275   }
2276 
2277   // If the old declaration is invalid, just give up here.
2278   if (Old->isInvalidDecl())
2279     return New->setInvalidDecl();
2280 
2281   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2282     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2283     auto *NewTag = New->getAnonDeclWithTypedefName();
2284     NamedDecl *Hidden = nullptr;
2285     if (OldTag && NewTag &&
2286         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2287         !hasVisibleDefinition(OldTag, &Hidden)) {
2288       // There is a definition of this tag, but it is not visible. Use it
2289       // instead of our tag.
2290       New->setTypeForDecl(OldTD->getTypeForDecl());
2291       if (OldTD->isModed())
2292         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2293                                     OldTD->getUnderlyingType());
2294       else
2295         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2296 
2297       // Make the old tag definition visible.
2298       makeMergedDefinitionVisible(Hidden);
2299 
2300       // If this was an unscoped enumeration, yank all of its enumerators
2301       // out of the scope.
2302       if (isa<EnumDecl>(NewTag)) {
2303         Scope *EnumScope = getNonFieldDeclScope(S);
2304         for (auto *D : NewTag->decls()) {
2305           auto *ED = cast<EnumConstantDecl>(D);
2306           assert(EnumScope->isDeclScope(ED));
2307           EnumScope->RemoveDecl(ED);
2308           IdResolver.RemoveDecl(ED);
2309           ED->getLexicalDeclContext()->removeDecl(ED);
2310         }
2311       }
2312     }
2313   }
2314 
2315   // If the typedef types are not identical, reject them in all languages and
2316   // with any extensions enabled.
2317   if (isIncompatibleTypedef(Old, New))
2318     return;
2319 
2320   // The types match.  Link up the redeclaration chain and merge attributes if
2321   // the old declaration was a typedef.
2322   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2323     New->setPreviousDecl(Typedef);
2324     mergeDeclAttributes(New, Old);
2325   }
2326 
2327   if (getLangOpts().MicrosoftExt)
2328     return;
2329 
2330   if (getLangOpts().CPlusPlus) {
2331     // C++ [dcl.typedef]p2:
2332     //   In a given non-class scope, a typedef specifier can be used to
2333     //   redefine the name of any type declared in that scope to refer
2334     //   to the type to which it already refers.
2335     if (!isa<CXXRecordDecl>(CurContext))
2336       return;
2337 
2338     // C++0x [dcl.typedef]p4:
2339     //   In a given class scope, a typedef specifier can be used to redefine
2340     //   any class-name declared in that scope that is not also a typedef-name
2341     //   to refer to the type to which it already refers.
2342     //
2343     // This wording came in via DR424, which was a correction to the
2344     // wording in DR56, which accidentally banned code like:
2345     //
2346     //   struct S {
2347     //     typedef struct A { } A;
2348     //   };
2349     //
2350     // in the C++03 standard. We implement the C++0x semantics, which
2351     // allow the above but disallow
2352     //
2353     //   struct S {
2354     //     typedef int I;
2355     //     typedef int I;
2356     //   };
2357     //
2358     // since that was the intent of DR56.
2359     if (!isa<TypedefNameDecl>(Old))
2360       return;
2361 
2362     Diag(New->getLocation(), diag::err_redefinition)
2363       << New->getDeclName();
2364     notePreviousDefinition(Old, New->getLocation());
2365     return New->setInvalidDecl();
2366   }
2367 
2368   // Modules always permit redefinition of typedefs, as does C11.
2369   if (getLangOpts().Modules || getLangOpts().C11)
2370     return;
2371 
2372   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2373   // is normally mapped to an error, but can be controlled with
2374   // -Wtypedef-redefinition.  If either the original or the redefinition is
2375   // in a system header, don't emit this for compatibility with GCC.
2376   if (getDiagnostics().getSuppressSystemWarnings() &&
2377       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2378       (Old->isImplicit() ||
2379        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2380        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2381     return;
2382 
2383   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2384     << New->getDeclName();
2385   notePreviousDefinition(Old, New->getLocation());
2386 }
2387 
2388 /// DeclhasAttr - returns true if decl Declaration already has the target
2389 /// attribute.
2390 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2391   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2392   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2393   for (const auto *i : D->attrs())
2394     if (i->getKind() == A->getKind()) {
2395       if (Ann) {
2396         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2397           return true;
2398         continue;
2399       }
2400       // FIXME: Don't hardcode this check
2401       if (OA && isa<OwnershipAttr>(i))
2402         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2403       return true;
2404     }
2405 
2406   return false;
2407 }
2408 
2409 static bool isAttributeTargetADefinition(Decl *D) {
2410   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2411     return VD->isThisDeclarationADefinition();
2412   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2413     return TD->isCompleteDefinition() || TD->isBeingDefined();
2414   return true;
2415 }
2416 
2417 /// Merge alignment attributes from \p Old to \p New, taking into account the
2418 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2419 ///
2420 /// \return \c true if any attributes were added to \p New.
2421 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2422   // Look for alignas attributes on Old, and pick out whichever attribute
2423   // specifies the strictest alignment requirement.
2424   AlignedAttr *OldAlignasAttr = nullptr;
2425   AlignedAttr *OldStrictestAlignAttr = nullptr;
2426   unsigned OldAlign = 0;
2427   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2428     // FIXME: We have no way of representing inherited dependent alignments
2429     // in a case like:
2430     //   template<int A, int B> struct alignas(A) X;
2431     //   template<int A, int B> struct alignas(B) X {};
2432     // For now, we just ignore any alignas attributes which are not on the
2433     // definition in such a case.
2434     if (I->isAlignmentDependent())
2435       return false;
2436 
2437     if (I->isAlignas())
2438       OldAlignasAttr = I;
2439 
2440     unsigned Align = I->getAlignment(S.Context);
2441     if (Align > OldAlign) {
2442       OldAlign = Align;
2443       OldStrictestAlignAttr = I;
2444     }
2445   }
2446 
2447   // Look for alignas attributes on New.
2448   AlignedAttr *NewAlignasAttr = nullptr;
2449   unsigned NewAlign = 0;
2450   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2451     if (I->isAlignmentDependent())
2452       return false;
2453 
2454     if (I->isAlignas())
2455       NewAlignasAttr = I;
2456 
2457     unsigned Align = I->getAlignment(S.Context);
2458     if (Align > NewAlign)
2459       NewAlign = Align;
2460   }
2461 
2462   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2463     // Both declarations have 'alignas' attributes. We require them to match.
2464     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2465     // fall short. (If two declarations both have alignas, they must both match
2466     // every definition, and so must match each other if there is a definition.)
2467 
2468     // If either declaration only contains 'alignas(0)' specifiers, then it
2469     // specifies the natural alignment for the type.
2470     if (OldAlign == 0 || NewAlign == 0) {
2471       QualType Ty;
2472       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2473         Ty = VD->getType();
2474       else
2475         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2476 
2477       if (OldAlign == 0)
2478         OldAlign = S.Context.getTypeAlign(Ty);
2479       if (NewAlign == 0)
2480         NewAlign = S.Context.getTypeAlign(Ty);
2481     }
2482 
2483     if (OldAlign != NewAlign) {
2484       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2485         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2486         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2487       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2488     }
2489   }
2490 
2491   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2492     // C++11 [dcl.align]p6:
2493     //   if any declaration of an entity has an alignment-specifier,
2494     //   every defining declaration of that entity shall specify an
2495     //   equivalent alignment.
2496     // C11 6.7.5/7:
2497     //   If the definition of an object does not have an alignment
2498     //   specifier, any other declaration of that object shall also
2499     //   have no alignment specifier.
2500     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2501       << OldAlignasAttr;
2502     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2503       << OldAlignasAttr;
2504   }
2505 
2506   bool AnyAdded = false;
2507 
2508   // Ensure we have an attribute representing the strictest alignment.
2509   if (OldAlign > NewAlign) {
2510     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2511     Clone->setInherited(true);
2512     New->addAttr(Clone);
2513     AnyAdded = true;
2514   }
2515 
2516   // Ensure we have an alignas attribute if the old declaration had one.
2517   if (OldAlignasAttr && !NewAlignasAttr &&
2518       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2519     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2520     Clone->setInherited(true);
2521     New->addAttr(Clone);
2522     AnyAdded = true;
2523   }
2524 
2525   return AnyAdded;
2526 }
2527 
2528 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2529                                const InheritableAttr *Attr,
2530                                Sema::AvailabilityMergeKind AMK) {
2531   // This function copies an attribute Attr from a previous declaration to the
2532   // new declaration D if the new declaration doesn't itself have that attribute
2533   // yet or if that attribute allows duplicates.
2534   // If you're adding a new attribute that requires logic different from
2535   // "use explicit attribute on decl if present, else use attribute from
2536   // previous decl", for example if the attribute needs to be consistent
2537   // between redeclarations, you need to call a custom merge function here.
2538   InheritableAttr *NewAttr = nullptr;
2539   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2540     NewAttr = S.mergeAvailabilityAttr(
2541         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2542         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2543         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2544         AA->getPriority());
2545   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2546     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2547   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2548     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2549   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2550     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2551   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2552     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2553   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2554     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2555                                 FA->getFirstArg());
2556   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2557     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2558   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2559     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2560   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2561     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2562                                        IA->getInheritanceModel());
2563   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2564     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2565                                       &S.Context.Idents.get(AA->getSpelling()));
2566   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2567            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2568             isa<CUDAGlobalAttr>(Attr))) {
2569     // CUDA target attributes are part of function signature for
2570     // overloading purposes and must not be merged.
2571     return false;
2572   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2573     NewAttr = S.mergeMinSizeAttr(D, *MA);
2574   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2575     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2576   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2577     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2578   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2579     NewAttr = S.mergeCommonAttr(D, *CommonA);
2580   else if (isa<AlignedAttr>(Attr))
2581     // AlignedAttrs are handled separately, because we need to handle all
2582     // such attributes on a declaration at the same time.
2583     NewAttr = nullptr;
2584   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2585            (AMK == Sema::AMK_Override ||
2586             AMK == Sema::AMK_ProtocolImplementation))
2587     NewAttr = nullptr;
2588   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2589     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2590   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2591     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2592   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2593     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2594   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2595     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2596 
2597   if (NewAttr) {
2598     NewAttr->setInherited(true);
2599     D->addAttr(NewAttr);
2600     if (isa<MSInheritanceAttr>(NewAttr))
2601       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2602     return true;
2603   }
2604 
2605   return false;
2606 }
2607 
2608 static const NamedDecl *getDefinition(const Decl *D) {
2609   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2610     return TD->getDefinition();
2611   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2612     const VarDecl *Def = VD->getDefinition();
2613     if (Def)
2614       return Def;
2615     return VD->getActingDefinition();
2616   }
2617   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2618     return FD->getDefinition();
2619   return nullptr;
2620 }
2621 
2622 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2623   for (const auto *Attribute : D->attrs())
2624     if (Attribute->getKind() == Kind)
2625       return true;
2626   return false;
2627 }
2628 
2629 /// checkNewAttributesAfterDef - If we already have a definition, check that
2630 /// there are no new attributes in this declaration.
2631 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2632   if (!New->hasAttrs())
2633     return;
2634 
2635   const NamedDecl *Def = getDefinition(Old);
2636   if (!Def || Def == New)
2637     return;
2638 
2639   AttrVec &NewAttributes = New->getAttrs();
2640   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2641     const Attr *NewAttribute = NewAttributes[I];
2642 
2643     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2644       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2645         Sema::SkipBodyInfo SkipBody;
2646         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2647 
2648         // If we're skipping this definition, drop the "alias" attribute.
2649         if (SkipBody.ShouldSkip) {
2650           NewAttributes.erase(NewAttributes.begin() + I);
2651           --E;
2652           continue;
2653         }
2654       } else {
2655         VarDecl *VD = cast<VarDecl>(New);
2656         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2657                                 VarDecl::TentativeDefinition
2658                             ? diag::err_alias_after_tentative
2659                             : diag::err_redefinition;
2660         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2661         if (Diag == diag::err_redefinition)
2662           S.notePreviousDefinition(Def, VD->getLocation());
2663         else
2664           S.Diag(Def->getLocation(), diag::note_previous_definition);
2665         VD->setInvalidDecl();
2666       }
2667       ++I;
2668       continue;
2669     }
2670 
2671     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2672       // Tentative definitions are only interesting for the alias check above.
2673       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2674         ++I;
2675         continue;
2676       }
2677     }
2678 
2679     if (hasAttribute(Def, NewAttribute->getKind())) {
2680       ++I;
2681       continue; // regular attr merging will take care of validating this.
2682     }
2683 
2684     if (isa<C11NoReturnAttr>(NewAttribute)) {
2685       // C's _Noreturn is allowed to be added to a function after it is defined.
2686       ++I;
2687       continue;
2688     } else if (isa<UuidAttr>(NewAttribute)) {
2689       // msvc will allow a subsequent definition to add an uuid to a class
2690       ++I;
2691       continue;
2692     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2693       if (AA->isAlignas()) {
2694         // C++11 [dcl.align]p6:
2695         //   if any declaration of an entity has an alignment-specifier,
2696         //   every defining declaration of that entity shall specify an
2697         //   equivalent alignment.
2698         // C11 6.7.5/7:
2699         //   If the definition of an object does not have an alignment
2700         //   specifier, any other declaration of that object shall also
2701         //   have no alignment specifier.
2702         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2703           << AA;
2704         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2705           << AA;
2706         NewAttributes.erase(NewAttributes.begin() + I);
2707         --E;
2708         continue;
2709       }
2710     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2711                cast<VarDecl>(New)->isInline() &&
2712                !cast<VarDecl>(New)->isInlineSpecified()) {
2713       // Don't warn about applying selectany to implicitly inline variables.
2714       // Older compilers and language modes would require the use of selectany
2715       // to make such variables inline, and it would have no effect if we
2716       // honored it.
2717       ++I;
2718       continue;
2719     }
2720 
2721     S.Diag(NewAttribute->getLocation(),
2722            diag::warn_attribute_precede_definition);
2723     S.Diag(Def->getLocation(), diag::note_previous_definition);
2724     NewAttributes.erase(NewAttributes.begin() + I);
2725     --E;
2726   }
2727 }
2728 
2729 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2730                                      const ConstInitAttr *CIAttr,
2731                                      bool AttrBeforeInit) {
2732   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2733 
2734   // Figure out a good way to write this specifier on the old declaration.
2735   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2736   // enough of the attribute list spelling information to extract that without
2737   // heroics.
2738   std::string SuitableSpelling;
2739   if (S.getLangOpts().CPlusPlus2a)
2740     SuitableSpelling =
2741         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2742   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2743     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2744         InsertLoc,
2745         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2746          tok::coloncolon,
2747          S.PP.getIdentifierInfo("require_constant_initialization"),
2748          tok::r_square, tok::r_square});
2749   if (SuitableSpelling.empty())
2750     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2751         InsertLoc,
2752         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2753          S.PP.getIdentifierInfo("require_constant_initialization"),
2754          tok::r_paren, tok::r_paren});
2755   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2756     SuitableSpelling = "constinit";
2757   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2758     SuitableSpelling = "[[clang::require_constant_initialization]]";
2759   if (SuitableSpelling.empty())
2760     SuitableSpelling = "__attribute__((require_constant_initialization))";
2761   SuitableSpelling += " ";
2762 
2763   if (AttrBeforeInit) {
2764     // extern constinit int a;
2765     // int a = 0; // error (missing 'constinit'), accepted as extension
2766     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2767     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2768         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2769     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2770   } else {
2771     // int a = 0;
2772     // constinit extern int a; // error (missing 'constinit')
2773     S.Diag(CIAttr->getLocation(),
2774            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2775                                  : diag::warn_require_const_init_added_too_late)
2776         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2777     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2778         << CIAttr->isConstinit()
2779         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2780   }
2781 }
2782 
2783 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2784 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2785                                AvailabilityMergeKind AMK) {
2786   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2787     UsedAttr *NewAttr = OldAttr->clone(Context);
2788     NewAttr->setInherited(true);
2789     New->addAttr(NewAttr);
2790   }
2791 
2792   if (!Old->hasAttrs() && !New->hasAttrs())
2793     return;
2794 
2795   // [dcl.constinit]p1:
2796   //   If the [constinit] specifier is applied to any declaration of a
2797   //   variable, it shall be applied to the initializing declaration.
2798   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2799   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2800   if (bool(OldConstInit) != bool(NewConstInit)) {
2801     const auto *OldVD = cast<VarDecl>(Old);
2802     auto *NewVD = cast<VarDecl>(New);
2803 
2804     // Find the initializing declaration. Note that we might not have linked
2805     // the new declaration into the redeclaration chain yet.
2806     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2807     if (!InitDecl &&
2808         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2809       InitDecl = NewVD;
2810 
2811     if (InitDecl == NewVD) {
2812       // This is the initializing declaration. If it would inherit 'constinit',
2813       // that's ill-formed. (Note that we do not apply this to the attribute
2814       // form).
2815       if (OldConstInit && OldConstInit->isConstinit())
2816         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2817                                  /*AttrBeforeInit=*/true);
2818     } else if (NewConstInit) {
2819       // This is the first time we've been told that this declaration should
2820       // have a constant initializer. If we already saw the initializing
2821       // declaration, this is too late.
2822       if (InitDecl && InitDecl != NewVD) {
2823         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2824                                  /*AttrBeforeInit=*/false);
2825         NewVD->dropAttr<ConstInitAttr>();
2826       }
2827     }
2828   }
2829 
2830   // Attributes declared post-definition are currently ignored.
2831   checkNewAttributesAfterDef(*this, New, Old);
2832 
2833   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2834     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2835       if (!OldA->isEquivalent(NewA)) {
2836         // This redeclaration changes __asm__ label.
2837         Diag(New->getLocation(), diag::err_different_asm_label);
2838         Diag(OldA->getLocation(), diag::note_previous_declaration);
2839       }
2840     } else if (Old->isUsed()) {
2841       // This redeclaration adds an __asm__ label to a declaration that has
2842       // already been ODR-used.
2843       Diag(New->getLocation(), diag::err_late_asm_label_name)
2844         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2845     }
2846   }
2847 
2848   // Re-declaration cannot add abi_tag's.
2849   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2850     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2851       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2852         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2853                       NewTag) == OldAbiTagAttr->tags_end()) {
2854           Diag(NewAbiTagAttr->getLocation(),
2855                diag::err_new_abi_tag_on_redeclaration)
2856               << NewTag;
2857           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2858         }
2859       }
2860     } else {
2861       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2862       Diag(Old->getLocation(), diag::note_previous_declaration);
2863     }
2864   }
2865 
2866   // This redeclaration adds a section attribute.
2867   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2868     if (auto *VD = dyn_cast<VarDecl>(New)) {
2869       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2870         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2871         Diag(Old->getLocation(), diag::note_previous_declaration);
2872       }
2873     }
2874   }
2875 
2876   // Redeclaration adds code-seg attribute.
2877   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2878   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2879       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2880     Diag(New->getLocation(), diag::warn_mismatched_section)
2881          << 0 /*codeseg*/;
2882     Diag(Old->getLocation(), diag::note_previous_declaration);
2883   }
2884 
2885   if (!Old->hasAttrs())
2886     return;
2887 
2888   bool foundAny = New->hasAttrs();
2889 
2890   // Ensure that any moving of objects within the allocated map is done before
2891   // we process them.
2892   if (!foundAny) New->setAttrs(AttrVec());
2893 
2894   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2895     // Ignore deprecated/unavailable/availability attributes if requested.
2896     AvailabilityMergeKind LocalAMK = AMK_None;
2897     if (isa<DeprecatedAttr>(I) ||
2898         isa<UnavailableAttr>(I) ||
2899         isa<AvailabilityAttr>(I)) {
2900       switch (AMK) {
2901       case AMK_None:
2902         continue;
2903 
2904       case AMK_Redeclaration:
2905       case AMK_Override:
2906       case AMK_ProtocolImplementation:
2907         LocalAMK = AMK;
2908         break;
2909       }
2910     }
2911 
2912     // Already handled.
2913     if (isa<UsedAttr>(I))
2914       continue;
2915 
2916     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2917       foundAny = true;
2918   }
2919 
2920   if (mergeAlignedAttrs(*this, New, Old))
2921     foundAny = true;
2922 
2923   if (!foundAny) New->dropAttrs();
2924 }
2925 
2926 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2927 /// to the new one.
2928 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2929                                      const ParmVarDecl *oldDecl,
2930                                      Sema &S) {
2931   // C++11 [dcl.attr.depend]p2:
2932   //   The first declaration of a function shall specify the
2933   //   carries_dependency attribute for its declarator-id if any declaration
2934   //   of the function specifies the carries_dependency attribute.
2935   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2936   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2937     S.Diag(CDA->getLocation(),
2938            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2939     // Find the first declaration of the parameter.
2940     // FIXME: Should we build redeclaration chains for function parameters?
2941     const FunctionDecl *FirstFD =
2942       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2943     const ParmVarDecl *FirstVD =
2944       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2945     S.Diag(FirstVD->getLocation(),
2946            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2947   }
2948 
2949   if (!oldDecl->hasAttrs())
2950     return;
2951 
2952   bool foundAny = newDecl->hasAttrs();
2953 
2954   // Ensure that any moving of objects within the allocated map is
2955   // done before we process them.
2956   if (!foundAny) newDecl->setAttrs(AttrVec());
2957 
2958   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2959     if (!DeclHasAttr(newDecl, I)) {
2960       InheritableAttr *newAttr =
2961         cast<InheritableParamAttr>(I->clone(S.Context));
2962       newAttr->setInherited(true);
2963       newDecl->addAttr(newAttr);
2964       foundAny = true;
2965     }
2966   }
2967 
2968   if (!foundAny) newDecl->dropAttrs();
2969 }
2970 
2971 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2972                                 const ParmVarDecl *OldParam,
2973                                 Sema &S) {
2974   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2975     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2976       if (*Oldnullability != *Newnullability) {
2977         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2978           << DiagNullabilityKind(
2979                *Newnullability,
2980                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2981                 != 0))
2982           << DiagNullabilityKind(
2983                *Oldnullability,
2984                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2985                 != 0));
2986         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2987       }
2988     } else {
2989       QualType NewT = NewParam->getType();
2990       NewT = S.Context.getAttributedType(
2991                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2992                          NewT, NewT);
2993       NewParam->setType(NewT);
2994     }
2995   }
2996 }
2997 
2998 namespace {
2999 
3000 /// Used in MergeFunctionDecl to keep track of function parameters in
3001 /// C.
3002 struct GNUCompatibleParamWarning {
3003   ParmVarDecl *OldParm;
3004   ParmVarDecl *NewParm;
3005   QualType PromotedType;
3006 };
3007 
3008 } // end anonymous namespace
3009 
3010 // Determine whether the previous declaration was a definition, implicit
3011 // declaration, or a declaration.
3012 template <typename T>
3013 static std::pair<diag::kind, SourceLocation>
3014 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3015   diag::kind PrevDiag;
3016   SourceLocation OldLocation = Old->getLocation();
3017   if (Old->isThisDeclarationADefinition())
3018     PrevDiag = diag::note_previous_definition;
3019   else if (Old->isImplicit()) {
3020     PrevDiag = diag::note_previous_implicit_declaration;
3021     if (OldLocation.isInvalid())
3022       OldLocation = New->getLocation();
3023   } else
3024     PrevDiag = diag::note_previous_declaration;
3025   return std::make_pair(PrevDiag, OldLocation);
3026 }
3027 
3028 /// canRedefineFunction - checks if a function can be redefined. Currently,
3029 /// only extern inline functions can be redefined, and even then only in
3030 /// GNU89 mode.
3031 static bool canRedefineFunction(const FunctionDecl *FD,
3032                                 const LangOptions& LangOpts) {
3033   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3034           !LangOpts.CPlusPlus &&
3035           FD->isInlineSpecified() &&
3036           FD->getStorageClass() == SC_Extern);
3037 }
3038 
3039 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3040   const AttributedType *AT = T->getAs<AttributedType>();
3041   while (AT && !AT->isCallingConv())
3042     AT = AT->getModifiedType()->getAs<AttributedType>();
3043   return AT;
3044 }
3045 
3046 template <typename T>
3047 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3048   const DeclContext *DC = Old->getDeclContext();
3049   if (DC->isRecord())
3050     return false;
3051 
3052   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3053   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3054     return true;
3055   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3056     return true;
3057   return false;
3058 }
3059 
3060 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3061 static bool isExternC(VarTemplateDecl *) { return false; }
3062 
3063 /// Check whether a redeclaration of an entity introduced by a
3064 /// using-declaration is valid, given that we know it's not an overload
3065 /// (nor a hidden tag declaration).
3066 template<typename ExpectedDecl>
3067 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3068                                    ExpectedDecl *New) {
3069   // C++11 [basic.scope.declarative]p4:
3070   //   Given a set of declarations in a single declarative region, each of
3071   //   which specifies the same unqualified name,
3072   //   -- they shall all refer to the same entity, or all refer to functions
3073   //      and function templates; or
3074   //   -- exactly one declaration shall declare a class name or enumeration
3075   //      name that is not a typedef name and the other declarations shall all
3076   //      refer to the same variable or enumerator, or all refer to functions
3077   //      and function templates; in this case the class name or enumeration
3078   //      name is hidden (3.3.10).
3079 
3080   // C++11 [namespace.udecl]p14:
3081   //   If a function declaration in namespace scope or block scope has the
3082   //   same name and the same parameter-type-list as a function introduced
3083   //   by a using-declaration, and the declarations do not declare the same
3084   //   function, the program is ill-formed.
3085 
3086   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3087   if (Old &&
3088       !Old->getDeclContext()->getRedeclContext()->Equals(
3089           New->getDeclContext()->getRedeclContext()) &&
3090       !(isExternC(Old) && isExternC(New)))
3091     Old = nullptr;
3092 
3093   if (!Old) {
3094     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3095     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3096     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3097     return true;
3098   }
3099   return false;
3100 }
3101 
3102 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3103                                             const FunctionDecl *B) {
3104   assert(A->getNumParams() == B->getNumParams());
3105 
3106   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3107     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3108     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3109     if (AttrA == AttrB)
3110       return true;
3111     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3112            AttrA->isDynamic() == AttrB->isDynamic();
3113   };
3114 
3115   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3116 }
3117 
3118 /// If necessary, adjust the semantic declaration context for a qualified
3119 /// declaration to name the correct inline namespace within the qualifier.
3120 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3121                                                DeclaratorDecl *OldD) {
3122   // The only case where we need to update the DeclContext is when
3123   // redeclaration lookup for a qualified name finds a declaration
3124   // in an inline namespace within the context named by the qualifier:
3125   //
3126   //   inline namespace N { int f(); }
3127   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3128   //
3129   // For unqualified declarations, the semantic context *can* change
3130   // along the redeclaration chain (for local extern declarations,
3131   // extern "C" declarations, and friend declarations in particular).
3132   if (!NewD->getQualifier())
3133     return;
3134 
3135   // NewD is probably already in the right context.
3136   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3137   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3138   if (NamedDC->Equals(SemaDC))
3139     return;
3140 
3141   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3142           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3143          "unexpected context for redeclaration");
3144 
3145   auto *LexDC = NewD->getLexicalDeclContext();
3146   auto FixSemaDC = [=](NamedDecl *D) {
3147     if (!D)
3148       return;
3149     D->setDeclContext(SemaDC);
3150     D->setLexicalDeclContext(LexDC);
3151   };
3152 
3153   FixSemaDC(NewD);
3154   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3155     FixSemaDC(FD->getDescribedFunctionTemplate());
3156   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3157     FixSemaDC(VD->getDescribedVarTemplate());
3158 }
3159 
3160 /// MergeFunctionDecl - We just parsed a function 'New' from
3161 /// declarator D which has the same name and scope as a previous
3162 /// declaration 'Old'.  Figure out how to resolve this situation,
3163 /// merging decls or emitting diagnostics as appropriate.
3164 ///
3165 /// In C++, New and Old must be declarations that are not
3166 /// overloaded. Use IsOverload to determine whether New and Old are
3167 /// overloaded, and to select the Old declaration that New should be
3168 /// merged with.
3169 ///
3170 /// Returns true if there was an error, false otherwise.
3171 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3172                              Scope *S, bool MergeTypeWithOld) {
3173   // Verify the old decl was also a function.
3174   FunctionDecl *Old = OldD->getAsFunction();
3175   if (!Old) {
3176     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3177       if (New->getFriendObjectKind()) {
3178         Diag(New->getLocation(), diag::err_using_decl_friend);
3179         Diag(Shadow->getTargetDecl()->getLocation(),
3180              diag::note_using_decl_target);
3181         Diag(Shadow->getUsingDecl()->getLocation(),
3182              diag::note_using_decl) << 0;
3183         return true;
3184       }
3185 
3186       // Check whether the two declarations might declare the same function.
3187       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3188         return true;
3189       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3190     } else {
3191       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3192         << New->getDeclName();
3193       notePreviousDefinition(OldD, New->getLocation());
3194       return true;
3195     }
3196   }
3197 
3198   // If the old declaration is invalid, just give up here.
3199   if (Old->isInvalidDecl())
3200     return true;
3201 
3202   // Disallow redeclaration of some builtins.
3203   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3204     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3205     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3206         << Old << Old->getType();
3207     return true;
3208   }
3209 
3210   diag::kind PrevDiag;
3211   SourceLocation OldLocation;
3212   std::tie(PrevDiag, OldLocation) =
3213       getNoteDiagForInvalidRedeclaration(Old, New);
3214 
3215   // Don't complain about this if we're in GNU89 mode and the old function
3216   // is an extern inline function.
3217   // Don't complain about specializations. They are not supposed to have
3218   // storage classes.
3219   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3220       New->getStorageClass() == SC_Static &&
3221       Old->hasExternalFormalLinkage() &&
3222       !New->getTemplateSpecializationInfo() &&
3223       !canRedefineFunction(Old, getLangOpts())) {
3224     if (getLangOpts().MicrosoftExt) {
3225       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3226       Diag(OldLocation, PrevDiag);
3227     } else {
3228       Diag(New->getLocation(), diag::err_static_non_static) << New;
3229       Diag(OldLocation, PrevDiag);
3230       return true;
3231     }
3232   }
3233 
3234   if (New->hasAttr<InternalLinkageAttr>() &&
3235       !Old->hasAttr<InternalLinkageAttr>()) {
3236     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3237         << New->getDeclName();
3238     notePreviousDefinition(Old, New->getLocation());
3239     New->dropAttr<InternalLinkageAttr>();
3240   }
3241 
3242   if (CheckRedeclarationModuleOwnership(New, Old))
3243     return true;
3244 
3245   if (!getLangOpts().CPlusPlus) {
3246     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3247     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3248       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3249         << New << OldOvl;
3250 
3251       // Try our best to find a decl that actually has the overloadable
3252       // attribute for the note. In most cases (e.g. programs with only one
3253       // broken declaration/definition), this won't matter.
3254       //
3255       // FIXME: We could do this if we juggled some extra state in
3256       // OverloadableAttr, rather than just removing it.
3257       const Decl *DiagOld = Old;
3258       if (OldOvl) {
3259         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3260           const auto *A = D->getAttr<OverloadableAttr>();
3261           return A && !A->isImplicit();
3262         });
3263         // If we've implicitly added *all* of the overloadable attrs to this
3264         // chain, emitting a "previous redecl" note is pointless.
3265         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3266       }
3267 
3268       if (DiagOld)
3269         Diag(DiagOld->getLocation(),
3270              diag::note_attribute_overloadable_prev_overload)
3271           << OldOvl;
3272 
3273       if (OldOvl)
3274         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3275       else
3276         New->dropAttr<OverloadableAttr>();
3277     }
3278   }
3279 
3280   // If a function is first declared with a calling convention, but is later
3281   // declared or defined without one, all following decls assume the calling
3282   // convention of the first.
3283   //
3284   // It's OK if a function is first declared without a calling convention,
3285   // but is later declared or defined with the default calling convention.
3286   //
3287   // To test if either decl has an explicit calling convention, we look for
3288   // AttributedType sugar nodes on the type as written.  If they are missing or
3289   // were canonicalized away, we assume the calling convention was implicit.
3290   //
3291   // Note also that we DO NOT return at this point, because we still have
3292   // other tests to run.
3293   QualType OldQType = Context.getCanonicalType(Old->getType());
3294   QualType NewQType = Context.getCanonicalType(New->getType());
3295   const FunctionType *OldType = cast<FunctionType>(OldQType);
3296   const FunctionType *NewType = cast<FunctionType>(NewQType);
3297   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3298   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3299   bool RequiresAdjustment = false;
3300 
3301   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3302     FunctionDecl *First = Old->getFirstDecl();
3303     const FunctionType *FT =
3304         First->getType().getCanonicalType()->castAs<FunctionType>();
3305     FunctionType::ExtInfo FI = FT->getExtInfo();
3306     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3307     if (!NewCCExplicit) {
3308       // Inherit the CC from the previous declaration if it was specified
3309       // there but not here.
3310       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3311       RequiresAdjustment = true;
3312     } else if (New->getBuiltinID()) {
3313       // Calling Conventions on a Builtin aren't really useful and setting a
3314       // default calling convention and cdecl'ing some builtin redeclarations is
3315       // common, so warn and ignore the calling convention on the redeclaration.
3316       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3317           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3318           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3319       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3320       RequiresAdjustment = true;
3321     } else {
3322       // Calling conventions aren't compatible, so complain.
3323       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3324       Diag(New->getLocation(), diag::err_cconv_change)
3325         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3326         << !FirstCCExplicit
3327         << (!FirstCCExplicit ? "" :
3328             FunctionType::getNameForCallConv(FI.getCC()));
3329 
3330       // Put the note on the first decl, since it is the one that matters.
3331       Diag(First->getLocation(), diag::note_previous_declaration);
3332       return true;
3333     }
3334   }
3335 
3336   // FIXME: diagnose the other way around?
3337   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3338     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3339     RequiresAdjustment = true;
3340   }
3341 
3342   // Merge regparm attribute.
3343   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3344       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3345     if (NewTypeInfo.getHasRegParm()) {
3346       Diag(New->getLocation(), diag::err_regparm_mismatch)
3347         << NewType->getRegParmType()
3348         << OldType->getRegParmType();
3349       Diag(OldLocation, diag::note_previous_declaration);
3350       return true;
3351     }
3352 
3353     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3354     RequiresAdjustment = true;
3355   }
3356 
3357   // Merge ns_returns_retained attribute.
3358   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3359     if (NewTypeInfo.getProducesResult()) {
3360       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3361           << "'ns_returns_retained'";
3362       Diag(OldLocation, diag::note_previous_declaration);
3363       return true;
3364     }
3365 
3366     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3367     RequiresAdjustment = true;
3368   }
3369 
3370   if (OldTypeInfo.getNoCallerSavedRegs() !=
3371       NewTypeInfo.getNoCallerSavedRegs()) {
3372     if (NewTypeInfo.getNoCallerSavedRegs()) {
3373       AnyX86NoCallerSavedRegistersAttr *Attr =
3374         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3375       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3376       Diag(OldLocation, diag::note_previous_declaration);
3377       return true;
3378     }
3379 
3380     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3381     RequiresAdjustment = true;
3382   }
3383 
3384   if (RequiresAdjustment) {
3385     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3386     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3387     New->setType(QualType(AdjustedType, 0));
3388     NewQType = Context.getCanonicalType(New->getType());
3389   }
3390 
3391   // If this redeclaration makes the function inline, we may need to add it to
3392   // UndefinedButUsed.
3393   if (!Old->isInlined() && New->isInlined() &&
3394       !New->hasAttr<GNUInlineAttr>() &&
3395       !getLangOpts().GNUInline &&
3396       Old->isUsed(false) &&
3397       !Old->isDefined() && !New->isThisDeclarationADefinition())
3398     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3399                                            SourceLocation()));
3400 
3401   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3402   // about it.
3403   if (New->hasAttr<GNUInlineAttr>() &&
3404       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3405     UndefinedButUsed.erase(Old->getCanonicalDecl());
3406   }
3407 
3408   // If pass_object_size params don't match up perfectly, this isn't a valid
3409   // redeclaration.
3410   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3411       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3412     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3413         << New->getDeclName();
3414     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3415     return true;
3416   }
3417 
3418   if (getLangOpts().CPlusPlus) {
3419     // C++1z [over.load]p2
3420     //   Certain function declarations cannot be overloaded:
3421     //     -- Function declarations that differ only in the return type,
3422     //        the exception specification, or both cannot be overloaded.
3423 
3424     // Check the exception specifications match. This may recompute the type of
3425     // both Old and New if it resolved exception specifications, so grab the
3426     // types again after this. Because this updates the type, we do this before
3427     // any of the other checks below, which may update the "de facto" NewQType
3428     // but do not necessarily update the type of New.
3429     if (CheckEquivalentExceptionSpec(Old, New))
3430       return true;
3431     OldQType = Context.getCanonicalType(Old->getType());
3432     NewQType = Context.getCanonicalType(New->getType());
3433 
3434     // Go back to the type source info to compare the declared return types,
3435     // per C++1y [dcl.type.auto]p13:
3436     //   Redeclarations or specializations of a function or function template
3437     //   with a declared return type that uses a placeholder type shall also
3438     //   use that placeholder, not a deduced type.
3439     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3440     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3441     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3442         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3443                                        OldDeclaredReturnType)) {
3444       QualType ResQT;
3445       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3446           OldDeclaredReturnType->isObjCObjectPointerType())
3447         // FIXME: This does the wrong thing for a deduced return type.
3448         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3449       if (ResQT.isNull()) {
3450         if (New->isCXXClassMember() && New->isOutOfLine())
3451           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3452               << New << New->getReturnTypeSourceRange();
3453         else
3454           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3455               << New->getReturnTypeSourceRange();
3456         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3457                                     << Old->getReturnTypeSourceRange();
3458         return true;
3459       }
3460       else
3461         NewQType = ResQT;
3462     }
3463 
3464     QualType OldReturnType = OldType->getReturnType();
3465     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3466     if (OldReturnType != NewReturnType) {
3467       // If this function has a deduced return type and has already been
3468       // defined, copy the deduced value from the old declaration.
3469       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3470       if (OldAT && OldAT->isDeduced()) {
3471         New->setType(
3472             SubstAutoType(New->getType(),
3473                           OldAT->isDependentType() ? Context.DependentTy
3474                                                    : OldAT->getDeducedType()));
3475         NewQType = Context.getCanonicalType(
3476             SubstAutoType(NewQType,
3477                           OldAT->isDependentType() ? Context.DependentTy
3478                                                    : OldAT->getDeducedType()));
3479       }
3480     }
3481 
3482     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3483     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3484     if (OldMethod && NewMethod) {
3485       // Preserve triviality.
3486       NewMethod->setTrivial(OldMethod->isTrivial());
3487 
3488       // MSVC allows explicit template specialization at class scope:
3489       // 2 CXXMethodDecls referring to the same function will be injected.
3490       // We don't want a redeclaration error.
3491       bool IsClassScopeExplicitSpecialization =
3492                               OldMethod->isFunctionTemplateSpecialization() &&
3493                               NewMethod->isFunctionTemplateSpecialization();
3494       bool isFriend = NewMethod->getFriendObjectKind();
3495 
3496       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3497           !IsClassScopeExplicitSpecialization) {
3498         //    -- Member function declarations with the same name and the
3499         //       same parameter types cannot be overloaded if any of them
3500         //       is a static member function declaration.
3501         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3502           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3503           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3504           return true;
3505         }
3506 
3507         // C++ [class.mem]p1:
3508         //   [...] A member shall not be declared twice in the
3509         //   member-specification, except that a nested class or member
3510         //   class template can be declared and then later defined.
3511         if (!inTemplateInstantiation()) {
3512           unsigned NewDiag;
3513           if (isa<CXXConstructorDecl>(OldMethod))
3514             NewDiag = diag::err_constructor_redeclared;
3515           else if (isa<CXXDestructorDecl>(NewMethod))
3516             NewDiag = diag::err_destructor_redeclared;
3517           else if (isa<CXXConversionDecl>(NewMethod))
3518             NewDiag = diag::err_conv_function_redeclared;
3519           else
3520             NewDiag = diag::err_member_redeclared;
3521 
3522           Diag(New->getLocation(), NewDiag);
3523         } else {
3524           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3525             << New << New->getType();
3526         }
3527         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3528         return true;
3529 
3530       // Complain if this is an explicit declaration of a special
3531       // member that was initially declared implicitly.
3532       //
3533       // As an exception, it's okay to befriend such methods in order
3534       // to permit the implicit constructor/destructor/operator calls.
3535       } else if (OldMethod->isImplicit()) {
3536         if (isFriend) {
3537           NewMethod->setImplicit();
3538         } else {
3539           Diag(NewMethod->getLocation(),
3540                diag::err_definition_of_implicitly_declared_member)
3541             << New << getSpecialMember(OldMethod);
3542           return true;
3543         }
3544       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3545         Diag(NewMethod->getLocation(),
3546              diag::err_definition_of_explicitly_defaulted_member)
3547           << getSpecialMember(OldMethod);
3548         return true;
3549       }
3550     }
3551 
3552     // C++11 [dcl.attr.noreturn]p1:
3553     //   The first declaration of a function shall specify the noreturn
3554     //   attribute if any declaration of that function specifies the noreturn
3555     //   attribute.
3556     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3557     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3558       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3559       Diag(Old->getFirstDecl()->getLocation(),
3560            diag::note_noreturn_missing_first_decl);
3561     }
3562 
3563     // C++11 [dcl.attr.depend]p2:
3564     //   The first declaration of a function shall specify the
3565     //   carries_dependency attribute for its declarator-id if any declaration
3566     //   of the function specifies the carries_dependency attribute.
3567     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3568     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3569       Diag(CDA->getLocation(),
3570            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3571       Diag(Old->getFirstDecl()->getLocation(),
3572            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3573     }
3574 
3575     // (C++98 8.3.5p3):
3576     //   All declarations for a function shall agree exactly in both the
3577     //   return type and the parameter-type-list.
3578     // We also want to respect all the extended bits except noreturn.
3579 
3580     // noreturn should now match unless the old type info didn't have it.
3581     QualType OldQTypeForComparison = OldQType;
3582     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3583       auto *OldType = OldQType->castAs<FunctionProtoType>();
3584       const FunctionType *OldTypeForComparison
3585         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3586       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3587       assert(OldQTypeForComparison.isCanonical());
3588     }
3589 
3590     if (haveIncompatibleLanguageLinkages(Old, New)) {
3591       // As a special case, retain the language linkage from previous
3592       // declarations of a friend function as an extension.
3593       //
3594       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3595       // and is useful because there's otherwise no way to specify language
3596       // linkage within class scope.
3597       //
3598       // Check cautiously as the friend object kind isn't yet complete.
3599       if (New->getFriendObjectKind() != Decl::FOK_None) {
3600         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3601         Diag(OldLocation, PrevDiag);
3602       } else {
3603         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3604         Diag(OldLocation, PrevDiag);
3605         return true;
3606       }
3607     }
3608 
3609     // If the function types are compatible, merge the declarations. Ignore the
3610     // exception specifier because it was already checked above in
3611     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3612     // about incompatible types under -fms-compatibility.
3613     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3614                                                          NewQType))
3615       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3616 
3617     // If the types are imprecise (due to dependent constructs in friends or
3618     // local extern declarations), it's OK if they differ. We'll check again
3619     // during instantiation.
3620     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3621       return false;
3622 
3623     // Fall through for conflicting redeclarations and redefinitions.
3624   }
3625 
3626   // C: Function types need to be compatible, not identical. This handles
3627   // duplicate function decls like "void f(int); void f(enum X);" properly.
3628   if (!getLangOpts().CPlusPlus &&
3629       Context.typesAreCompatible(OldQType, NewQType)) {
3630     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3631     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3632     const FunctionProtoType *OldProto = nullptr;
3633     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3634         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3635       // The old declaration provided a function prototype, but the
3636       // new declaration does not. Merge in the prototype.
3637       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3638       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3639       NewQType =
3640           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3641                                   OldProto->getExtProtoInfo());
3642       New->setType(NewQType);
3643       New->setHasInheritedPrototype();
3644 
3645       // Synthesize parameters with the same types.
3646       SmallVector<ParmVarDecl*, 16> Params;
3647       for (const auto &ParamType : OldProto->param_types()) {
3648         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3649                                                  SourceLocation(), nullptr,
3650                                                  ParamType, /*TInfo=*/nullptr,
3651                                                  SC_None, nullptr);
3652         Param->setScopeInfo(0, Params.size());
3653         Param->setImplicit();
3654         Params.push_back(Param);
3655       }
3656 
3657       New->setParams(Params);
3658     }
3659 
3660     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3661   }
3662 
3663   // Check if the function types are compatible when pointer size address
3664   // spaces are ignored.
3665   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3666     return false;
3667 
3668   // GNU C permits a K&R definition to follow a prototype declaration
3669   // if the declared types of the parameters in the K&R definition
3670   // match the types in the prototype declaration, even when the
3671   // promoted types of the parameters from the K&R definition differ
3672   // from the types in the prototype. GCC then keeps the types from
3673   // the prototype.
3674   //
3675   // If a variadic prototype is followed by a non-variadic K&R definition,
3676   // the K&R definition becomes variadic.  This is sort of an edge case, but
3677   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3678   // C99 6.9.1p8.
3679   if (!getLangOpts().CPlusPlus &&
3680       Old->hasPrototype() && !New->hasPrototype() &&
3681       New->getType()->getAs<FunctionProtoType>() &&
3682       Old->getNumParams() == New->getNumParams()) {
3683     SmallVector<QualType, 16> ArgTypes;
3684     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3685     const FunctionProtoType *OldProto
3686       = Old->getType()->getAs<FunctionProtoType>();
3687     const FunctionProtoType *NewProto
3688       = New->getType()->getAs<FunctionProtoType>();
3689 
3690     // Determine whether this is the GNU C extension.
3691     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3692                                                NewProto->getReturnType());
3693     bool LooseCompatible = !MergedReturn.isNull();
3694     for (unsigned Idx = 0, End = Old->getNumParams();
3695          LooseCompatible && Idx != End; ++Idx) {
3696       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3697       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3698       if (Context.typesAreCompatible(OldParm->getType(),
3699                                      NewProto->getParamType(Idx))) {
3700         ArgTypes.push_back(NewParm->getType());
3701       } else if (Context.typesAreCompatible(OldParm->getType(),
3702                                             NewParm->getType(),
3703                                             /*CompareUnqualified=*/true)) {
3704         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3705                                            NewProto->getParamType(Idx) };
3706         Warnings.push_back(Warn);
3707         ArgTypes.push_back(NewParm->getType());
3708       } else
3709         LooseCompatible = false;
3710     }
3711 
3712     if (LooseCompatible) {
3713       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3714         Diag(Warnings[Warn].NewParm->getLocation(),
3715              diag::ext_param_promoted_not_compatible_with_prototype)
3716           << Warnings[Warn].PromotedType
3717           << Warnings[Warn].OldParm->getType();
3718         if (Warnings[Warn].OldParm->getLocation().isValid())
3719           Diag(Warnings[Warn].OldParm->getLocation(),
3720                diag::note_previous_declaration);
3721       }
3722 
3723       if (MergeTypeWithOld)
3724         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3725                                              OldProto->getExtProtoInfo()));
3726       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3727     }
3728 
3729     // Fall through to diagnose conflicting types.
3730   }
3731 
3732   // A function that has already been declared has been redeclared or
3733   // defined with a different type; show an appropriate diagnostic.
3734 
3735   // If the previous declaration was an implicitly-generated builtin
3736   // declaration, then at the very least we should use a specialized note.
3737   unsigned BuiltinID;
3738   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3739     // If it's actually a library-defined builtin function like 'malloc'
3740     // or 'printf', just warn about the incompatible redeclaration.
3741     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3742       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3743       Diag(OldLocation, diag::note_previous_builtin_declaration)
3744         << Old << Old->getType();
3745 
3746       // If this is a global redeclaration, just forget hereafter
3747       // about the "builtin-ness" of the function.
3748       //
3749       // Doing this for local extern declarations is problematic.  If
3750       // the builtin declaration remains visible, a second invalid
3751       // local declaration will produce a hard error; if it doesn't
3752       // remain visible, a single bogus local redeclaration (which is
3753       // actually only a warning) could break all the downstream code.
3754       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3755         New->getIdentifier()->revertBuiltin();
3756 
3757       return false;
3758     }
3759 
3760     PrevDiag = diag::note_previous_builtin_declaration;
3761   }
3762 
3763   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3764   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3765   return true;
3766 }
3767 
3768 /// Completes the merge of two function declarations that are
3769 /// known to be compatible.
3770 ///
3771 /// This routine handles the merging of attributes and other
3772 /// properties of function declarations from the old declaration to
3773 /// the new declaration, once we know that New is in fact a
3774 /// redeclaration of Old.
3775 ///
3776 /// \returns false
3777 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3778                                         Scope *S, bool MergeTypeWithOld) {
3779   // Merge the attributes
3780   mergeDeclAttributes(New, Old);
3781 
3782   // Merge "pure" flag.
3783   if (Old->isPure())
3784     New->setPure();
3785 
3786   // Merge "used" flag.
3787   if (Old->getMostRecentDecl()->isUsed(false))
3788     New->setIsUsed();
3789 
3790   // Merge attributes from the parameters.  These can mismatch with K&R
3791   // declarations.
3792   if (New->getNumParams() == Old->getNumParams())
3793       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3794         ParmVarDecl *NewParam = New->getParamDecl(i);
3795         ParmVarDecl *OldParam = Old->getParamDecl(i);
3796         mergeParamDeclAttributes(NewParam, OldParam, *this);
3797         mergeParamDeclTypes(NewParam, OldParam, *this);
3798       }
3799 
3800   if (getLangOpts().CPlusPlus)
3801     return MergeCXXFunctionDecl(New, Old, S);
3802 
3803   // Merge the function types so the we get the composite types for the return
3804   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3805   // was visible.
3806   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3807   if (!Merged.isNull() && MergeTypeWithOld)
3808     New->setType(Merged);
3809 
3810   return false;
3811 }
3812 
3813 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3814                                 ObjCMethodDecl *oldMethod) {
3815   // Merge the attributes, including deprecated/unavailable
3816   AvailabilityMergeKind MergeKind =
3817     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3818       ? AMK_ProtocolImplementation
3819       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3820                                                        : AMK_Override;
3821 
3822   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3823 
3824   // Merge attributes from the parameters.
3825   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3826                                        oe = oldMethod->param_end();
3827   for (ObjCMethodDecl::param_iterator
3828          ni = newMethod->param_begin(), ne = newMethod->param_end();
3829        ni != ne && oi != oe; ++ni, ++oi)
3830     mergeParamDeclAttributes(*ni, *oi, *this);
3831 
3832   CheckObjCMethodOverride(newMethod, oldMethod);
3833 }
3834 
3835 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3836   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3837 
3838   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3839          ? diag::err_redefinition_different_type
3840          : diag::err_redeclaration_different_type)
3841     << New->getDeclName() << New->getType() << Old->getType();
3842 
3843   diag::kind PrevDiag;
3844   SourceLocation OldLocation;
3845   std::tie(PrevDiag, OldLocation)
3846     = getNoteDiagForInvalidRedeclaration(Old, New);
3847   S.Diag(OldLocation, PrevDiag);
3848   New->setInvalidDecl();
3849 }
3850 
3851 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3852 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3853 /// emitting diagnostics as appropriate.
3854 ///
3855 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3856 /// to here in AddInitializerToDecl. We can't check them before the initializer
3857 /// is attached.
3858 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3859                              bool MergeTypeWithOld) {
3860   if (New->isInvalidDecl() || Old->isInvalidDecl())
3861     return;
3862 
3863   QualType MergedT;
3864   if (getLangOpts().CPlusPlus) {
3865     if (New->getType()->isUndeducedType()) {
3866       // We don't know what the new type is until the initializer is attached.
3867       return;
3868     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3869       // These could still be something that needs exception specs checked.
3870       return MergeVarDeclExceptionSpecs(New, Old);
3871     }
3872     // C++ [basic.link]p10:
3873     //   [...] the types specified by all declarations referring to a given
3874     //   object or function shall be identical, except that declarations for an
3875     //   array object can specify array types that differ by the presence or
3876     //   absence of a major array bound (8.3.4).
3877     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3878       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3879       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3880 
3881       // We are merging a variable declaration New into Old. If it has an array
3882       // bound, and that bound differs from Old's bound, we should diagnose the
3883       // mismatch.
3884       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3885         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3886              PrevVD = PrevVD->getPreviousDecl()) {
3887           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3888           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3889             continue;
3890 
3891           if (!Context.hasSameType(NewArray, PrevVDTy))
3892             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3893         }
3894       }
3895 
3896       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3897         if (Context.hasSameType(OldArray->getElementType(),
3898                                 NewArray->getElementType()))
3899           MergedT = New->getType();
3900       }
3901       // FIXME: Check visibility. New is hidden but has a complete type. If New
3902       // has no array bound, it should not inherit one from Old, if Old is not
3903       // visible.
3904       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3905         if (Context.hasSameType(OldArray->getElementType(),
3906                                 NewArray->getElementType()))
3907           MergedT = Old->getType();
3908       }
3909     }
3910     else if (New->getType()->isObjCObjectPointerType() &&
3911                Old->getType()->isObjCObjectPointerType()) {
3912       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3913                                               Old->getType());
3914     }
3915   } else {
3916     // C 6.2.7p2:
3917     //   All declarations that refer to the same object or function shall have
3918     //   compatible type.
3919     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3920   }
3921   if (MergedT.isNull()) {
3922     // It's OK if we couldn't merge types if either type is dependent, for a
3923     // block-scope variable. In other cases (static data members of class
3924     // templates, variable templates, ...), we require the types to be
3925     // equivalent.
3926     // FIXME: The C++ standard doesn't say anything about this.
3927     if ((New->getType()->isDependentType() ||
3928          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3929       // If the old type was dependent, we can't merge with it, so the new type
3930       // becomes dependent for now. We'll reproduce the original type when we
3931       // instantiate the TypeSourceInfo for the variable.
3932       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3933         New->setType(Context.DependentTy);
3934       return;
3935     }
3936     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3937   }
3938 
3939   // Don't actually update the type on the new declaration if the old
3940   // declaration was an extern declaration in a different scope.
3941   if (MergeTypeWithOld)
3942     New->setType(MergedT);
3943 }
3944 
3945 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3946                                   LookupResult &Previous) {
3947   // C11 6.2.7p4:
3948   //   For an identifier with internal or external linkage declared
3949   //   in a scope in which a prior declaration of that identifier is
3950   //   visible, if the prior declaration specifies internal or
3951   //   external linkage, the type of the identifier at the later
3952   //   declaration becomes the composite type.
3953   //
3954   // If the variable isn't visible, we do not merge with its type.
3955   if (Previous.isShadowed())
3956     return false;
3957 
3958   if (S.getLangOpts().CPlusPlus) {
3959     // C++11 [dcl.array]p3:
3960     //   If there is a preceding declaration of the entity in the same
3961     //   scope in which the bound was specified, an omitted array bound
3962     //   is taken to be the same as in that earlier declaration.
3963     return NewVD->isPreviousDeclInSameBlockScope() ||
3964            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3965             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3966   } else {
3967     // If the old declaration was function-local, don't merge with its
3968     // type unless we're in the same function.
3969     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3970            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3971   }
3972 }
3973 
3974 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3975 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3976 /// situation, merging decls or emitting diagnostics as appropriate.
3977 ///
3978 /// Tentative definition rules (C99 6.9.2p2) are checked by
3979 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3980 /// definitions here, since the initializer hasn't been attached.
3981 ///
3982 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3983   // If the new decl is already invalid, don't do any other checking.
3984   if (New->isInvalidDecl())
3985     return;
3986 
3987   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3988     return;
3989 
3990   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3991 
3992   // Verify the old decl was also a variable or variable template.
3993   VarDecl *Old = nullptr;
3994   VarTemplateDecl *OldTemplate = nullptr;
3995   if (Previous.isSingleResult()) {
3996     if (NewTemplate) {
3997       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3998       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3999 
4000       if (auto *Shadow =
4001               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4002         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4003           return New->setInvalidDecl();
4004     } else {
4005       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4006 
4007       if (auto *Shadow =
4008               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4009         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4010           return New->setInvalidDecl();
4011     }
4012   }
4013   if (!Old) {
4014     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4015         << New->getDeclName();
4016     notePreviousDefinition(Previous.getRepresentativeDecl(),
4017                            New->getLocation());
4018     return New->setInvalidDecl();
4019   }
4020 
4021   // Ensure the template parameters are compatible.
4022   if (NewTemplate &&
4023       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4024                                       OldTemplate->getTemplateParameters(),
4025                                       /*Complain=*/true, TPL_TemplateMatch))
4026     return New->setInvalidDecl();
4027 
4028   // C++ [class.mem]p1:
4029   //   A member shall not be declared twice in the member-specification [...]
4030   //
4031   // Here, we need only consider static data members.
4032   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4033     Diag(New->getLocation(), diag::err_duplicate_member)
4034       << New->getIdentifier();
4035     Diag(Old->getLocation(), diag::note_previous_declaration);
4036     New->setInvalidDecl();
4037   }
4038 
4039   mergeDeclAttributes(New, Old);
4040   // Warn if an already-declared variable is made a weak_import in a subsequent
4041   // declaration
4042   if (New->hasAttr<WeakImportAttr>() &&
4043       Old->getStorageClass() == SC_None &&
4044       !Old->hasAttr<WeakImportAttr>()) {
4045     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4046     notePreviousDefinition(Old, New->getLocation());
4047     // Remove weak_import attribute on new declaration.
4048     New->dropAttr<WeakImportAttr>();
4049   }
4050 
4051   if (New->hasAttr<InternalLinkageAttr>() &&
4052       !Old->hasAttr<InternalLinkageAttr>()) {
4053     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4054         << New->getDeclName();
4055     notePreviousDefinition(Old, New->getLocation());
4056     New->dropAttr<InternalLinkageAttr>();
4057   }
4058 
4059   // Merge the types.
4060   VarDecl *MostRecent = Old->getMostRecentDecl();
4061   if (MostRecent != Old) {
4062     MergeVarDeclTypes(New, MostRecent,
4063                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4064     if (New->isInvalidDecl())
4065       return;
4066   }
4067 
4068   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4069   if (New->isInvalidDecl())
4070     return;
4071 
4072   diag::kind PrevDiag;
4073   SourceLocation OldLocation;
4074   std::tie(PrevDiag, OldLocation) =
4075       getNoteDiagForInvalidRedeclaration(Old, New);
4076 
4077   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4078   if (New->getStorageClass() == SC_Static &&
4079       !New->isStaticDataMember() &&
4080       Old->hasExternalFormalLinkage()) {
4081     if (getLangOpts().MicrosoftExt) {
4082       Diag(New->getLocation(), diag::ext_static_non_static)
4083           << New->getDeclName();
4084       Diag(OldLocation, PrevDiag);
4085     } else {
4086       Diag(New->getLocation(), diag::err_static_non_static)
4087           << New->getDeclName();
4088       Diag(OldLocation, PrevDiag);
4089       return New->setInvalidDecl();
4090     }
4091   }
4092   // C99 6.2.2p4:
4093   //   For an identifier declared with the storage-class specifier
4094   //   extern in a scope in which a prior declaration of that
4095   //   identifier is visible,23) if the prior declaration specifies
4096   //   internal or external linkage, the linkage of the identifier at
4097   //   the later declaration is the same as the linkage specified at
4098   //   the prior declaration. If no prior declaration is visible, or
4099   //   if the prior declaration specifies no linkage, then the
4100   //   identifier has external linkage.
4101   if (New->hasExternalStorage() && Old->hasLinkage())
4102     /* Okay */;
4103   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4104            !New->isStaticDataMember() &&
4105            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4106     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4107     Diag(OldLocation, PrevDiag);
4108     return New->setInvalidDecl();
4109   }
4110 
4111   // Check if extern is followed by non-extern and vice-versa.
4112   if (New->hasExternalStorage() &&
4113       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4114     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4115     Diag(OldLocation, PrevDiag);
4116     return New->setInvalidDecl();
4117   }
4118   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4119       !New->hasExternalStorage()) {
4120     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4121     Diag(OldLocation, PrevDiag);
4122     return New->setInvalidDecl();
4123   }
4124 
4125   if (CheckRedeclarationModuleOwnership(New, Old))
4126     return;
4127 
4128   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4129 
4130   // FIXME: The test for external storage here seems wrong? We still
4131   // need to check for mismatches.
4132   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4133       // Don't complain about out-of-line definitions of static members.
4134       !(Old->getLexicalDeclContext()->isRecord() &&
4135         !New->getLexicalDeclContext()->isRecord())) {
4136     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4137     Diag(OldLocation, PrevDiag);
4138     return New->setInvalidDecl();
4139   }
4140 
4141   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4142     if (VarDecl *Def = Old->getDefinition()) {
4143       // C++1z [dcl.fcn.spec]p4:
4144       //   If the definition of a variable appears in a translation unit before
4145       //   its first declaration as inline, the program is ill-formed.
4146       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4147       Diag(Def->getLocation(), diag::note_previous_definition);
4148     }
4149   }
4150 
4151   // If this redeclaration makes the variable inline, we may need to add it to
4152   // UndefinedButUsed.
4153   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4154       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4155     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4156                                            SourceLocation()));
4157 
4158   if (New->getTLSKind() != Old->getTLSKind()) {
4159     if (!Old->getTLSKind()) {
4160       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4161       Diag(OldLocation, PrevDiag);
4162     } else if (!New->getTLSKind()) {
4163       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4164       Diag(OldLocation, PrevDiag);
4165     } else {
4166       // Do not allow redeclaration to change the variable between requiring
4167       // static and dynamic initialization.
4168       // FIXME: GCC allows this, but uses the TLS keyword on the first
4169       // declaration to determine the kind. Do we need to be compatible here?
4170       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4171         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4172       Diag(OldLocation, PrevDiag);
4173     }
4174   }
4175 
4176   // C++ doesn't have tentative definitions, so go right ahead and check here.
4177   if (getLangOpts().CPlusPlus &&
4178       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4179     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4180         Old->getCanonicalDecl()->isConstexpr()) {
4181       // This definition won't be a definition any more once it's been merged.
4182       Diag(New->getLocation(),
4183            diag::warn_deprecated_redundant_constexpr_static_def);
4184     } else if (VarDecl *Def = Old->getDefinition()) {
4185       if (checkVarDeclRedefinition(Def, New))
4186         return;
4187     }
4188   }
4189 
4190   if (haveIncompatibleLanguageLinkages(Old, New)) {
4191     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4192     Diag(OldLocation, PrevDiag);
4193     New->setInvalidDecl();
4194     return;
4195   }
4196 
4197   // Merge "used" flag.
4198   if (Old->getMostRecentDecl()->isUsed(false))
4199     New->setIsUsed();
4200 
4201   // Keep a chain of previous declarations.
4202   New->setPreviousDecl(Old);
4203   if (NewTemplate)
4204     NewTemplate->setPreviousDecl(OldTemplate);
4205   adjustDeclContextForDeclaratorDecl(New, Old);
4206 
4207   // Inherit access appropriately.
4208   New->setAccess(Old->getAccess());
4209   if (NewTemplate)
4210     NewTemplate->setAccess(New->getAccess());
4211 
4212   if (Old->isInline())
4213     New->setImplicitlyInline();
4214 }
4215 
4216 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4217   SourceManager &SrcMgr = getSourceManager();
4218   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4219   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4220   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4221   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4222   auto &HSI = PP.getHeaderSearchInfo();
4223   StringRef HdrFilename =
4224       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4225 
4226   auto noteFromModuleOrInclude = [&](Module *Mod,
4227                                      SourceLocation IncLoc) -> bool {
4228     // Redefinition errors with modules are common with non modular mapped
4229     // headers, example: a non-modular header H in module A that also gets
4230     // included directly in a TU. Pointing twice to the same header/definition
4231     // is confusing, try to get better diagnostics when modules is on.
4232     if (IncLoc.isValid()) {
4233       if (Mod) {
4234         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4235             << HdrFilename.str() << Mod->getFullModuleName();
4236         if (!Mod->DefinitionLoc.isInvalid())
4237           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4238               << Mod->getFullModuleName();
4239       } else {
4240         Diag(IncLoc, diag::note_redefinition_include_same_file)
4241             << HdrFilename.str();
4242       }
4243       return true;
4244     }
4245 
4246     return false;
4247   };
4248 
4249   // Is it the same file and same offset? Provide more information on why
4250   // this leads to a redefinition error.
4251   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4252     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4253     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4254     bool EmittedDiag =
4255         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4256     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4257 
4258     // If the header has no guards, emit a note suggesting one.
4259     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4260       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4261 
4262     if (EmittedDiag)
4263       return;
4264   }
4265 
4266   // Redefinition coming from different files or couldn't do better above.
4267   if (Old->getLocation().isValid())
4268     Diag(Old->getLocation(), diag::note_previous_definition);
4269 }
4270 
4271 /// We've just determined that \p Old and \p New both appear to be definitions
4272 /// of the same variable. Either diagnose or fix the problem.
4273 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4274   if (!hasVisibleDefinition(Old) &&
4275       (New->getFormalLinkage() == InternalLinkage ||
4276        New->isInline() ||
4277        New->getDescribedVarTemplate() ||
4278        New->getNumTemplateParameterLists() ||
4279        New->getDeclContext()->isDependentContext())) {
4280     // The previous definition is hidden, and multiple definitions are
4281     // permitted (in separate TUs). Demote this to a declaration.
4282     New->demoteThisDefinitionToDeclaration();
4283 
4284     // Make the canonical definition visible.
4285     if (auto *OldTD = Old->getDescribedVarTemplate())
4286       makeMergedDefinitionVisible(OldTD);
4287     makeMergedDefinitionVisible(Old);
4288     return false;
4289   } else {
4290     Diag(New->getLocation(), diag::err_redefinition) << New;
4291     notePreviousDefinition(Old, New->getLocation());
4292     New->setInvalidDecl();
4293     return true;
4294   }
4295 }
4296 
4297 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4298 /// no declarator (e.g. "struct foo;") is parsed.
4299 Decl *
4300 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4301                                  RecordDecl *&AnonRecord) {
4302   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4303                                     AnonRecord);
4304 }
4305 
4306 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4307 // disambiguate entities defined in different scopes.
4308 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4309 // compatibility.
4310 // We will pick our mangling number depending on which version of MSVC is being
4311 // targeted.
4312 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4313   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4314              ? S->getMSCurManglingNumber()
4315              : S->getMSLastManglingNumber();
4316 }
4317 
4318 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4319   if (!Context.getLangOpts().CPlusPlus)
4320     return;
4321 
4322   if (isa<CXXRecordDecl>(Tag->getParent())) {
4323     // If this tag is the direct child of a class, number it if
4324     // it is anonymous.
4325     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4326       return;
4327     MangleNumberingContext &MCtx =
4328         Context.getManglingNumberContext(Tag->getParent());
4329     Context.setManglingNumber(
4330         Tag, MCtx.getManglingNumber(
4331                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4332     return;
4333   }
4334 
4335   // If this tag isn't a direct child of a class, number it if it is local.
4336   MangleNumberingContext *MCtx;
4337   Decl *ManglingContextDecl;
4338   std::tie(MCtx, ManglingContextDecl) =
4339       getCurrentMangleNumberContext(Tag->getDeclContext());
4340   if (MCtx) {
4341     Context.setManglingNumber(
4342         Tag, MCtx->getManglingNumber(
4343                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4344   }
4345 }
4346 
4347 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4348                                         TypedefNameDecl *NewTD) {
4349   if (TagFromDeclSpec->isInvalidDecl())
4350     return;
4351 
4352   // Do nothing if the tag already has a name for linkage purposes.
4353   if (TagFromDeclSpec->hasNameForLinkage())
4354     return;
4355 
4356   // A well-formed anonymous tag must always be a TUK_Definition.
4357   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4358 
4359   // The type must match the tag exactly;  no qualifiers allowed.
4360   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4361                            Context.getTagDeclType(TagFromDeclSpec))) {
4362     if (getLangOpts().CPlusPlus)
4363       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4364     return;
4365   }
4366 
4367   // If we've already computed linkage for the anonymous tag, then
4368   // adding a typedef name for the anonymous decl can change that
4369   // linkage, which might be a serious problem.  Diagnose this as
4370   // unsupported and ignore the typedef name.  TODO: we should
4371   // pursue this as a language defect and establish a formal rule
4372   // for how to handle it.
4373   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4374     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4375 
4376     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4377     tagLoc = getLocForEndOfToken(tagLoc);
4378 
4379     llvm::SmallString<40> textToInsert;
4380     textToInsert += ' ';
4381     textToInsert += NewTD->getIdentifier()->getName();
4382     Diag(tagLoc, diag::note_typedef_changes_linkage)
4383         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4384     return;
4385   }
4386 
4387   // Otherwise, set this is the anon-decl typedef for the tag.
4388   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4389 }
4390 
4391 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4392   switch (T) {
4393   case DeclSpec::TST_class:
4394     return 0;
4395   case DeclSpec::TST_struct:
4396     return 1;
4397   case DeclSpec::TST_interface:
4398     return 2;
4399   case DeclSpec::TST_union:
4400     return 3;
4401   case DeclSpec::TST_enum:
4402     return 4;
4403   default:
4404     llvm_unreachable("unexpected type specifier");
4405   }
4406 }
4407 
4408 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4409 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4410 /// parameters to cope with template friend declarations.
4411 Decl *
4412 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4413                                  MultiTemplateParamsArg TemplateParams,
4414                                  bool IsExplicitInstantiation,
4415                                  RecordDecl *&AnonRecord) {
4416   Decl *TagD = nullptr;
4417   TagDecl *Tag = nullptr;
4418   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4419       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4420       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4421       DS.getTypeSpecType() == DeclSpec::TST_union ||
4422       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4423     TagD = DS.getRepAsDecl();
4424 
4425     if (!TagD) // We probably had an error
4426       return nullptr;
4427 
4428     // Note that the above type specs guarantee that the
4429     // type rep is a Decl, whereas in many of the others
4430     // it's a Type.
4431     if (isa<TagDecl>(TagD))
4432       Tag = cast<TagDecl>(TagD);
4433     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4434       Tag = CTD->getTemplatedDecl();
4435   }
4436 
4437   if (Tag) {
4438     handleTagNumbering(Tag, S);
4439     Tag->setFreeStanding();
4440     if (Tag->isInvalidDecl())
4441       return Tag;
4442   }
4443 
4444   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4445     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4446     // or incomplete types shall not be restrict-qualified."
4447     if (TypeQuals & DeclSpec::TQ_restrict)
4448       Diag(DS.getRestrictSpecLoc(),
4449            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4450            << DS.getSourceRange();
4451   }
4452 
4453   if (DS.isInlineSpecified())
4454     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4455         << getLangOpts().CPlusPlus17;
4456 
4457   if (DS.hasConstexprSpecifier()) {
4458     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4459     // and definitions of functions and variables.
4460     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4461     // the declaration of a function or function template
4462     if (Tag)
4463       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4464           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4465           << DS.getConstexprSpecifier();
4466     else
4467       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4468           << DS.getConstexprSpecifier();
4469     // Don't emit warnings after this error.
4470     return TagD;
4471   }
4472 
4473   DiagnoseFunctionSpecifiers(DS);
4474 
4475   if (DS.isFriendSpecified()) {
4476     // If we're dealing with a decl but not a TagDecl, assume that
4477     // whatever routines created it handled the friendship aspect.
4478     if (TagD && !Tag)
4479       return nullptr;
4480     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4481   }
4482 
4483   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4484   bool IsExplicitSpecialization =
4485     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4486   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4487       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4488       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4489     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4490     // nested-name-specifier unless it is an explicit instantiation
4491     // or an explicit specialization.
4492     //
4493     // FIXME: We allow class template partial specializations here too, per the
4494     // obvious intent of DR1819.
4495     //
4496     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4497     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4498         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4499     return nullptr;
4500   }
4501 
4502   // Track whether this decl-specifier declares anything.
4503   bool DeclaresAnything = true;
4504 
4505   // Handle anonymous struct definitions.
4506   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4507     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4508         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4509       if (getLangOpts().CPlusPlus ||
4510           Record->getDeclContext()->isRecord()) {
4511         // If CurContext is a DeclContext that can contain statements,
4512         // RecursiveASTVisitor won't visit the decls that
4513         // BuildAnonymousStructOrUnion() will put into CurContext.
4514         // Also store them here so that they can be part of the
4515         // DeclStmt that gets created in this case.
4516         // FIXME: Also return the IndirectFieldDecls created by
4517         // BuildAnonymousStructOr union, for the same reason?
4518         if (CurContext->isFunctionOrMethod())
4519           AnonRecord = Record;
4520         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4521                                            Context.getPrintingPolicy());
4522       }
4523 
4524       DeclaresAnything = false;
4525     }
4526   }
4527 
4528   // C11 6.7.2.1p2:
4529   //   A struct-declaration that does not declare an anonymous structure or
4530   //   anonymous union shall contain a struct-declarator-list.
4531   //
4532   // This rule also existed in C89 and C99; the grammar for struct-declaration
4533   // did not permit a struct-declaration without a struct-declarator-list.
4534   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4535       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4536     // Check for Microsoft C extension: anonymous struct/union member.
4537     // Handle 2 kinds of anonymous struct/union:
4538     //   struct STRUCT;
4539     //   union UNION;
4540     // and
4541     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4542     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4543     if ((Tag && Tag->getDeclName()) ||
4544         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4545       RecordDecl *Record = nullptr;
4546       if (Tag)
4547         Record = dyn_cast<RecordDecl>(Tag);
4548       else if (const RecordType *RT =
4549                    DS.getRepAsType().get()->getAsStructureType())
4550         Record = RT->getDecl();
4551       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4552         Record = UT->getDecl();
4553 
4554       if (Record && getLangOpts().MicrosoftExt) {
4555         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4556             << Record->isUnion() << DS.getSourceRange();
4557         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4558       }
4559 
4560       DeclaresAnything = false;
4561     }
4562   }
4563 
4564   // Skip all the checks below if we have a type error.
4565   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4566       (TagD && TagD->isInvalidDecl()))
4567     return TagD;
4568 
4569   if (getLangOpts().CPlusPlus &&
4570       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4571     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4572       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4573           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4574         DeclaresAnything = false;
4575 
4576   if (!DS.isMissingDeclaratorOk()) {
4577     // Customize diagnostic for a typedef missing a name.
4578     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4579       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4580           << DS.getSourceRange();
4581     else
4582       DeclaresAnything = false;
4583   }
4584 
4585   if (DS.isModulePrivateSpecified() &&
4586       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4587     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4588       << Tag->getTagKind()
4589       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4590 
4591   ActOnDocumentableDecl(TagD);
4592 
4593   // C 6.7/2:
4594   //   A declaration [...] shall declare at least a declarator [...], a tag,
4595   //   or the members of an enumeration.
4596   // C++ [dcl.dcl]p3:
4597   //   [If there are no declarators], and except for the declaration of an
4598   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4599   //   names into the program, or shall redeclare a name introduced by a
4600   //   previous declaration.
4601   if (!DeclaresAnything) {
4602     // In C, we allow this as a (popular) extension / bug. Don't bother
4603     // producing further diagnostics for redundant qualifiers after this.
4604     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4605     return TagD;
4606   }
4607 
4608   // C++ [dcl.stc]p1:
4609   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4610   //   init-declarator-list of the declaration shall not be empty.
4611   // C++ [dcl.fct.spec]p1:
4612   //   If a cv-qualifier appears in a decl-specifier-seq, the
4613   //   init-declarator-list of the declaration shall not be empty.
4614   //
4615   // Spurious qualifiers here appear to be valid in C.
4616   unsigned DiagID = diag::warn_standalone_specifier;
4617   if (getLangOpts().CPlusPlus)
4618     DiagID = diag::ext_standalone_specifier;
4619 
4620   // Note that a linkage-specification sets a storage class, but
4621   // 'extern "C" struct foo;' is actually valid and not theoretically
4622   // useless.
4623   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4624     if (SCS == DeclSpec::SCS_mutable)
4625       // Since mutable is not a viable storage class specifier in C, there is
4626       // no reason to treat it as an extension. Instead, diagnose as an error.
4627       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4628     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4629       Diag(DS.getStorageClassSpecLoc(), DiagID)
4630         << DeclSpec::getSpecifierName(SCS);
4631   }
4632 
4633   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4634     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4635       << DeclSpec::getSpecifierName(TSCS);
4636   if (DS.getTypeQualifiers()) {
4637     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4638       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4639     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4640       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4641     // Restrict is covered above.
4642     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4643       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4644     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4645       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4646   }
4647 
4648   // Warn about ignored type attributes, for example:
4649   // __attribute__((aligned)) struct A;
4650   // Attributes should be placed after tag to apply to type declaration.
4651   if (!DS.getAttributes().empty()) {
4652     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4653     if (TypeSpecType == DeclSpec::TST_class ||
4654         TypeSpecType == DeclSpec::TST_struct ||
4655         TypeSpecType == DeclSpec::TST_interface ||
4656         TypeSpecType == DeclSpec::TST_union ||
4657         TypeSpecType == DeclSpec::TST_enum) {
4658       for (const ParsedAttr &AL : DS.getAttributes())
4659         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4660             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4661     }
4662   }
4663 
4664   return TagD;
4665 }
4666 
4667 /// We are trying to inject an anonymous member into the given scope;
4668 /// check if there's an existing declaration that can't be overloaded.
4669 ///
4670 /// \return true if this is a forbidden redeclaration
4671 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4672                                          Scope *S,
4673                                          DeclContext *Owner,
4674                                          DeclarationName Name,
4675                                          SourceLocation NameLoc,
4676                                          bool IsUnion) {
4677   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4678                  Sema::ForVisibleRedeclaration);
4679   if (!SemaRef.LookupName(R, S)) return false;
4680 
4681   // Pick a representative declaration.
4682   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4683   assert(PrevDecl && "Expected a non-null Decl");
4684 
4685   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4686     return false;
4687 
4688   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4689     << IsUnion << Name;
4690   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4691 
4692   return true;
4693 }
4694 
4695 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4696 /// anonymous struct or union AnonRecord into the owning context Owner
4697 /// and scope S. This routine will be invoked just after we realize
4698 /// that an unnamed union or struct is actually an anonymous union or
4699 /// struct, e.g.,
4700 ///
4701 /// @code
4702 /// union {
4703 ///   int i;
4704 ///   float f;
4705 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4706 ///    // f into the surrounding scope.x
4707 /// @endcode
4708 ///
4709 /// This routine is recursive, injecting the names of nested anonymous
4710 /// structs/unions into the owning context and scope as well.
4711 static bool
4712 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4713                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4714                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4715   bool Invalid = false;
4716 
4717   // Look every FieldDecl and IndirectFieldDecl with a name.
4718   for (auto *D : AnonRecord->decls()) {
4719     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4720         cast<NamedDecl>(D)->getDeclName()) {
4721       ValueDecl *VD = cast<ValueDecl>(D);
4722       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4723                                        VD->getLocation(),
4724                                        AnonRecord->isUnion())) {
4725         // C++ [class.union]p2:
4726         //   The names of the members of an anonymous union shall be
4727         //   distinct from the names of any other entity in the
4728         //   scope in which the anonymous union is declared.
4729         Invalid = true;
4730       } else {
4731         // C++ [class.union]p2:
4732         //   For the purpose of name lookup, after the anonymous union
4733         //   definition, the members of the anonymous union are
4734         //   considered to have been defined in the scope in which the
4735         //   anonymous union is declared.
4736         unsigned OldChainingSize = Chaining.size();
4737         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4738           Chaining.append(IF->chain_begin(), IF->chain_end());
4739         else
4740           Chaining.push_back(VD);
4741 
4742         assert(Chaining.size() >= 2);
4743         NamedDecl **NamedChain =
4744           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4745         for (unsigned i = 0; i < Chaining.size(); i++)
4746           NamedChain[i] = Chaining[i];
4747 
4748         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4749             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4750             VD->getType(), {NamedChain, Chaining.size()});
4751 
4752         for (const auto *Attr : VD->attrs())
4753           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4754 
4755         IndirectField->setAccess(AS);
4756         IndirectField->setImplicit();
4757         SemaRef.PushOnScopeChains(IndirectField, S);
4758 
4759         // That includes picking up the appropriate access specifier.
4760         if (AS != AS_none) IndirectField->setAccess(AS);
4761 
4762         Chaining.resize(OldChainingSize);
4763       }
4764     }
4765   }
4766 
4767   return Invalid;
4768 }
4769 
4770 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4771 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4772 /// illegal input values are mapped to SC_None.
4773 static StorageClass
4774 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4775   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4776   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4777          "Parser allowed 'typedef' as storage class VarDecl.");
4778   switch (StorageClassSpec) {
4779   case DeclSpec::SCS_unspecified:    return SC_None;
4780   case DeclSpec::SCS_extern:
4781     if (DS.isExternInLinkageSpec())
4782       return SC_None;
4783     return SC_Extern;
4784   case DeclSpec::SCS_static:         return SC_Static;
4785   case DeclSpec::SCS_auto:           return SC_Auto;
4786   case DeclSpec::SCS_register:       return SC_Register;
4787   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4788     // Illegal SCSs map to None: error reporting is up to the caller.
4789   case DeclSpec::SCS_mutable:        // Fall through.
4790   case DeclSpec::SCS_typedef:        return SC_None;
4791   }
4792   llvm_unreachable("unknown storage class specifier");
4793 }
4794 
4795 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4796   assert(Record->hasInClassInitializer());
4797 
4798   for (const auto *I : Record->decls()) {
4799     const auto *FD = dyn_cast<FieldDecl>(I);
4800     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4801       FD = IFD->getAnonField();
4802     if (FD && FD->hasInClassInitializer())
4803       return FD->getLocation();
4804   }
4805 
4806   llvm_unreachable("couldn't find in-class initializer");
4807 }
4808 
4809 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4810                                       SourceLocation DefaultInitLoc) {
4811   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4812     return;
4813 
4814   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4815   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4816 }
4817 
4818 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4819                                       CXXRecordDecl *AnonUnion) {
4820   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4821     return;
4822 
4823   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4824 }
4825 
4826 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4827 /// anonymous structure or union. Anonymous unions are a C++ feature
4828 /// (C++ [class.union]) and a C11 feature; anonymous structures
4829 /// are a C11 feature and GNU C++ extension.
4830 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4831                                         AccessSpecifier AS,
4832                                         RecordDecl *Record,
4833                                         const PrintingPolicy &Policy) {
4834   DeclContext *Owner = Record->getDeclContext();
4835 
4836   // Diagnose whether this anonymous struct/union is an extension.
4837   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4838     Diag(Record->getLocation(), diag::ext_anonymous_union);
4839   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4840     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4841   else if (!Record->isUnion() && !getLangOpts().C11)
4842     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4843 
4844   // C and C++ require different kinds of checks for anonymous
4845   // structs/unions.
4846   bool Invalid = false;
4847   if (getLangOpts().CPlusPlus) {
4848     const char *PrevSpec = nullptr;
4849     if (Record->isUnion()) {
4850       // C++ [class.union]p6:
4851       // C++17 [class.union.anon]p2:
4852       //   Anonymous unions declared in a named namespace or in the
4853       //   global namespace shall be declared static.
4854       unsigned DiagID;
4855       DeclContext *OwnerScope = Owner->getRedeclContext();
4856       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4857           (OwnerScope->isTranslationUnit() ||
4858            (OwnerScope->isNamespace() &&
4859             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4860         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4861           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4862 
4863         // Recover by adding 'static'.
4864         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4865                                PrevSpec, DiagID, Policy);
4866       }
4867       // C++ [class.union]p6:
4868       //   A storage class is not allowed in a declaration of an
4869       //   anonymous union in a class scope.
4870       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4871                isa<RecordDecl>(Owner)) {
4872         Diag(DS.getStorageClassSpecLoc(),
4873              diag::err_anonymous_union_with_storage_spec)
4874           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4875 
4876         // Recover by removing the storage specifier.
4877         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4878                                SourceLocation(),
4879                                PrevSpec, DiagID, Context.getPrintingPolicy());
4880       }
4881     }
4882 
4883     // Ignore const/volatile/restrict qualifiers.
4884     if (DS.getTypeQualifiers()) {
4885       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4886         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4887           << Record->isUnion() << "const"
4888           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4889       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4890         Diag(DS.getVolatileSpecLoc(),
4891              diag::ext_anonymous_struct_union_qualified)
4892           << Record->isUnion() << "volatile"
4893           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4894       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4895         Diag(DS.getRestrictSpecLoc(),
4896              diag::ext_anonymous_struct_union_qualified)
4897           << Record->isUnion() << "restrict"
4898           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4899       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4900         Diag(DS.getAtomicSpecLoc(),
4901              diag::ext_anonymous_struct_union_qualified)
4902           << Record->isUnion() << "_Atomic"
4903           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4904       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4905         Diag(DS.getUnalignedSpecLoc(),
4906              diag::ext_anonymous_struct_union_qualified)
4907           << Record->isUnion() << "__unaligned"
4908           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4909 
4910       DS.ClearTypeQualifiers();
4911     }
4912 
4913     // C++ [class.union]p2:
4914     //   The member-specification of an anonymous union shall only
4915     //   define non-static data members. [Note: nested types and
4916     //   functions cannot be declared within an anonymous union. ]
4917     for (auto *Mem : Record->decls()) {
4918       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4919         // C++ [class.union]p3:
4920         //   An anonymous union shall not have private or protected
4921         //   members (clause 11).
4922         assert(FD->getAccess() != AS_none);
4923         if (FD->getAccess() != AS_public) {
4924           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4925             << Record->isUnion() << (FD->getAccess() == AS_protected);
4926           Invalid = true;
4927         }
4928 
4929         // C++ [class.union]p1
4930         //   An object of a class with a non-trivial constructor, a non-trivial
4931         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4932         //   assignment operator cannot be a member of a union, nor can an
4933         //   array of such objects.
4934         if (CheckNontrivialField(FD))
4935           Invalid = true;
4936       } else if (Mem->isImplicit()) {
4937         // Any implicit members are fine.
4938       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4939         // This is a type that showed up in an
4940         // elaborated-type-specifier inside the anonymous struct or
4941         // union, but which actually declares a type outside of the
4942         // anonymous struct or union. It's okay.
4943       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4944         if (!MemRecord->isAnonymousStructOrUnion() &&
4945             MemRecord->getDeclName()) {
4946           // Visual C++ allows type definition in anonymous struct or union.
4947           if (getLangOpts().MicrosoftExt)
4948             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4949               << Record->isUnion();
4950           else {
4951             // This is a nested type declaration.
4952             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4953               << Record->isUnion();
4954             Invalid = true;
4955           }
4956         } else {
4957           // This is an anonymous type definition within another anonymous type.
4958           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4959           // not part of standard C++.
4960           Diag(MemRecord->getLocation(),
4961                diag::ext_anonymous_record_with_anonymous_type)
4962             << Record->isUnion();
4963         }
4964       } else if (isa<AccessSpecDecl>(Mem)) {
4965         // Any access specifier is fine.
4966       } else if (isa<StaticAssertDecl>(Mem)) {
4967         // In C++1z, static_assert declarations are also fine.
4968       } else {
4969         // We have something that isn't a non-static data
4970         // member. Complain about it.
4971         unsigned DK = diag::err_anonymous_record_bad_member;
4972         if (isa<TypeDecl>(Mem))
4973           DK = diag::err_anonymous_record_with_type;
4974         else if (isa<FunctionDecl>(Mem))
4975           DK = diag::err_anonymous_record_with_function;
4976         else if (isa<VarDecl>(Mem))
4977           DK = diag::err_anonymous_record_with_static;
4978 
4979         // Visual C++ allows type definition in anonymous struct or union.
4980         if (getLangOpts().MicrosoftExt &&
4981             DK == diag::err_anonymous_record_with_type)
4982           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4983             << Record->isUnion();
4984         else {
4985           Diag(Mem->getLocation(), DK) << Record->isUnion();
4986           Invalid = true;
4987         }
4988       }
4989     }
4990 
4991     // C++11 [class.union]p8 (DR1460):
4992     //   At most one variant member of a union may have a
4993     //   brace-or-equal-initializer.
4994     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4995         Owner->isRecord())
4996       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4997                                 cast<CXXRecordDecl>(Record));
4998   }
4999 
5000   if (!Record->isUnion() && !Owner->isRecord()) {
5001     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5002       << getLangOpts().CPlusPlus;
5003     Invalid = true;
5004   }
5005 
5006   // C++ [dcl.dcl]p3:
5007   //   [If there are no declarators], and except for the declaration of an
5008   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5009   //   names into the program
5010   // C++ [class.mem]p2:
5011   //   each such member-declaration shall either declare at least one member
5012   //   name of the class or declare at least one unnamed bit-field
5013   //
5014   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5015   if (getLangOpts().CPlusPlus && Record->field_empty())
5016     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5017 
5018   // Mock up a declarator.
5019   Declarator Dc(DS, DeclaratorContext::MemberContext);
5020   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5021   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5022 
5023   // Create a declaration for this anonymous struct/union.
5024   NamedDecl *Anon = nullptr;
5025   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5026     Anon = FieldDecl::Create(
5027         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5028         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5029         /*BitWidth=*/nullptr, /*Mutable=*/false,
5030         /*InitStyle=*/ICIS_NoInit);
5031     Anon->setAccess(AS);
5032     ProcessDeclAttributes(S, Anon, Dc);
5033 
5034     if (getLangOpts().CPlusPlus)
5035       FieldCollector->Add(cast<FieldDecl>(Anon));
5036   } else {
5037     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5038     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5039     if (SCSpec == DeclSpec::SCS_mutable) {
5040       // mutable can only appear on non-static class members, so it's always
5041       // an error here
5042       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5043       Invalid = true;
5044       SC = SC_None;
5045     }
5046 
5047     assert(DS.getAttributes().empty() && "No attribute expected");
5048     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5049                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5050                            Context.getTypeDeclType(Record), TInfo, SC);
5051 
5052     // Default-initialize the implicit variable. This initialization will be
5053     // trivial in almost all cases, except if a union member has an in-class
5054     // initializer:
5055     //   union { int n = 0; };
5056     ActOnUninitializedDecl(Anon);
5057   }
5058   Anon->setImplicit();
5059 
5060   // Mark this as an anonymous struct/union type.
5061   Record->setAnonymousStructOrUnion(true);
5062 
5063   // Add the anonymous struct/union object to the current
5064   // context. We'll be referencing this object when we refer to one of
5065   // its members.
5066   Owner->addDecl(Anon);
5067 
5068   // Inject the members of the anonymous struct/union into the owning
5069   // context and into the identifier resolver chain for name lookup
5070   // purposes.
5071   SmallVector<NamedDecl*, 2> Chain;
5072   Chain.push_back(Anon);
5073 
5074   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5075     Invalid = true;
5076 
5077   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5078     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5079       MangleNumberingContext *MCtx;
5080       Decl *ManglingContextDecl;
5081       std::tie(MCtx, ManglingContextDecl) =
5082           getCurrentMangleNumberContext(NewVD->getDeclContext());
5083       if (MCtx) {
5084         Context.setManglingNumber(
5085             NewVD, MCtx->getManglingNumber(
5086                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5087         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5088       }
5089     }
5090   }
5091 
5092   if (Invalid)
5093     Anon->setInvalidDecl();
5094 
5095   return Anon;
5096 }
5097 
5098 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5099 /// Microsoft C anonymous structure.
5100 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5101 /// Example:
5102 ///
5103 /// struct A { int a; };
5104 /// struct B { struct A; int b; };
5105 ///
5106 /// void foo() {
5107 ///   B var;
5108 ///   var.a = 3;
5109 /// }
5110 ///
5111 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5112                                            RecordDecl *Record) {
5113   assert(Record && "expected a record!");
5114 
5115   // Mock up a declarator.
5116   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5117   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5118   assert(TInfo && "couldn't build declarator info for anonymous struct");
5119 
5120   auto *ParentDecl = cast<RecordDecl>(CurContext);
5121   QualType RecTy = Context.getTypeDeclType(Record);
5122 
5123   // Create a declaration for this anonymous struct.
5124   NamedDecl *Anon =
5125       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5126                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5127                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5128                         /*InitStyle=*/ICIS_NoInit);
5129   Anon->setImplicit();
5130 
5131   // Add the anonymous struct object to the current context.
5132   CurContext->addDecl(Anon);
5133 
5134   // Inject the members of the anonymous struct into the current
5135   // context and into the identifier resolver chain for name lookup
5136   // purposes.
5137   SmallVector<NamedDecl*, 2> Chain;
5138   Chain.push_back(Anon);
5139 
5140   RecordDecl *RecordDef = Record->getDefinition();
5141   if (RequireCompleteType(Anon->getLocation(), RecTy,
5142                           diag::err_field_incomplete) ||
5143       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5144                                           AS_none, Chain)) {
5145     Anon->setInvalidDecl();
5146     ParentDecl->setInvalidDecl();
5147   }
5148 
5149   return Anon;
5150 }
5151 
5152 /// GetNameForDeclarator - Determine the full declaration name for the
5153 /// given Declarator.
5154 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5155   return GetNameFromUnqualifiedId(D.getName());
5156 }
5157 
5158 /// Retrieves the declaration name from a parsed unqualified-id.
5159 DeclarationNameInfo
5160 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5161   DeclarationNameInfo NameInfo;
5162   NameInfo.setLoc(Name.StartLocation);
5163 
5164   switch (Name.getKind()) {
5165 
5166   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5167   case UnqualifiedIdKind::IK_Identifier:
5168     NameInfo.setName(Name.Identifier);
5169     return NameInfo;
5170 
5171   case UnqualifiedIdKind::IK_DeductionGuideName: {
5172     // C++ [temp.deduct.guide]p3:
5173     //   The simple-template-id shall name a class template specialization.
5174     //   The template-name shall be the same identifier as the template-name
5175     //   of the simple-template-id.
5176     // These together intend to imply that the template-name shall name a
5177     // class template.
5178     // FIXME: template<typename T> struct X {};
5179     //        template<typename T> using Y = X<T>;
5180     //        Y(int) -> Y<int>;
5181     //   satisfies these rules but does not name a class template.
5182     TemplateName TN = Name.TemplateName.get().get();
5183     auto *Template = TN.getAsTemplateDecl();
5184     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5185       Diag(Name.StartLocation,
5186            diag::err_deduction_guide_name_not_class_template)
5187         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5188       if (Template)
5189         Diag(Template->getLocation(), diag::note_template_decl_here);
5190       return DeclarationNameInfo();
5191     }
5192 
5193     NameInfo.setName(
5194         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5195     return NameInfo;
5196   }
5197 
5198   case UnqualifiedIdKind::IK_OperatorFunctionId:
5199     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5200                                            Name.OperatorFunctionId.Operator));
5201     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5202       = Name.OperatorFunctionId.SymbolLocations[0];
5203     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5204       = Name.EndLocation.getRawEncoding();
5205     return NameInfo;
5206 
5207   case UnqualifiedIdKind::IK_LiteralOperatorId:
5208     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5209                                                            Name.Identifier));
5210     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5211     return NameInfo;
5212 
5213   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5214     TypeSourceInfo *TInfo;
5215     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5216     if (Ty.isNull())
5217       return DeclarationNameInfo();
5218     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5219                                                Context.getCanonicalType(Ty)));
5220     NameInfo.setNamedTypeInfo(TInfo);
5221     return NameInfo;
5222   }
5223 
5224   case UnqualifiedIdKind::IK_ConstructorName: {
5225     TypeSourceInfo *TInfo;
5226     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5227     if (Ty.isNull())
5228       return DeclarationNameInfo();
5229     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5230                                               Context.getCanonicalType(Ty)));
5231     NameInfo.setNamedTypeInfo(TInfo);
5232     return NameInfo;
5233   }
5234 
5235   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5236     // In well-formed code, we can only have a constructor
5237     // template-id that refers to the current context, so go there
5238     // to find the actual type being constructed.
5239     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5240     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5241       return DeclarationNameInfo();
5242 
5243     // Determine the type of the class being constructed.
5244     QualType CurClassType = Context.getTypeDeclType(CurClass);
5245 
5246     // FIXME: Check two things: that the template-id names the same type as
5247     // CurClassType, and that the template-id does not occur when the name
5248     // was qualified.
5249 
5250     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5251                                     Context.getCanonicalType(CurClassType)));
5252     // FIXME: should we retrieve TypeSourceInfo?
5253     NameInfo.setNamedTypeInfo(nullptr);
5254     return NameInfo;
5255   }
5256 
5257   case UnqualifiedIdKind::IK_DestructorName: {
5258     TypeSourceInfo *TInfo;
5259     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5260     if (Ty.isNull())
5261       return DeclarationNameInfo();
5262     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5263                                               Context.getCanonicalType(Ty)));
5264     NameInfo.setNamedTypeInfo(TInfo);
5265     return NameInfo;
5266   }
5267 
5268   case UnqualifiedIdKind::IK_TemplateId: {
5269     TemplateName TName = Name.TemplateId->Template.get();
5270     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5271     return Context.getNameForTemplate(TName, TNameLoc);
5272   }
5273 
5274   } // switch (Name.getKind())
5275 
5276   llvm_unreachable("Unknown name kind");
5277 }
5278 
5279 static QualType getCoreType(QualType Ty) {
5280   do {
5281     if (Ty->isPointerType() || Ty->isReferenceType())
5282       Ty = Ty->getPointeeType();
5283     else if (Ty->isArrayType())
5284       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5285     else
5286       return Ty.withoutLocalFastQualifiers();
5287   } while (true);
5288 }
5289 
5290 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5291 /// and Definition have "nearly" matching parameters. This heuristic is
5292 /// used to improve diagnostics in the case where an out-of-line function
5293 /// definition doesn't match any declaration within the class or namespace.
5294 /// Also sets Params to the list of indices to the parameters that differ
5295 /// between the declaration and the definition. If hasSimilarParameters
5296 /// returns true and Params is empty, then all of the parameters match.
5297 static bool hasSimilarParameters(ASTContext &Context,
5298                                      FunctionDecl *Declaration,
5299                                      FunctionDecl *Definition,
5300                                      SmallVectorImpl<unsigned> &Params) {
5301   Params.clear();
5302   if (Declaration->param_size() != Definition->param_size())
5303     return false;
5304   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5305     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5306     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5307 
5308     // The parameter types are identical
5309     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5310       continue;
5311 
5312     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5313     QualType DefParamBaseTy = getCoreType(DefParamTy);
5314     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5315     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5316 
5317     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5318         (DeclTyName && DeclTyName == DefTyName))
5319       Params.push_back(Idx);
5320     else  // The two parameters aren't even close
5321       return false;
5322   }
5323 
5324   return true;
5325 }
5326 
5327 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5328 /// declarator needs to be rebuilt in the current instantiation.
5329 /// Any bits of declarator which appear before the name are valid for
5330 /// consideration here.  That's specifically the type in the decl spec
5331 /// and the base type in any member-pointer chunks.
5332 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5333                                                     DeclarationName Name) {
5334   // The types we specifically need to rebuild are:
5335   //   - typenames, typeofs, and decltypes
5336   //   - types which will become injected class names
5337   // Of course, we also need to rebuild any type referencing such a
5338   // type.  It's safest to just say "dependent", but we call out a
5339   // few cases here.
5340 
5341   DeclSpec &DS = D.getMutableDeclSpec();
5342   switch (DS.getTypeSpecType()) {
5343   case DeclSpec::TST_typename:
5344   case DeclSpec::TST_typeofType:
5345   case DeclSpec::TST_underlyingType:
5346   case DeclSpec::TST_atomic: {
5347     // Grab the type from the parser.
5348     TypeSourceInfo *TSI = nullptr;
5349     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5350     if (T.isNull() || !T->isDependentType()) break;
5351 
5352     // Make sure there's a type source info.  This isn't really much
5353     // of a waste; most dependent types should have type source info
5354     // attached already.
5355     if (!TSI)
5356       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5357 
5358     // Rebuild the type in the current instantiation.
5359     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5360     if (!TSI) return true;
5361 
5362     // Store the new type back in the decl spec.
5363     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5364     DS.UpdateTypeRep(LocType);
5365     break;
5366   }
5367 
5368   case DeclSpec::TST_decltype:
5369   case DeclSpec::TST_typeofExpr: {
5370     Expr *E = DS.getRepAsExpr();
5371     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5372     if (Result.isInvalid()) return true;
5373     DS.UpdateExprRep(Result.get());
5374     break;
5375   }
5376 
5377   default:
5378     // Nothing to do for these decl specs.
5379     break;
5380   }
5381 
5382   // It doesn't matter what order we do this in.
5383   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5384     DeclaratorChunk &Chunk = D.getTypeObject(I);
5385 
5386     // The only type information in the declarator which can come
5387     // before the declaration name is the base type of a member
5388     // pointer.
5389     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5390       continue;
5391 
5392     // Rebuild the scope specifier in-place.
5393     CXXScopeSpec &SS = Chunk.Mem.Scope();
5394     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5395       return true;
5396   }
5397 
5398   return false;
5399 }
5400 
5401 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5402   D.setFunctionDefinitionKind(FDK_Declaration);
5403   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5404 
5405   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5406       Dcl && Dcl->getDeclContext()->isFileContext())
5407     Dcl->setTopLevelDeclInObjCContainer();
5408 
5409   if (getLangOpts().OpenCL)
5410     setCurrentOpenCLExtensionForDecl(Dcl);
5411 
5412   return Dcl;
5413 }
5414 
5415 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5416 ///   If T is the name of a class, then each of the following shall have a
5417 ///   name different from T:
5418 ///     - every static data member of class T;
5419 ///     - every member function of class T
5420 ///     - every member of class T that is itself a type;
5421 /// \returns true if the declaration name violates these rules.
5422 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5423                                    DeclarationNameInfo NameInfo) {
5424   DeclarationName Name = NameInfo.getName();
5425 
5426   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5427   while (Record && Record->isAnonymousStructOrUnion())
5428     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5429   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5430     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5431     return true;
5432   }
5433 
5434   return false;
5435 }
5436 
5437 /// Diagnose a declaration whose declarator-id has the given
5438 /// nested-name-specifier.
5439 ///
5440 /// \param SS The nested-name-specifier of the declarator-id.
5441 ///
5442 /// \param DC The declaration context to which the nested-name-specifier
5443 /// resolves.
5444 ///
5445 /// \param Name The name of the entity being declared.
5446 ///
5447 /// \param Loc The location of the name of the entity being declared.
5448 ///
5449 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5450 /// we're declaring an explicit / partial specialization / instantiation.
5451 ///
5452 /// \returns true if we cannot safely recover from this error, false otherwise.
5453 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5454                                         DeclarationName Name,
5455                                         SourceLocation Loc, bool IsTemplateId) {
5456   DeclContext *Cur = CurContext;
5457   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5458     Cur = Cur->getParent();
5459 
5460   // If the user provided a superfluous scope specifier that refers back to the
5461   // class in which the entity is already declared, diagnose and ignore it.
5462   //
5463   // class X {
5464   //   void X::f();
5465   // };
5466   //
5467   // Note, it was once ill-formed to give redundant qualification in all
5468   // contexts, but that rule was removed by DR482.
5469   if (Cur->Equals(DC)) {
5470     if (Cur->isRecord()) {
5471       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5472                                       : diag::err_member_extra_qualification)
5473         << Name << FixItHint::CreateRemoval(SS.getRange());
5474       SS.clear();
5475     } else {
5476       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5477     }
5478     return false;
5479   }
5480 
5481   // Check whether the qualifying scope encloses the scope of the original
5482   // declaration. For a template-id, we perform the checks in
5483   // CheckTemplateSpecializationScope.
5484   if (!Cur->Encloses(DC) && !IsTemplateId) {
5485     if (Cur->isRecord())
5486       Diag(Loc, diag::err_member_qualification)
5487         << Name << SS.getRange();
5488     else if (isa<TranslationUnitDecl>(DC))
5489       Diag(Loc, diag::err_invalid_declarator_global_scope)
5490         << Name << SS.getRange();
5491     else if (isa<FunctionDecl>(Cur))
5492       Diag(Loc, diag::err_invalid_declarator_in_function)
5493         << Name << SS.getRange();
5494     else if (isa<BlockDecl>(Cur))
5495       Diag(Loc, diag::err_invalid_declarator_in_block)
5496         << Name << SS.getRange();
5497     else
5498       Diag(Loc, diag::err_invalid_declarator_scope)
5499       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5500 
5501     return true;
5502   }
5503 
5504   if (Cur->isRecord()) {
5505     // Cannot qualify members within a class.
5506     Diag(Loc, diag::err_member_qualification)
5507       << Name << SS.getRange();
5508     SS.clear();
5509 
5510     // C++ constructors and destructors with incorrect scopes can break
5511     // our AST invariants by having the wrong underlying types. If
5512     // that's the case, then drop this declaration entirely.
5513     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5514          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5515         !Context.hasSameType(Name.getCXXNameType(),
5516                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5517       return true;
5518 
5519     return false;
5520   }
5521 
5522   // C++11 [dcl.meaning]p1:
5523   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5524   //   not begin with a decltype-specifer"
5525   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5526   while (SpecLoc.getPrefix())
5527     SpecLoc = SpecLoc.getPrefix();
5528   if (dyn_cast_or_null<DecltypeType>(
5529         SpecLoc.getNestedNameSpecifier()->getAsType()))
5530     Diag(Loc, diag::err_decltype_in_declarator)
5531       << SpecLoc.getTypeLoc().getSourceRange();
5532 
5533   return false;
5534 }
5535 
5536 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5537                                   MultiTemplateParamsArg TemplateParamLists) {
5538   // TODO: consider using NameInfo for diagnostic.
5539   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5540   DeclarationName Name = NameInfo.getName();
5541 
5542   // All of these full declarators require an identifier.  If it doesn't have
5543   // one, the ParsedFreeStandingDeclSpec action should be used.
5544   if (D.isDecompositionDeclarator()) {
5545     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5546   } else if (!Name) {
5547     if (!D.isInvalidType())  // Reject this if we think it is valid.
5548       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5549           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5550     return nullptr;
5551   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5552     return nullptr;
5553 
5554   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5555   // we find one that is.
5556   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5557          (S->getFlags() & Scope::TemplateParamScope) != 0)
5558     S = S->getParent();
5559 
5560   DeclContext *DC = CurContext;
5561   if (D.getCXXScopeSpec().isInvalid())
5562     D.setInvalidType();
5563   else if (D.getCXXScopeSpec().isSet()) {
5564     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5565                                         UPPC_DeclarationQualifier))
5566       return nullptr;
5567 
5568     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5569     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5570     if (!DC || isa<EnumDecl>(DC)) {
5571       // If we could not compute the declaration context, it's because the
5572       // declaration context is dependent but does not refer to a class,
5573       // class template, or class template partial specialization. Complain
5574       // and return early, to avoid the coming semantic disaster.
5575       Diag(D.getIdentifierLoc(),
5576            diag::err_template_qualified_declarator_no_match)
5577         << D.getCXXScopeSpec().getScopeRep()
5578         << D.getCXXScopeSpec().getRange();
5579       return nullptr;
5580     }
5581     bool IsDependentContext = DC->isDependentContext();
5582 
5583     if (!IsDependentContext &&
5584         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5585       return nullptr;
5586 
5587     // If a class is incomplete, do not parse entities inside it.
5588     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5589       Diag(D.getIdentifierLoc(),
5590            diag::err_member_def_undefined_record)
5591         << Name << DC << D.getCXXScopeSpec().getRange();
5592       return nullptr;
5593     }
5594     if (!D.getDeclSpec().isFriendSpecified()) {
5595       if (diagnoseQualifiedDeclaration(
5596               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5597               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5598         if (DC->isRecord())
5599           return nullptr;
5600 
5601         D.setInvalidType();
5602       }
5603     }
5604 
5605     // Check whether we need to rebuild the type of the given
5606     // declaration in the current instantiation.
5607     if (EnteringContext && IsDependentContext &&
5608         TemplateParamLists.size() != 0) {
5609       ContextRAII SavedContext(*this, DC);
5610       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5611         D.setInvalidType();
5612     }
5613   }
5614 
5615   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5616   QualType R = TInfo->getType();
5617 
5618   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5619                                       UPPC_DeclarationType))
5620     D.setInvalidType();
5621 
5622   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5623                         forRedeclarationInCurContext());
5624 
5625   // See if this is a redefinition of a variable in the same scope.
5626   if (!D.getCXXScopeSpec().isSet()) {
5627     bool IsLinkageLookup = false;
5628     bool CreateBuiltins = false;
5629 
5630     // If the declaration we're planning to build will be a function
5631     // or object with linkage, then look for another declaration with
5632     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5633     //
5634     // If the declaration we're planning to build will be declared with
5635     // external linkage in the translation unit, create any builtin with
5636     // the same name.
5637     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5638       /* Do nothing*/;
5639     else if (CurContext->isFunctionOrMethod() &&
5640              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5641               R->isFunctionType())) {
5642       IsLinkageLookup = true;
5643       CreateBuiltins =
5644           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5645     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5646                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5647       CreateBuiltins = true;
5648 
5649     if (IsLinkageLookup) {
5650       Previous.clear(LookupRedeclarationWithLinkage);
5651       Previous.setRedeclarationKind(ForExternalRedeclaration);
5652     }
5653 
5654     LookupName(Previous, S, CreateBuiltins);
5655   } else { // Something like "int foo::x;"
5656     LookupQualifiedName(Previous, DC);
5657 
5658     // C++ [dcl.meaning]p1:
5659     //   When the declarator-id is qualified, the declaration shall refer to a
5660     //  previously declared member of the class or namespace to which the
5661     //  qualifier refers (or, in the case of a namespace, of an element of the
5662     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5663     //  thereof; [...]
5664     //
5665     // Note that we already checked the context above, and that we do not have
5666     // enough information to make sure that Previous contains the declaration
5667     // we want to match. For example, given:
5668     //
5669     //   class X {
5670     //     void f();
5671     //     void f(float);
5672     //   };
5673     //
5674     //   void X::f(int) { } // ill-formed
5675     //
5676     // In this case, Previous will point to the overload set
5677     // containing the two f's declared in X, but neither of them
5678     // matches.
5679 
5680     // C++ [dcl.meaning]p1:
5681     //   [...] the member shall not merely have been introduced by a
5682     //   using-declaration in the scope of the class or namespace nominated by
5683     //   the nested-name-specifier of the declarator-id.
5684     RemoveUsingDecls(Previous);
5685   }
5686 
5687   if (Previous.isSingleResult() &&
5688       Previous.getFoundDecl()->isTemplateParameter()) {
5689     // Maybe we will complain about the shadowed template parameter.
5690     if (!D.isInvalidType())
5691       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5692                                       Previous.getFoundDecl());
5693 
5694     // Just pretend that we didn't see the previous declaration.
5695     Previous.clear();
5696   }
5697 
5698   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5699     // Forget that the previous declaration is the injected-class-name.
5700     Previous.clear();
5701 
5702   // In C++, the previous declaration we find might be a tag type
5703   // (class or enum). In this case, the new declaration will hide the
5704   // tag type. Note that this applies to functions, function templates, and
5705   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5706   if (Previous.isSingleTagDecl() &&
5707       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5708       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5709     Previous.clear();
5710 
5711   // Check that there are no default arguments other than in the parameters
5712   // of a function declaration (C++ only).
5713   if (getLangOpts().CPlusPlus)
5714     CheckExtraCXXDefaultArguments(D);
5715 
5716   NamedDecl *New;
5717 
5718   bool AddToScope = true;
5719   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5720     if (TemplateParamLists.size()) {
5721       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5722       return nullptr;
5723     }
5724 
5725     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5726   } else if (R->isFunctionType()) {
5727     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5728                                   TemplateParamLists,
5729                                   AddToScope);
5730   } else {
5731     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5732                                   AddToScope);
5733   }
5734 
5735   if (!New)
5736     return nullptr;
5737 
5738   // If this has an identifier and is not a function template specialization,
5739   // add it to the scope stack.
5740   if (New->getDeclName() && AddToScope)
5741     PushOnScopeChains(New, S);
5742 
5743   if (isInOpenMPDeclareTargetContext())
5744     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5745 
5746   return New;
5747 }
5748 
5749 /// Helper method to turn variable array types into constant array
5750 /// types in certain situations which would otherwise be errors (for
5751 /// GCC compatibility).
5752 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5753                                                     ASTContext &Context,
5754                                                     bool &SizeIsNegative,
5755                                                     llvm::APSInt &Oversized) {
5756   // This method tries to turn a variable array into a constant
5757   // array even when the size isn't an ICE.  This is necessary
5758   // for compatibility with code that depends on gcc's buggy
5759   // constant expression folding, like struct {char x[(int)(char*)2];}
5760   SizeIsNegative = false;
5761   Oversized = 0;
5762 
5763   if (T->isDependentType())
5764     return QualType();
5765 
5766   QualifierCollector Qs;
5767   const Type *Ty = Qs.strip(T);
5768 
5769   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5770     QualType Pointee = PTy->getPointeeType();
5771     QualType FixedType =
5772         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5773                                             Oversized);
5774     if (FixedType.isNull()) return FixedType;
5775     FixedType = Context.getPointerType(FixedType);
5776     return Qs.apply(Context, FixedType);
5777   }
5778   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5779     QualType Inner = PTy->getInnerType();
5780     QualType FixedType =
5781         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5782                                             Oversized);
5783     if (FixedType.isNull()) return FixedType;
5784     FixedType = Context.getParenType(FixedType);
5785     return Qs.apply(Context, FixedType);
5786   }
5787 
5788   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5789   if (!VLATy)
5790     return QualType();
5791   // FIXME: We should probably handle this case
5792   if (VLATy->getElementType()->isVariablyModifiedType())
5793     return QualType();
5794 
5795   Expr::EvalResult Result;
5796   if (!VLATy->getSizeExpr() ||
5797       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5798     return QualType();
5799 
5800   llvm::APSInt Res = Result.Val.getInt();
5801 
5802   // Check whether the array size is negative.
5803   if (Res.isSigned() && Res.isNegative()) {
5804     SizeIsNegative = true;
5805     return QualType();
5806   }
5807 
5808   // Check whether the array is too large to be addressed.
5809   unsigned ActiveSizeBits
5810     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5811                                               Res);
5812   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5813     Oversized = Res;
5814     return QualType();
5815   }
5816 
5817   return Context.getConstantArrayType(
5818       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5819 }
5820 
5821 static void
5822 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5823   SrcTL = SrcTL.getUnqualifiedLoc();
5824   DstTL = DstTL.getUnqualifiedLoc();
5825   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5826     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5827     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5828                                       DstPTL.getPointeeLoc());
5829     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5830     return;
5831   }
5832   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5833     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5834     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5835                                       DstPTL.getInnerLoc());
5836     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5837     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5838     return;
5839   }
5840   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5841   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5842   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5843   TypeLoc DstElemTL = DstATL.getElementLoc();
5844   DstElemTL.initializeFullCopy(SrcElemTL);
5845   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5846   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5847   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5848 }
5849 
5850 /// Helper method to turn variable array types into constant array
5851 /// types in certain situations which would otherwise be errors (for
5852 /// GCC compatibility).
5853 static TypeSourceInfo*
5854 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5855                                               ASTContext &Context,
5856                                               bool &SizeIsNegative,
5857                                               llvm::APSInt &Oversized) {
5858   QualType FixedTy
5859     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5860                                           SizeIsNegative, Oversized);
5861   if (FixedTy.isNull())
5862     return nullptr;
5863   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5864   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5865                                     FixedTInfo->getTypeLoc());
5866   return FixedTInfo;
5867 }
5868 
5869 /// Register the given locally-scoped extern "C" declaration so
5870 /// that it can be found later for redeclarations. We include any extern "C"
5871 /// declaration that is not visible in the translation unit here, not just
5872 /// function-scope declarations.
5873 void
5874 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5875   if (!getLangOpts().CPlusPlus &&
5876       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5877     // Don't need to track declarations in the TU in C.
5878     return;
5879 
5880   // Note that we have a locally-scoped external with this name.
5881   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5882 }
5883 
5884 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5885   // FIXME: We can have multiple results via __attribute__((overloadable)).
5886   auto Result = Context.getExternCContextDecl()->lookup(Name);
5887   return Result.empty() ? nullptr : *Result.begin();
5888 }
5889 
5890 /// Diagnose function specifiers on a declaration of an identifier that
5891 /// does not identify a function.
5892 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5893   // FIXME: We should probably indicate the identifier in question to avoid
5894   // confusion for constructs like "virtual int a(), b;"
5895   if (DS.isVirtualSpecified())
5896     Diag(DS.getVirtualSpecLoc(),
5897          diag::err_virtual_non_function);
5898 
5899   if (DS.hasExplicitSpecifier())
5900     Diag(DS.getExplicitSpecLoc(),
5901          diag::err_explicit_non_function);
5902 
5903   if (DS.isNoreturnSpecified())
5904     Diag(DS.getNoreturnSpecLoc(),
5905          diag::err_noreturn_non_function);
5906 }
5907 
5908 NamedDecl*
5909 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5910                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5911   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5912   if (D.getCXXScopeSpec().isSet()) {
5913     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5914       << D.getCXXScopeSpec().getRange();
5915     D.setInvalidType();
5916     // Pretend we didn't see the scope specifier.
5917     DC = CurContext;
5918     Previous.clear();
5919   }
5920 
5921   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5922 
5923   if (D.getDeclSpec().isInlineSpecified())
5924     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5925         << getLangOpts().CPlusPlus17;
5926   if (D.getDeclSpec().hasConstexprSpecifier())
5927     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5928         << 1 << D.getDeclSpec().getConstexprSpecifier();
5929 
5930   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5931     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5932       Diag(D.getName().StartLocation,
5933            diag::err_deduction_guide_invalid_specifier)
5934           << "typedef";
5935     else
5936       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5937           << D.getName().getSourceRange();
5938     return nullptr;
5939   }
5940 
5941   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5942   if (!NewTD) return nullptr;
5943 
5944   // Handle attributes prior to checking for duplicates in MergeVarDecl
5945   ProcessDeclAttributes(S, NewTD, D);
5946 
5947   CheckTypedefForVariablyModifiedType(S, NewTD);
5948 
5949   bool Redeclaration = D.isRedeclaration();
5950   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5951   D.setRedeclaration(Redeclaration);
5952   return ND;
5953 }
5954 
5955 void
5956 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5957   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5958   // then it shall have block scope.
5959   // Note that variably modified types must be fixed before merging the decl so
5960   // that redeclarations will match.
5961   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5962   QualType T = TInfo->getType();
5963   if (T->isVariablyModifiedType()) {
5964     setFunctionHasBranchProtectedScope();
5965 
5966     if (S->getFnParent() == nullptr) {
5967       bool SizeIsNegative;
5968       llvm::APSInt Oversized;
5969       TypeSourceInfo *FixedTInfo =
5970         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5971                                                       SizeIsNegative,
5972                                                       Oversized);
5973       if (FixedTInfo) {
5974         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5975         NewTD->setTypeSourceInfo(FixedTInfo);
5976       } else {
5977         if (SizeIsNegative)
5978           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5979         else if (T->isVariableArrayType())
5980           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5981         else if (Oversized.getBoolValue())
5982           Diag(NewTD->getLocation(), diag::err_array_too_large)
5983             << Oversized.toString(10);
5984         else
5985           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5986         NewTD->setInvalidDecl();
5987       }
5988     }
5989   }
5990 }
5991 
5992 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5993 /// declares a typedef-name, either using the 'typedef' type specifier or via
5994 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5995 NamedDecl*
5996 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5997                            LookupResult &Previous, bool &Redeclaration) {
5998 
5999   // Find the shadowed declaration before filtering for scope.
6000   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6001 
6002   // Merge the decl with the existing one if appropriate. If the decl is
6003   // in an outer scope, it isn't the same thing.
6004   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6005                        /*AllowInlineNamespace*/false);
6006   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6007   if (!Previous.empty()) {
6008     Redeclaration = true;
6009     MergeTypedefNameDecl(S, NewTD, Previous);
6010   } else {
6011     inferGslPointerAttribute(NewTD);
6012   }
6013 
6014   if (ShadowedDecl && !Redeclaration)
6015     CheckShadow(NewTD, ShadowedDecl, Previous);
6016 
6017   // If this is the C FILE type, notify the AST context.
6018   if (IdentifierInfo *II = NewTD->getIdentifier())
6019     if (!NewTD->isInvalidDecl() &&
6020         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6021       if (II->isStr("FILE"))
6022         Context.setFILEDecl(NewTD);
6023       else if (II->isStr("jmp_buf"))
6024         Context.setjmp_bufDecl(NewTD);
6025       else if (II->isStr("sigjmp_buf"))
6026         Context.setsigjmp_bufDecl(NewTD);
6027       else if (II->isStr("ucontext_t"))
6028         Context.setucontext_tDecl(NewTD);
6029     }
6030 
6031   return NewTD;
6032 }
6033 
6034 /// Determines whether the given declaration is an out-of-scope
6035 /// previous declaration.
6036 ///
6037 /// This routine should be invoked when name lookup has found a
6038 /// previous declaration (PrevDecl) that is not in the scope where a
6039 /// new declaration by the same name is being introduced. If the new
6040 /// declaration occurs in a local scope, previous declarations with
6041 /// linkage may still be considered previous declarations (C99
6042 /// 6.2.2p4-5, C++ [basic.link]p6).
6043 ///
6044 /// \param PrevDecl the previous declaration found by name
6045 /// lookup
6046 ///
6047 /// \param DC the context in which the new declaration is being
6048 /// declared.
6049 ///
6050 /// \returns true if PrevDecl is an out-of-scope previous declaration
6051 /// for a new delcaration with the same name.
6052 static bool
6053 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6054                                 ASTContext &Context) {
6055   if (!PrevDecl)
6056     return false;
6057 
6058   if (!PrevDecl->hasLinkage())
6059     return false;
6060 
6061   if (Context.getLangOpts().CPlusPlus) {
6062     // C++ [basic.link]p6:
6063     //   If there is a visible declaration of an entity with linkage
6064     //   having the same name and type, ignoring entities declared
6065     //   outside the innermost enclosing namespace scope, the block
6066     //   scope declaration declares that same entity and receives the
6067     //   linkage of the previous declaration.
6068     DeclContext *OuterContext = DC->getRedeclContext();
6069     if (!OuterContext->isFunctionOrMethod())
6070       // This rule only applies to block-scope declarations.
6071       return false;
6072 
6073     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6074     if (PrevOuterContext->isRecord())
6075       // We found a member function: ignore it.
6076       return false;
6077 
6078     // Find the innermost enclosing namespace for the new and
6079     // previous declarations.
6080     OuterContext = OuterContext->getEnclosingNamespaceContext();
6081     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6082 
6083     // The previous declaration is in a different namespace, so it
6084     // isn't the same function.
6085     if (!OuterContext->Equals(PrevOuterContext))
6086       return false;
6087   }
6088 
6089   return true;
6090 }
6091 
6092 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6093   CXXScopeSpec &SS = D.getCXXScopeSpec();
6094   if (!SS.isSet()) return;
6095   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6096 }
6097 
6098 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6099   QualType type = decl->getType();
6100   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6101   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6102     // Various kinds of declaration aren't allowed to be __autoreleasing.
6103     unsigned kind = -1U;
6104     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6105       if (var->hasAttr<BlocksAttr>())
6106         kind = 0; // __block
6107       else if (!var->hasLocalStorage())
6108         kind = 1; // global
6109     } else if (isa<ObjCIvarDecl>(decl)) {
6110       kind = 3; // ivar
6111     } else if (isa<FieldDecl>(decl)) {
6112       kind = 2; // field
6113     }
6114 
6115     if (kind != -1U) {
6116       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6117         << kind;
6118     }
6119   } else if (lifetime == Qualifiers::OCL_None) {
6120     // Try to infer lifetime.
6121     if (!type->isObjCLifetimeType())
6122       return false;
6123 
6124     lifetime = type->getObjCARCImplicitLifetime();
6125     type = Context.getLifetimeQualifiedType(type, lifetime);
6126     decl->setType(type);
6127   }
6128 
6129   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6130     // Thread-local variables cannot have lifetime.
6131     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6132         var->getTLSKind()) {
6133       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6134         << var->getType();
6135       return true;
6136     }
6137   }
6138 
6139   return false;
6140 }
6141 
6142 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6143   if (Decl->getType().hasAddressSpace())
6144     return;
6145   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6146     QualType Type = Var->getType();
6147     if (Type->isSamplerT() || Type->isVoidType())
6148       return;
6149     LangAS ImplAS = LangAS::opencl_private;
6150     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6151         Var->hasGlobalStorage())
6152       ImplAS = LangAS::opencl_global;
6153     // If the original type from a decayed type is an array type and that array
6154     // type has no address space yet, deduce it now.
6155     if (auto DT = dyn_cast<DecayedType>(Type)) {
6156       auto OrigTy = DT->getOriginalType();
6157       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6158         // Add the address space to the original array type and then propagate
6159         // that to the element type through `getAsArrayType`.
6160         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6161         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6162         // Re-generate the decayed type.
6163         Type = Context.getDecayedType(OrigTy);
6164       }
6165     }
6166     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6167     // Apply any qualifiers (including address space) from the array type to
6168     // the element type. This implements C99 6.7.3p8: "If the specification of
6169     // an array type includes any type qualifiers, the element type is so
6170     // qualified, not the array type."
6171     if (Type->isArrayType())
6172       Type = QualType(Context.getAsArrayType(Type), 0);
6173     Decl->setType(Type);
6174   }
6175 }
6176 
6177 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6178   // Ensure that an auto decl is deduced otherwise the checks below might cache
6179   // the wrong linkage.
6180   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6181 
6182   // 'weak' only applies to declarations with external linkage.
6183   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6184     if (!ND.isExternallyVisible()) {
6185       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6186       ND.dropAttr<WeakAttr>();
6187     }
6188   }
6189   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6190     if (ND.isExternallyVisible()) {
6191       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6192       ND.dropAttr<WeakRefAttr>();
6193       ND.dropAttr<AliasAttr>();
6194     }
6195   }
6196 
6197   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6198     if (VD->hasInit()) {
6199       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6200         assert(VD->isThisDeclarationADefinition() &&
6201                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6202         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6203         VD->dropAttr<AliasAttr>();
6204       }
6205     }
6206   }
6207 
6208   // 'selectany' only applies to externally visible variable declarations.
6209   // It does not apply to functions.
6210   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6211     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6212       S.Diag(Attr->getLocation(),
6213              diag::err_attribute_selectany_non_extern_data);
6214       ND.dropAttr<SelectAnyAttr>();
6215     }
6216   }
6217 
6218   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6219     auto *VD = dyn_cast<VarDecl>(&ND);
6220     bool IsAnonymousNS = false;
6221     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6222     if (VD) {
6223       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6224       while (NS && !IsAnonymousNS) {
6225         IsAnonymousNS = NS->isAnonymousNamespace();
6226         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6227       }
6228     }
6229     // dll attributes require external linkage. Static locals may have external
6230     // linkage but still cannot be explicitly imported or exported.
6231     // In Microsoft mode, a variable defined in anonymous namespace must have
6232     // external linkage in order to be exported.
6233     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6234     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6235         (!AnonNSInMicrosoftMode &&
6236          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6237       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6238         << &ND << Attr;
6239       ND.setInvalidDecl();
6240     }
6241   }
6242 
6243   // Virtual functions cannot be marked as 'notail'.
6244   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6245     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6246       if (MD->isVirtual()) {
6247         S.Diag(ND.getLocation(),
6248                diag::err_invalid_attribute_on_virtual_function)
6249             << Attr;
6250         ND.dropAttr<NotTailCalledAttr>();
6251       }
6252 
6253   // Check the attributes on the function type, if any.
6254   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6255     // Don't declare this variable in the second operand of the for-statement;
6256     // GCC miscompiles that by ending its lifetime before evaluating the
6257     // third operand. See gcc.gnu.org/PR86769.
6258     AttributedTypeLoc ATL;
6259     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6260          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6261          TL = ATL.getModifiedLoc()) {
6262       // The [[lifetimebound]] attribute can be applied to the implicit object
6263       // parameter of a non-static member function (other than a ctor or dtor)
6264       // by applying it to the function type.
6265       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6266         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6267         if (!MD || MD->isStatic()) {
6268           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6269               << !MD << A->getRange();
6270         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6271           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6272               << isa<CXXDestructorDecl>(MD) << A->getRange();
6273         }
6274       }
6275     }
6276   }
6277 }
6278 
6279 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6280                                            NamedDecl *NewDecl,
6281                                            bool IsSpecialization,
6282                                            bool IsDefinition) {
6283   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6284     return;
6285 
6286   bool IsTemplate = false;
6287   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6288     OldDecl = OldTD->getTemplatedDecl();
6289     IsTemplate = true;
6290     if (!IsSpecialization)
6291       IsDefinition = false;
6292   }
6293   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6294     NewDecl = NewTD->getTemplatedDecl();
6295     IsTemplate = true;
6296   }
6297 
6298   if (!OldDecl || !NewDecl)
6299     return;
6300 
6301   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6302   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6303   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6304   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6305 
6306   // dllimport and dllexport are inheritable attributes so we have to exclude
6307   // inherited attribute instances.
6308   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6309                     (NewExportAttr && !NewExportAttr->isInherited());
6310 
6311   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6312   // the only exception being explicit specializations.
6313   // Implicitly generated declarations are also excluded for now because there
6314   // is no other way to switch these to use dllimport or dllexport.
6315   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6316 
6317   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6318     // Allow with a warning for free functions and global variables.
6319     bool JustWarn = false;
6320     if (!OldDecl->isCXXClassMember()) {
6321       auto *VD = dyn_cast<VarDecl>(OldDecl);
6322       if (VD && !VD->getDescribedVarTemplate())
6323         JustWarn = true;
6324       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6325       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6326         JustWarn = true;
6327     }
6328 
6329     // We cannot change a declaration that's been used because IR has already
6330     // been emitted. Dllimported functions will still work though (modulo
6331     // address equality) as they can use the thunk.
6332     if (OldDecl->isUsed())
6333       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6334         JustWarn = false;
6335 
6336     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6337                                : diag::err_attribute_dll_redeclaration;
6338     S.Diag(NewDecl->getLocation(), DiagID)
6339         << NewDecl
6340         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6341     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6342     if (!JustWarn) {
6343       NewDecl->setInvalidDecl();
6344       return;
6345     }
6346   }
6347 
6348   // A redeclaration is not allowed to drop a dllimport attribute, the only
6349   // exceptions being inline function definitions (except for function
6350   // templates), local extern declarations, qualified friend declarations or
6351   // special MSVC extension: in the last case, the declaration is treated as if
6352   // it were marked dllexport.
6353   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6354   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6355   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6356     // Ignore static data because out-of-line definitions are diagnosed
6357     // separately.
6358     IsStaticDataMember = VD->isStaticDataMember();
6359     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6360                    VarDecl::DeclarationOnly;
6361   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6362     IsInline = FD->isInlined();
6363     IsQualifiedFriend = FD->getQualifier() &&
6364                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6365   }
6366 
6367   if (OldImportAttr && !HasNewAttr &&
6368       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6369       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6370     if (IsMicrosoft && IsDefinition) {
6371       S.Diag(NewDecl->getLocation(),
6372              diag::warn_redeclaration_without_import_attribute)
6373           << NewDecl;
6374       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6375       NewDecl->dropAttr<DLLImportAttr>();
6376       NewDecl->addAttr(
6377           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6378     } else {
6379       S.Diag(NewDecl->getLocation(),
6380              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6381           << NewDecl << OldImportAttr;
6382       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6383       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6384       OldDecl->dropAttr<DLLImportAttr>();
6385       NewDecl->dropAttr<DLLImportAttr>();
6386     }
6387   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6388     // In MinGW, seeing a function declared inline drops the dllimport
6389     // attribute.
6390     OldDecl->dropAttr<DLLImportAttr>();
6391     NewDecl->dropAttr<DLLImportAttr>();
6392     S.Diag(NewDecl->getLocation(),
6393            diag::warn_dllimport_dropped_from_inline_function)
6394         << NewDecl << OldImportAttr;
6395   }
6396 
6397   // A specialization of a class template member function is processed here
6398   // since it's a redeclaration. If the parent class is dllexport, the
6399   // specialization inherits that attribute. This doesn't happen automatically
6400   // since the parent class isn't instantiated until later.
6401   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6402     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6403         !NewImportAttr && !NewExportAttr) {
6404       if (const DLLExportAttr *ParentExportAttr =
6405               MD->getParent()->getAttr<DLLExportAttr>()) {
6406         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6407         NewAttr->setInherited(true);
6408         NewDecl->addAttr(NewAttr);
6409       }
6410     }
6411   }
6412 }
6413 
6414 /// Given that we are within the definition of the given function,
6415 /// will that definition behave like C99's 'inline', where the
6416 /// definition is discarded except for optimization purposes?
6417 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6418   // Try to avoid calling GetGVALinkageForFunction.
6419 
6420   // All cases of this require the 'inline' keyword.
6421   if (!FD->isInlined()) return false;
6422 
6423   // This is only possible in C++ with the gnu_inline attribute.
6424   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6425     return false;
6426 
6427   // Okay, go ahead and call the relatively-more-expensive function.
6428   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6429 }
6430 
6431 /// Determine whether a variable is extern "C" prior to attaching
6432 /// an initializer. We can't just call isExternC() here, because that
6433 /// will also compute and cache whether the declaration is externally
6434 /// visible, which might change when we attach the initializer.
6435 ///
6436 /// This can only be used if the declaration is known to not be a
6437 /// redeclaration of an internal linkage declaration.
6438 ///
6439 /// For instance:
6440 ///
6441 ///   auto x = []{};
6442 ///
6443 /// Attaching the initializer here makes this declaration not externally
6444 /// visible, because its type has internal linkage.
6445 ///
6446 /// FIXME: This is a hack.
6447 template<typename T>
6448 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6449   if (S.getLangOpts().CPlusPlus) {
6450     // In C++, the overloadable attribute negates the effects of extern "C".
6451     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6452       return false;
6453 
6454     // So do CUDA's host/device attributes.
6455     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6456                                  D->template hasAttr<CUDAHostAttr>()))
6457       return false;
6458   }
6459   return D->isExternC();
6460 }
6461 
6462 static bool shouldConsiderLinkage(const VarDecl *VD) {
6463   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6464   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6465       isa<OMPDeclareMapperDecl>(DC))
6466     return VD->hasExternalStorage();
6467   if (DC->isFileContext())
6468     return true;
6469   if (DC->isRecord())
6470     return false;
6471   if (isa<RequiresExprBodyDecl>(DC))
6472     return false;
6473   llvm_unreachable("Unexpected context");
6474 }
6475 
6476 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6477   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6478   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6479       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6480     return true;
6481   if (DC->isRecord())
6482     return false;
6483   llvm_unreachable("Unexpected context");
6484 }
6485 
6486 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6487                           ParsedAttr::Kind Kind) {
6488   // Check decl attributes on the DeclSpec.
6489   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6490     return true;
6491 
6492   // Walk the declarator structure, checking decl attributes that were in a type
6493   // position to the decl itself.
6494   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6495     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6496       return true;
6497   }
6498 
6499   // Finally, check attributes on the decl itself.
6500   return PD.getAttributes().hasAttribute(Kind);
6501 }
6502 
6503 /// Adjust the \c DeclContext for a function or variable that might be a
6504 /// function-local external declaration.
6505 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6506   if (!DC->isFunctionOrMethod())
6507     return false;
6508 
6509   // If this is a local extern function or variable declared within a function
6510   // template, don't add it into the enclosing namespace scope until it is
6511   // instantiated; it might have a dependent type right now.
6512   if (DC->isDependentContext())
6513     return true;
6514 
6515   // C++11 [basic.link]p7:
6516   //   When a block scope declaration of an entity with linkage is not found to
6517   //   refer to some other declaration, then that entity is a member of the
6518   //   innermost enclosing namespace.
6519   //
6520   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6521   // semantically-enclosing namespace, not a lexically-enclosing one.
6522   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6523     DC = DC->getParent();
6524   return true;
6525 }
6526 
6527 /// Returns true if given declaration has external C language linkage.
6528 static bool isDeclExternC(const Decl *D) {
6529   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6530     return FD->isExternC();
6531   if (const auto *VD = dyn_cast<VarDecl>(D))
6532     return VD->isExternC();
6533 
6534   llvm_unreachable("Unknown type of decl!");
6535 }
6536 /// Returns true if there hasn't been any invalid type diagnosed.
6537 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6538                                 DeclContext *DC, QualType R) {
6539   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6540   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6541   // argument.
6542   if (R->isImageType() || R->isPipeType()) {
6543     Se.Diag(D.getIdentifierLoc(),
6544             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6545         << R;
6546     D.setInvalidType();
6547     return false;
6548   }
6549 
6550   // OpenCL v1.2 s6.9.r:
6551   // The event type cannot be used to declare a program scope variable.
6552   // OpenCL v2.0 s6.9.q:
6553   // The clk_event_t and reserve_id_t types cannot be declared in program
6554   // scope.
6555   if (NULL == S->getParent()) {
6556     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6557       Se.Diag(D.getIdentifierLoc(),
6558               diag::err_invalid_type_for_program_scope_var)
6559           << R;
6560       D.setInvalidType();
6561       return false;
6562     }
6563   }
6564 
6565   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6566   QualType NR = R;
6567   while (NR->isPointerType()) {
6568     if (NR->isFunctionPointerType()) {
6569       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6570       D.setInvalidType();
6571       return false;
6572     }
6573     NR = NR->getPointeeType();
6574   }
6575 
6576   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6577     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6578     // half array type (unless the cl_khr_fp16 extension is enabled).
6579     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6580       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6581       D.setInvalidType();
6582       return false;
6583     }
6584   }
6585 
6586   // OpenCL v1.2 s6.9.r:
6587   // The event type cannot be used with the __local, __constant and __global
6588   // address space qualifiers.
6589   if (R->isEventT()) {
6590     if (R.getAddressSpace() != LangAS::opencl_private) {
6591       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6592       D.setInvalidType();
6593       return false;
6594     }
6595   }
6596 
6597   // C++ for OpenCL does not allow the thread_local storage qualifier.
6598   // OpenCL C does not support thread_local either, and
6599   // also reject all other thread storage class specifiers.
6600   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6601   if (TSC != TSCS_unspecified) {
6602     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6603     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6604             diag::err_opencl_unknown_type_specifier)
6605         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6606         << DeclSpec::getSpecifierName(TSC) << 1;
6607     D.setInvalidType();
6608     return false;
6609   }
6610 
6611   if (R->isSamplerT()) {
6612     // OpenCL v1.2 s6.9.b p4:
6613     // The sampler type cannot be used with the __local and __global address
6614     // space qualifiers.
6615     if (R.getAddressSpace() == LangAS::opencl_local ||
6616         R.getAddressSpace() == LangAS::opencl_global) {
6617       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6618       D.setInvalidType();
6619     }
6620 
6621     // OpenCL v1.2 s6.12.14.1:
6622     // A global sampler must be declared with either the constant address
6623     // space qualifier or with the const qualifier.
6624     if (DC->isTranslationUnit() &&
6625         !(R.getAddressSpace() == LangAS::opencl_constant ||
6626           R.isConstQualified())) {
6627       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6628       D.setInvalidType();
6629     }
6630     if (D.isInvalidType())
6631       return false;
6632   }
6633   return true;
6634 }
6635 
6636 NamedDecl *Sema::ActOnVariableDeclarator(
6637     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6638     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6639     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6640   QualType R = TInfo->getType();
6641   DeclarationName Name = GetNameForDeclarator(D).getName();
6642 
6643   IdentifierInfo *II = Name.getAsIdentifierInfo();
6644 
6645   if (D.isDecompositionDeclarator()) {
6646     // Take the name of the first declarator as our name for diagnostic
6647     // purposes.
6648     auto &Decomp = D.getDecompositionDeclarator();
6649     if (!Decomp.bindings().empty()) {
6650       II = Decomp.bindings()[0].Name;
6651       Name = II;
6652     }
6653   } else if (!II) {
6654     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6655     return nullptr;
6656   }
6657 
6658 
6659   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6660   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6661 
6662   // dllimport globals without explicit storage class are treated as extern. We
6663   // have to change the storage class this early to get the right DeclContext.
6664   if (SC == SC_None && !DC->isRecord() &&
6665       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6666       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6667     SC = SC_Extern;
6668 
6669   DeclContext *OriginalDC = DC;
6670   bool IsLocalExternDecl = SC == SC_Extern &&
6671                            adjustContextForLocalExternDecl(DC);
6672 
6673   if (SCSpec == DeclSpec::SCS_mutable) {
6674     // mutable can only appear on non-static class members, so it's always
6675     // an error here
6676     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6677     D.setInvalidType();
6678     SC = SC_None;
6679   }
6680 
6681   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6682       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6683                               D.getDeclSpec().getStorageClassSpecLoc())) {
6684     // In C++11, the 'register' storage class specifier is deprecated.
6685     // Suppress the warning in system macros, it's used in macros in some
6686     // popular C system headers, such as in glibc's htonl() macro.
6687     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6688          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6689                                    : diag::warn_deprecated_register)
6690       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6691   }
6692 
6693   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6694 
6695   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6696     // C99 6.9p2: The storage-class specifiers auto and register shall not
6697     // appear in the declaration specifiers in an external declaration.
6698     // Global Register+Asm is a GNU extension we support.
6699     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6700       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6701       D.setInvalidType();
6702     }
6703   }
6704 
6705   bool IsMemberSpecialization = false;
6706   bool IsVariableTemplateSpecialization = false;
6707   bool IsPartialSpecialization = false;
6708   bool IsVariableTemplate = false;
6709   VarDecl *NewVD = nullptr;
6710   VarTemplateDecl *NewTemplate = nullptr;
6711   TemplateParameterList *TemplateParams = nullptr;
6712   if (!getLangOpts().CPlusPlus) {
6713     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6714                             II, R, TInfo, SC);
6715 
6716     if (R->getContainedDeducedType())
6717       ParsingInitForAutoVars.insert(NewVD);
6718 
6719     if (D.isInvalidType())
6720       NewVD->setInvalidDecl();
6721 
6722     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6723         NewVD->hasLocalStorage())
6724       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6725                             NTCUC_AutoVar, NTCUK_Destruct);
6726   } else {
6727     bool Invalid = false;
6728 
6729     if (DC->isRecord() && !CurContext->isRecord()) {
6730       // This is an out-of-line definition of a static data member.
6731       switch (SC) {
6732       case SC_None:
6733         break;
6734       case SC_Static:
6735         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6736              diag::err_static_out_of_line)
6737           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6738         break;
6739       case SC_Auto:
6740       case SC_Register:
6741       case SC_Extern:
6742         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6743         // to names of variables declared in a block or to function parameters.
6744         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6745         // of class members
6746 
6747         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6748              diag::err_storage_class_for_static_member)
6749           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6750         break;
6751       case SC_PrivateExtern:
6752         llvm_unreachable("C storage class in c++!");
6753       }
6754     }
6755 
6756     if (SC == SC_Static && CurContext->isRecord()) {
6757       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6758         if (RD->isLocalClass())
6759           Diag(D.getIdentifierLoc(),
6760                diag::err_static_data_member_not_allowed_in_local_class)
6761             << Name << RD->getDeclName();
6762 
6763         // C++98 [class.union]p1: If a union contains a static data member,
6764         // the program is ill-formed. C++11 drops this restriction.
6765         if (RD->isUnion())
6766           Diag(D.getIdentifierLoc(),
6767                getLangOpts().CPlusPlus11
6768                  ? diag::warn_cxx98_compat_static_data_member_in_union
6769                  : diag::ext_static_data_member_in_union) << Name;
6770         // We conservatively disallow static data members in anonymous structs.
6771         else if (!RD->getDeclName())
6772           Diag(D.getIdentifierLoc(),
6773                diag::err_static_data_member_not_allowed_in_anon_struct)
6774             << Name << RD->isUnion();
6775       }
6776     }
6777 
6778     // Match up the template parameter lists with the scope specifier, then
6779     // determine whether we have a template or a template specialization.
6780     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6781         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6782         D.getCXXScopeSpec(),
6783         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6784             ? D.getName().TemplateId
6785             : nullptr,
6786         TemplateParamLists,
6787         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6788 
6789     if (TemplateParams) {
6790       if (!TemplateParams->size() &&
6791           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6792         // There is an extraneous 'template<>' for this variable. Complain
6793         // about it, but allow the declaration of the variable.
6794         Diag(TemplateParams->getTemplateLoc(),
6795              diag::err_template_variable_noparams)
6796           << II
6797           << SourceRange(TemplateParams->getTemplateLoc(),
6798                          TemplateParams->getRAngleLoc());
6799         TemplateParams = nullptr;
6800       } else {
6801         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6802           // This is an explicit specialization or a partial specialization.
6803           // FIXME: Check that we can declare a specialization here.
6804           IsVariableTemplateSpecialization = true;
6805           IsPartialSpecialization = TemplateParams->size() > 0;
6806         } else { // if (TemplateParams->size() > 0)
6807           // This is a template declaration.
6808           IsVariableTemplate = true;
6809 
6810           // Check that we can declare a template here.
6811           if (CheckTemplateDeclScope(S, TemplateParams))
6812             return nullptr;
6813 
6814           // Only C++1y supports variable templates (N3651).
6815           Diag(D.getIdentifierLoc(),
6816                getLangOpts().CPlusPlus14
6817                    ? diag::warn_cxx11_compat_variable_template
6818                    : diag::ext_variable_template);
6819         }
6820       }
6821     } else {
6822       assert((Invalid ||
6823               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6824              "should have a 'template<>' for this decl");
6825     }
6826 
6827     if (IsVariableTemplateSpecialization) {
6828       SourceLocation TemplateKWLoc =
6829           TemplateParamLists.size() > 0
6830               ? TemplateParamLists[0]->getTemplateLoc()
6831               : SourceLocation();
6832       DeclResult Res = ActOnVarTemplateSpecialization(
6833           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6834           IsPartialSpecialization);
6835       if (Res.isInvalid())
6836         return nullptr;
6837       NewVD = cast<VarDecl>(Res.get());
6838       AddToScope = false;
6839     } else if (D.isDecompositionDeclarator()) {
6840       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6841                                         D.getIdentifierLoc(), R, TInfo, SC,
6842                                         Bindings);
6843     } else
6844       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6845                               D.getIdentifierLoc(), II, R, TInfo, SC);
6846 
6847     // If this is supposed to be a variable template, create it as such.
6848     if (IsVariableTemplate) {
6849       NewTemplate =
6850           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6851                                   TemplateParams, NewVD);
6852       NewVD->setDescribedVarTemplate(NewTemplate);
6853     }
6854 
6855     // If this decl has an auto type in need of deduction, make a note of the
6856     // Decl so we can diagnose uses of it in its own initializer.
6857     if (R->getContainedDeducedType())
6858       ParsingInitForAutoVars.insert(NewVD);
6859 
6860     if (D.isInvalidType() || Invalid) {
6861       NewVD->setInvalidDecl();
6862       if (NewTemplate)
6863         NewTemplate->setInvalidDecl();
6864     }
6865 
6866     SetNestedNameSpecifier(*this, NewVD, D);
6867 
6868     // If we have any template parameter lists that don't directly belong to
6869     // the variable (matching the scope specifier), store them.
6870     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6871     if (TemplateParamLists.size() > VDTemplateParamLists)
6872       NewVD->setTemplateParameterListsInfo(
6873           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6874   }
6875 
6876   if (D.getDeclSpec().isInlineSpecified()) {
6877     if (!getLangOpts().CPlusPlus) {
6878       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6879           << 0;
6880     } else if (CurContext->isFunctionOrMethod()) {
6881       // 'inline' is not allowed on block scope variable declaration.
6882       Diag(D.getDeclSpec().getInlineSpecLoc(),
6883            diag::err_inline_declaration_block_scope) << Name
6884         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6885     } else {
6886       Diag(D.getDeclSpec().getInlineSpecLoc(),
6887            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6888                                      : diag::ext_inline_variable);
6889       NewVD->setInlineSpecified();
6890     }
6891   }
6892 
6893   // Set the lexical context. If the declarator has a C++ scope specifier, the
6894   // lexical context will be different from the semantic context.
6895   NewVD->setLexicalDeclContext(CurContext);
6896   if (NewTemplate)
6897     NewTemplate->setLexicalDeclContext(CurContext);
6898 
6899   if (IsLocalExternDecl) {
6900     if (D.isDecompositionDeclarator())
6901       for (auto *B : Bindings)
6902         B->setLocalExternDecl();
6903     else
6904       NewVD->setLocalExternDecl();
6905   }
6906 
6907   bool EmitTLSUnsupportedError = false;
6908   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6909     // C++11 [dcl.stc]p4:
6910     //   When thread_local is applied to a variable of block scope the
6911     //   storage-class-specifier static is implied if it does not appear
6912     //   explicitly.
6913     // Core issue: 'static' is not implied if the variable is declared
6914     //   'extern'.
6915     if (NewVD->hasLocalStorage() &&
6916         (SCSpec != DeclSpec::SCS_unspecified ||
6917          TSCS != DeclSpec::TSCS_thread_local ||
6918          !DC->isFunctionOrMethod()))
6919       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6920            diag::err_thread_non_global)
6921         << DeclSpec::getSpecifierName(TSCS);
6922     else if (!Context.getTargetInfo().isTLSSupported()) {
6923       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6924         // Postpone error emission until we've collected attributes required to
6925         // figure out whether it's a host or device variable and whether the
6926         // error should be ignored.
6927         EmitTLSUnsupportedError = true;
6928         // We still need to mark the variable as TLS so it shows up in AST with
6929         // proper storage class for other tools to use even if we're not going
6930         // to emit any code for it.
6931         NewVD->setTSCSpec(TSCS);
6932       } else
6933         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6934              diag::err_thread_unsupported);
6935     } else
6936       NewVD->setTSCSpec(TSCS);
6937   }
6938 
6939   switch (D.getDeclSpec().getConstexprSpecifier()) {
6940   case CSK_unspecified:
6941     break;
6942 
6943   case CSK_consteval:
6944     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6945         diag::err_constexpr_wrong_decl_kind)
6946       << D.getDeclSpec().getConstexprSpecifier();
6947     LLVM_FALLTHROUGH;
6948 
6949   case CSK_constexpr:
6950     NewVD->setConstexpr(true);
6951     // C++1z [dcl.spec.constexpr]p1:
6952     //   A static data member declared with the constexpr specifier is
6953     //   implicitly an inline variable.
6954     if (NewVD->isStaticDataMember() &&
6955         (getLangOpts().CPlusPlus17 ||
6956          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6957       NewVD->setImplicitlyInline();
6958     break;
6959 
6960   case CSK_constinit:
6961     if (!NewVD->hasGlobalStorage())
6962       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6963            diag::err_constinit_local_variable);
6964     else
6965       NewVD->addAttr(ConstInitAttr::Create(
6966           Context, D.getDeclSpec().getConstexprSpecLoc(),
6967           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6968     break;
6969   }
6970 
6971   // C99 6.7.4p3
6972   //   An inline definition of a function with external linkage shall
6973   //   not contain a definition of a modifiable object with static or
6974   //   thread storage duration...
6975   // We only apply this when the function is required to be defined
6976   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6977   // that a local variable with thread storage duration still has to
6978   // be marked 'static'.  Also note that it's possible to get these
6979   // semantics in C++ using __attribute__((gnu_inline)).
6980   if (SC == SC_Static && S->getFnParent() != nullptr &&
6981       !NewVD->getType().isConstQualified()) {
6982     FunctionDecl *CurFD = getCurFunctionDecl();
6983     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6984       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6985            diag::warn_static_local_in_extern_inline);
6986       MaybeSuggestAddingStaticToDecl(CurFD);
6987     }
6988   }
6989 
6990   if (D.getDeclSpec().isModulePrivateSpecified()) {
6991     if (IsVariableTemplateSpecialization)
6992       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6993           << (IsPartialSpecialization ? 1 : 0)
6994           << FixItHint::CreateRemoval(
6995                  D.getDeclSpec().getModulePrivateSpecLoc());
6996     else if (IsMemberSpecialization)
6997       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6998         << 2
6999         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7000     else if (NewVD->hasLocalStorage())
7001       Diag(NewVD->getLocation(), diag::err_module_private_local)
7002         << 0 << NewVD->getDeclName()
7003         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7004         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7005     else {
7006       NewVD->setModulePrivate();
7007       if (NewTemplate)
7008         NewTemplate->setModulePrivate();
7009       for (auto *B : Bindings)
7010         B->setModulePrivate();
7011     }
7012   }
7013 
7014   if (getLangOpts().OpenCL) {
7015 
7016     deduceOpenCLAddressSpace(NewVD);
7017 
7018     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7019   }
7020 
7021   // Handle attributes prior to checking for duplicates in MergeVarDecl
7022   ProcessDeclAttributes(S, NewVD, D);
7023 
7024   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7025     if (EmitTLSUnsupportedError &&
7026         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7027          (getLangOpts().OpenMPIsDevice &&
7028           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7029       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7030            diag::err_thread_unsupported);
7031     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7032     // storage [duration]."
7033     if (SC == SC_None && S->getFnParent() != nullptr &&
7034         (NewVD->hasAttr<CUDASharedAttr>() ||
7035          NewVD->hasAttr<CUDAConstantAttr>())) {
7036       NewVD->setStorageClass(SC_Static);
7037     }
7038   }
7039 
7040   // Ensure that dllimport globals without explicit storage class are treated as
7041   // extern. The storage class is set above using parsed attributes. Now we can
7042   // check the VarDecl itself.
7043   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7044          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7045          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7046 
7047   // In auto-retain/release, infer strong retension for variables of
7048   // retainable type.
7049   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7050     NewVD->setInvalidDecl();
7051 
7052   // Handle GNU asm-label extension (encoded as an attribute).
7053   if (Expr *E = (Expr*)D.getAsmLabel()) {
7054     // The parser guarantees this is a string.
7055     StringLiteral *SE = cast<StringLiteral>(E);
7056     StringRef Label = SE->getString();
7057     if (S->getFnParent() != nullptr) {
7058       switch (SC) {
7059       case SC_None:
7060       case SC_Auto:
7061         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7062         break;
7063       case SC_Register:
7064         // Local Named register
7065         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7066             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7067           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7068         break;
7069       case SC_Static:
7070       case SC_Extern:
7071       case SC_PrivateExtern:
7072         break;
7073       }
7074     } else if (SC == SC_Register) {
7075       // Global Named register
7076       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7077         const auto &TI = Context.getTargetInfo();
7078         bool HasSizeMismatch;
7079 
7080         if (!TI.isValidGCCRegisterName(Label))
7081           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7082         else if (!TI.validateGlobalRegisterVariable(Label,
7083                                                     Context.getTypeSize(R),
7084                                                     HasSizeMismatch))
7085           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7086         else if (HasSizeMismatch)
7087           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7088       }
7089 
7090       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7091         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7092         NewVD->setInvalidDecl(true);
7093       }
7094     }
7095 
7096     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7097                                         /*IsLiteralLabel=*/true,
7098                                         SE->getStrTokenLoc(0)));
7099   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7100     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7101       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7102     if (I != ExtnameUndeclaredIdentifiers.end()) {
7103       if (isDeclExternC(NewVD)) {
7104         NewVD->addAttr(I->second);
7105         ExtnameUndeclaredIdentifiers.erase(I);
7106       } else
7107         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7108             << /*Variable*/1 << NewVD;
7109     }
7110   }
7111 
7112   // Find the shadowed declaration before filtering for scope.
7113   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7114                                 ? getShadowedDeclaration(NewVD, Previous)
7115                                 : nullptr;
7116 
7117   // Don't consider existing declarations that are in a different
7118   // scope and are out-of-semantic-context declarations (if the new
7119   // declaration has linkage).
7120   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7121                        D.getCXXScopeSpec().isNotEmpty() ||
7122                        IsMemberSpecialization ||
7123                        IsVariableTemplateSpecialization);
7124 
7125   // Check whether the previous declaration is in the same block scope. This
7126   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7127   if (getLangOpts().CPlusPlus &&
7128       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7129     NewVD->setPreviousDeclInSameBlockScope(
7130         Previous.isSingleResult() && !Previous.isShadowed() &&
7131         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7132 
7133   if (!getLangOpts().CPlusPlus) {
7134     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7135   } else {
7136     // If this is an explicit specialization of a static data member, check it.
7137     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7138         CheckMemberSpecialization(NewVD, Previous))
7139       NewVD->setInvalidDecl();
7140 
7141     // Merge the decl with the existing one if appropriate.
7142     if (!Previous.empty()) {
7143       if (Previous.isSingleResult() &&
7144           isa<FieldDecl>(Previous.getFoundDecl()) &&
7145           D.getCXXScopeSpec().isSet()) {
7146         // The user tried to define a non-static data member
7147         // out-of-line (C++ [dcl.meaning]p1).
7148         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7149           << D.getCXXScopeSpec().getRange();
7150         Previous.clear();
7151         NewVD->setInvalidDecl();
7152       }
7153     } else if (D.getCXXScopeSpec().isSet()) {
7154       // No previous declaration in the qualifying scope.
7155       Diag(D.getIdentifierLoc(), diag::err_no_member)
7156         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7157         << D.getCXXScopeSpec().getRange();
7158       NewVD->setInvalidDecl();
7159     }
7160 
7161     if (!IsVariableTemplateSpecialization)
7162       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7163 
7164     if (NewTemplate) {
7165       VarTemplateDecl *PrevVarTemplate =
7166           NewVD->getPreviousDecl()
7167               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7168               : nullptr;
7169 
7170       // Check the template parameter list of this declaration, possibly
7171       // merging in the template parameter list from the previous variable
7172       // template declaration.
7173       if (CheckTemplateParameterList(
7174               TemplateParams,
7175               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7176                               : nullptr,
7177               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7178                DC->isDependentContext())
7179                   ? TPC_ClassTemplateMember
7180                   : TPC_VarTemplate))
7181         NewVD->setInvalidDecl();
7182 
7183       // If we are providing an explicit specialization of a static variable
7184       // template, make a note of that.
7185       if (PrevVarTemplate &&
7186           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7187         PrevVarTemplate->setMemberSpecialization();
7188     }
7189   }
7190 
7191   // Diagnose shadowed variables iff this isn't a redeclaration.
7192   if (ShadowedDecl && !D.isRedeclaration())
7193     CheckShadow(NewVD, ShadowedDecl, Previous);
7194 
7195   ProcessPragmaWeak(S, NewVD);
7196 
7197   // If this is the first declaration of an extern C variable, update
7198   // the map of such variables.
7199   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7200       isIncompleteDeclExternC(*this, NewVD))
7201     RegisterLocallyScopedExternCDecl(NewVD, S);
7202 
7203   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7204     MangleNumberingContext *MCtx;
7205     Decl *ManglingContextDecl;
7206     std::tie(MCtx, ManglingContextDecl) =
7207         getCurrentMangleNumberContext(NewVD->getDeclContext());
7208     if (MCtx) {
7209       Context.setManglingNumber(
7210           NewVD, MCtx->getManglingNumber(
7211                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7212       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7213     }
7214   }
7215 
7216   // Special handling of variable named 'main'.
7217   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7218       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7219       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7220 
7221     // C++ [basic.start.main]p3
7222     // A program that declares a variable main at global scope is ill-formed.
7223     if (getLangOpts().CPlusPlus)
7224       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7225 
7226     // In C, and external-linkage variable named main results in undefined
7227     // behavior.
7228     else if (NewVD->hasExternalFormalLinkage())
7229       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7230   }
7231 
7232   if (D.isRedeclaration() && !Previous.empty()) {
7233     NamedDecl *Prev = Previous.getRepresentativeDecl();
7234     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7235                                    D.isFunctionDefinition());
7236   }
7237 
7238   if (NewTemplate) {
7239     if (NewVD->isInvalidDecl())
7240       NewTemplate->setInvalidDecl();
7241     ActOnDocumentableDecl(NewTemplate);
7242     return NewTemplate;
7243   }
7244 
7245   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7246     CompleteMemberSpecialization(NewVD, Previous);
7247 
7248   return NewVD;
7249 }
7250 
7251 /// Enum describing the %select options in diag::warn_decl_shadow.
7252 enum ShadowedDeclKind {
7253   SDK_Local,
7254   SDK_Global,
7255   SDK_StaticMember,
7256   SDK_Field,
7257   SDK_Typedef,
7258   SDK_Using
7259 };
7260 
7261 /// Determine what kind of declaration we're shadowing.
7262 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7263                                                 const DeclContext *OldDC) {
7264   if (isa<TypeAliasDecl>(ShadowedDecl))
7265     return SDK_Using;
7266   else if (isa<TypedefDecl>(ShadowedDecl))
7267     return SDK_Typedef;
7268   else if (isa<RecordDecl>(OldDC))
7269     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7270 
7271   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7272 }
7273 
7274 /// Return the location of the capture if the given lambda captures the given
7275 /// variable \p VD, or an invalid source location otherwise.
7276 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7277                                          const VarDecl *VD) {
7278   for (const Capture &Capture : LSI->Captures) {
7279     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7280       return Capture.getLocation();
7281   }
7282   return SourceLocation();
7283 }
7284 
7285 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7286                                      const LookupResult &R) {
7287   // Only diagnose if we're shadowing an unambiguous field or variable.
7288   if (R.getResultKind() != LookupResult::Found)
7289     return false;
7290 
7291   // Return false if warning is ignored.
7292   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7293 }
7294 
7295 /// Return the declaration shadowed by the given variable \p D, or null
7296 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7297 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7298                                         const LookupResult &R) {
7299   if (!shouldWarnIfShadowedDecl(Diags, R))
7300     return nullptr;
7301 
7302   // Don't diagnose declarations at file scope.
7303   if (D->hasGlobalStorage())
7304     return nullptr;
7305 
7306   NamedDecl *ShadowedDecl = R.getFoundDecl();
7307   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7308              ? ShadowedDecl
7309              : nullptr;
7310 }
7311 
7312 /// Return the declaration shadowed by the given typedef \p D, or null
7313 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7314 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7315                                         const LookupResult &R) {
7316   // Don't warn if typedef declaration is part of a class
7317   if (D->getDeclContext()->isRecord())
7318     return nullptr;
7319 
7320   if (!shouldWarnIfShadowedDecl(Diags, R))
7321     return nullptr;
7322 
7323   NamedDecl *ShadowedDecl = R.getFoundDecl();
7324   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7325 }
7326 
7327 /// Diagnose variable or built-in function shadowing.  Implements
7328 /// -Wshadow.
7329 ///
7330 /// This method is called whenever a VarDecl is added to a "useful"
7331 /// scope.
7332 ///
7333 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7334 /// \param R the lookup of the name
7335 ///
7336 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7337                        const LookupResult &R) {
7338   DeclContext *NewDC = D->getDeclContext();
7339 
7340   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7341     // Fields are not shadowed by variables in C++ static methods.
7342     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7343       if (MD->isStatic())
7344         return;
7345 
7346     // Fields shadowed by constructor parameters are a special case. Usually
7347     // the constructor initializes the field with the parameter.
7348     if (isa<CXXConstructorDecl>(NewDC))
7349       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7350         // Remember that this was shadowed so we can either warn about its
7351         // modification or its existence depending on warning settings.
7352         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7353         return;
7354       }
7355   }
7356 
7357   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7358     if (shadowedVar->isExternC()) {
7359       // For shadowing external vars, make sure that we point to the global
7360       // declaration, not a locally scoped extern declaration.
7361       for (auto I : shadowedVar->redecls())
7362         if (I->isFileVarDecl()) {
7363           ShadowedDecl = I;
7364           break;
7365         }
7366     }
7367 
7368   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7369 
7370   unsigned WarningDiag = diag::warn_decl_shadow;
7371   SourceLocation CaptureLoc;
7372   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7373       isa<CXXMethodDecl>(NewDC)) {
7374     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7375       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7376         if (RD->getLambdaCaptureDefault() == LCD_None) {
7377           // Try to avoid warnings for lambdas with an explicit capture list.
7378           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7379           // Warn only when the lambda captures the shadowed decl explicitly.
7380           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7381           if (CaptureLoc.isInvalid())
7382             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7383         } else {
7384           // Remember that this was shadowed so we can avoid the warning if the
7385           // shadowed decl isn't captured and the warning settings allow it.
7386           cast<LambdaScopeInfo>(getCurFunction())
7387               ->ShadowingDecls.push_back(
7388                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7389           return;
7390         }
7391       }
7392 
7393       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7394         // A variable can't shadow a local variable in an enclosing scope, if
7395         // they are separated by a non-capturing declaration context.
7396         for (DeclContext *ParentDC = NewDC;
7397              ParentDC && !ParentDC->Equals(OldDC);
7398              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7399           // Only block literals, captured statements, and lambda expressions
7400           // can capture; other scopes don't.
7401           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7402               !isLambdaCallOperator(ParentDC)) {
7403             return;
7404           }
7405         }
7406       }
7407     }
7408   }
7409 
7410   // Only warn about certain kinds of shadowing for class members.
7411   if (NewDC && NewDC->isRecord()) {
7412     // In particular, don't warn about shadowing non-class members.
7413     if (!OldDC->isRecord())
7414       return;
7415 
7416     // TODO: should we warn about static data members shadowing
7417     // static data members from base classes?
7418 
7419     // TODO: don't diagnose for inaccessible shadowed members.
7420     // This is hard to do perfectly because we might friend the
7421     // shadowing context, but that's just a false negative.
7422   }
7423 
7424 
7425   DeclarationName Name = R.getLookupName();
7426 
7427   // Emit warning and note.
7428   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7429     return;
7430   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7431   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7432   if (!CaptureLoc.isInvalid())
7433     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7434         << Name << /*explicitly*/ 1;
7435   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7436 }
7437 
7438 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7439 /// when these variables are captured by the lambda.
7440 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7441   for (const auto &Shadow : LSI->ShadowingDecls) {
7442     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7443     // Try to avoid the warning when the shadowed decl isn't captured.
7444     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7445     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7446     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7447                                        ? diag::warn_decl_shadow_uncaptured_local
7448                                        : diag::warn_decl_shadow)
7449         << Shadow.VD->getDeclName()
7450         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7451     if (!CaptureLoc.isInvalid())
7452       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7453           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7454     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7455   }
7456 }
7457 
7458 /// Check -Wshadow without the advantage of a previous lookup.
7459 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7460   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7461     return;
7462 
7463   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7464                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7465   LookupName(R, S);
7466   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7467     CheckShadow(D, ShadowedDecl, R);
7468 }
7469 
7470 /// Check if 'E', which is an expression that is about to be modified, refers
7471 /// to a constructor parameter that shadows a field.
7472 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7473   // Quickly ignore expressions that can't be shadowing ctor parameters.
7474   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7475     return;
7476   E = E->IgnoreParenImpCasts();
7477   auto *DRE = dyn_cast<DeclRefExpr>(E);
7478   if (!DRE)
7479     return;
7480   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7481   auto I = ShadowingDecls.find(D);
7482   if (I == ShadowingDecls.end())
7483     return;
7484   const NamedDecl *ShadowedDecl = I->second;
7485   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7486   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7487   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7488   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7489 
7490   // Avoid issuing multiple warnings about the same decl.
7491   ShadowingDecls.erase(I);
7492 }
7493 
7494 /// Check for conflict between this global or extern "C" declaration and
7495 /// previous global or extern "C" declarations. This is only used in C++.
7496 template<typename T>
7497 static bool checkGlobalOrExternCConflict(
7498     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7499   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7500   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7501 
7502   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7503     // The common case: this global doesn't conflict with any extern "C"
7504     // declaration.
7505     return false;
7506   }
7507 
7508   if (Prev) {
7509     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7510       // Both the old and new declarations have C language linkage. This is a
7511       // redeclaration.
7512       Previous.clear();
7513       Previous.addDecl(Prev);
7514       return true;
7515     }
7516 
7517     // This is a global, non-extern "C" declaration, and there is a previous
7518     // non-global extern "C" declaration. Diagnose if this is a variable
7519     // declaration.
7520     if (!isa<VarDecl>(ND))
7521       return false;
7522   } else {
7523     // The declaration is extern "C". Check for any declaration in the
7524     // translation unit which might conflict.
7525     if (IsGlobal) {
7526       // We have already performed the lookup into the translation unit.
7527       IsGlobal = false;
7528       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7529            I != E; ++I) {
7530         if (isa<VarDecl>(*I)) {
7531           Prev = *I;
7532           break;
7533         }
7534       }
7535     } else {
7536       DeclContext::lookup_result R =
7537           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7538       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7539            I != E; ++I) {
7540         if (isa<VarDecl>(*I)) {
7541           Prev = *I;
7542           break;
7543         }
7544         // FIXME: If we have any other entity with this name in global scope,
7545         // the declaration is ill-formed, but that is a defect: it breaks the
7546         // 'stat' hack, for instance. Only variables can have mangled name
7547         // clashes with extern "C" declarations, so only they deserve a
7548         // diagnostic.
7549       }
7550     }
7551 
7552     if (!Prev)
7553       return false;
7554   }
7555 
7556   // Use the first declaration's location to ensure we point at something which
7557   // is lexically inside an extern "C" linkage-spec.
7558   assert(Prev && "should have found a previous declaration to diagnose");
7559   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7560     Prev = FD->getFirstDecl();
7561   else
7562     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7563 
7564   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7565     << IsGlobal << ND;
7566   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7567     << IsGlobal;
7568   return false;
7569 }
7570 
7571 /// Apply special rules for handling extern "C" declarations. Returns \c true
7572 /// if we have found that this is a redeclaration of some prior entity.
7573 ///
7574 /// Per C++ [dcl.link]p6:
7575 ///   Two declarations [for a function or variable] with C language linkage
7576 ///   with the same name that appear in different scopes refer to the same
7577 ///   [entity]. An entity with C language linkage shall not be declared with
7578 ///   the same name as an entity in global scope.
7579 template<typename T>
7580 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7581                                                   LookupResult &Previous) {
7582   if (!S.getLangOpts().CPlusPlus) {
7583     // In C, when declaring a global variable, look for a corresponding 'extern'
7584     // variable declared in function scope. We don't need this in C++, because
7585     // we find local extern decls in the surrounding file-scope DeclContext.
7586     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7587       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7588         Previous.clear();
7589         Previous.addDecl(Prev);
7590         return true;
7591       }
7592     }
7593     return false;
7594   }
7595 
7596   // A declaration in the translation unit can conflict with an extern "C"
7597   // declaration.
7598   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7599     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7600 
7601   // An extern "C" declaration can conflict with a declaration in the
7602   // translation unit or can be a redeclaration of an extern "C" declaration
7603   // in another scope.
7604   if (isIncompleteDeclExternC(S,ND))
7605     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7606 
7607   // Neither global nor extern "C": nothing to do.
7608   return false;
7609 }
7610 
7611 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7612   // If the decl is already known invalid, don't check it.
7613   if (NewVD->isInvalidDecl())
7614     return;
7615 
7616   QualType T = NewVD->getType();
7617 
7618   // Defer checking an 'auto' type until its initializer is attached.
7619   if (T->isUndeducedType())
7620     return;
7621 
7622   if (NewVD->hasAttrs())
7623     CheckAlignasUnderalignment(NewVD);
7624 
7625   if (T->isObjCObjectType()) {
7626     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7627       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7628     T = Context.getObjCObjectPointerType(T);
7629     NewVD->setType(T);
7630   }
7631 
7632   // Emit an error if an address space was applied to decl with local storage.
7633   // This includes arrays of objects with address space qualifiers, but not
7634   // automatic variables that point to other address spaces.
7635   // ISO/IEC TR 18037 S5.1.2
7636   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7637       T.getAddressSpace() != LangAS::Default) {
7638     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7639     NewVD->setInvalidDecl();
7640     return;
7641   }
7642 
7643   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7644   // scope.
7645   if (getLangOpts().OpenCLVersion == 120 &&
7646       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7647       NewVD->isStaticLocal()) {
7648     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7649     NewVD->setInvalidDecl();
7650     return;
7651   }
7652 
7653   if (getLangOpts().OpenCL) {
7654     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7655     if (NewVD->hasAttr<BlocksAttr>()) {
7656       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7657       return;
7658     }
7659 
7660     if (T->isBlockPointerType()) {
7661       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7662       // can't use 'extern' storage class.
7663       if (!T.isConstQualified()) {
7664         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7665             << 0 /*const*/;
7666         NewVD->setInvalidDecl();
7667         return;
7668       }
7669       if (NewVD->hasExternalStorage()) {
7670         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7671         NewVD->setInvalidDecl();
7672         return;
7673       }
7674     }
7675     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7676     // __constant address space.
7677     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7678     // variables inside a function can also be declared in the global
7679     // address space.
7680     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7681     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7682     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7683         NewVD->hasExternalStorage()) {
7684       if (!T->isSamplerT() &&
7685           !(T.getAddressSpace() == LangAS::opencl_constant ||
7686             (T.getAddressSpace() == LangAS::opencl_global &&
7687              (getLangOpts().OpenCLVersion == 200 ||
7688               getLangOpts().OpenCLCPlusPlus)))) {
7689         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7690         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7691           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7692               << Scope << "global or constant";
7693         else
7694           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7695               << Scope << "constant";
7696         NewVD->setInvalidDecl();
7697         return;
7698       }
7699     } else {
7700       if (T.getAddressSpace() == LangAS::opencl_global) {
7701         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7702             << 1 /*is any function*/ << "global";
7703         NewVD->setInvalidDecl();
7704         return;
7705       }
7706       if (T.getAddressSpace() == LangAS::opencl_constant ||
7707           T.getAddressSpace() == LangAS::opencl_local) {
7708         FunctionDecl *FD = getCurFunctionDecl();
7709         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7710         // in functions.
7711         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7712           if (T.getAddressSpace() == LangAS::opencl_constant)
7713             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7714                 << 0 /*non-kernel only*/ << "constant";
7715           else
7716             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7717                 << 0 /*non-kernel only*/ << "local";
7718           NewVD->setInvalidDecl();
7719           return;
7720         }
7721         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7722         // in the outermost scope of a kernel function.
7723         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7724           if (!getCurScope()->isFunctionScope()) {
7725             if (T.getAddressSpace() == LangAS::opencl_constant)
7726               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7727                   << "constant";
7728             else
7729               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7730                   << "local";
7731             NewVD->setInvalidDecl();
7732             return;
7733           }
7734         }
7735       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7736                  // If we are parsing a template we didn't deduce an addr
7737                  // space yet.
7738                  T.getAddressSpace() != LangAS::Default) {
7739         // Do not allow other address spaces on automatic variable.
7740         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7741         NewVD->setInvalidDecl();
7742         return;
7743       }
7744     }
7745   }
7746 
7747   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7748       && !NewVD->hasAttr<BlocksAttr>()) {
7749     if (getLangOpts().getGC() != LangOptions::NonGC)
7750       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7751     else {
7752       assert(!getLangOpts().ObjCAutoRefCount);
7753       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7754     }
7755   }
7756 
7757   bool isVM = T->isVariablyModifiedType();
7758   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7759       NewVD->hasAttr<BlocksAttr>())
7760     setFunctionHasBranchProtectedScope();
7761 
7762   if ((isVM && NewVD->hasLinkage()) ||
7763       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7764     bool SizeIsNegative;
7765     llvm::APSInt Oversized;
7766     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7767         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7768     QualType FixedT;
7769     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7770       FixedT = FixedTInfo->getType();
7771     else if (FixedTInfo) {
7772       // Type and type-as-written are canonically different. We need to fix up
7773       // both types separately.
7774       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7775                                                    Oversized);
7776     }
7777     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7778       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7779       // FIXME: This won't give the correct result for
7780       // int a[10][n];
7781       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7782 
7783       if (NewVD->isFileVarDecl())
7784         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7785         << SizeRange;
7786       else if (NewVD->isStaticLocal())
7787         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7788         << SizeRange;
7789       else
7790         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7791         << SizeRange;
7792       NewVD->setInvalidDecl();
7793       return;
7794     }
7795 
7796     if (!FixedTInfo) {
7797       if (NewVD->isFileVarDecl())
7798         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7799       else
7800         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7801       NewVD->setInvalidDecl();
7802       return;
7803     }
7804 
7805     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7806     NewVD->setType(FixedT);
7807     NewVD->setTypeSourceInfo(FixedTInfo);
7808   }
7809 
7810   if (T->isVoidType()) {
7811     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7812     //                    of objects and functions.
7813     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7814       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7815         << T;
7816       NewVD->setInvalidDecl();
7817       return;
7818     }
7819   }
7820 
7821   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7822     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7823     NewVD->setInvalidDecl();
7824     return;
7825   }
7826 
7827   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7828     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7829     NewVD->setInvalidDecl();
7830     return;
7831   }
7832 
7833   if (NewVD->isConstexpr() && !T->isDependentType() &&
7834       RequireLiteralType(NewVD->getLocation(), T,
7835                          diag::err_constexpr_var_non_literal)) {
7836     NewVD->setInvalidDecl();
7837     return;
7838   }
7839 }
7840 
7841 /// Perform semantic checking on a newly-created variable
7842 /// declaration.
7843 ///
7844 /// This routine performs all of the type-checking required for a
7845 /// variable declaration once it has been built. It is used both to
7846 /// check variables after they have been parsed and their declarators
7847 /// have been translated into a declaration, and to check variables
7848 /// that have been instantiated from a template.
7849 ///
7850 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7851 ///
7852 /// Returns true if the variable declaration is a redeclaration.
7853 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7854   CheckVariableDeclarationType(NewVD);
7855 
7856   // If the decl is already known invalid, don't check it.
7857   if (NewVD->isInvalidDecl())
7858     return false;
7859 
7860   // If we did not find anything by this name, look for a non-visible
7861   // extern "C" declaration with the same name.
7862   if (Previous.empty() &&
7863       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7864     Previous.setShadowed();
7865 
7866   if (!Previous.empty()) {
7867     MergeVarDecl(NewVD, Previous);
7868     return true;
7869   }
7870   return false;
7871 }
7872 
7873 namespace {
7874 struct FindOverriddenMethod {
7875   Sema *S;
7876   CXXMethodDecl *Method;
7877 
7878   /// Member lookup function that determines whether a given C++
7879   /// method overrides a method in a base class, to be used with
7880   /// CXXRecordDecl::lookupInBases().
7881   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7882     RecordDecl *BaseRecord =
7883         Specifier->getType()->castAs<RecordType>()->getDecl();
7884 
7885     DeclarationName Name = Method->getDeclName();
7886 
7887     // FIXME: Do we care about other names here too?
7888     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7889       // We really want to find the base class destructor here.
7890       QualType T = S->Context.getTypeDeclType(BaseRecord);
7891       CanQualType CT = S->Context.getCanonicalType(T);
7892 
7893       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7894     }
7895 
7896     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7897          Path.Decls = Path.Decls.slice(1)) {
7898       NamedDecl *D = Path.Decls.front();
7899       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7900         if (MD->isVirtual() &&
7901             !S->IsOverload(
7902                 Method, MD, /*UseMemberUsingDeclRules=*/false,
7903                 /*ConsiderCudaAttrs=*/true,
7904                 // C++2a [class.virtual]p2 does not consider requires clauses
7905                 // when overriding.
7906                 /*ConsiderRequiresClauses=*/false))
7907           return true;
7908       }
7909     }
7910 
7911     return false;
7912   }
7913 };
7914 
7915 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7916 } // end anonymous namespace
7917 
7918 /// Report an error regarding overriding, along with any relevant
7919 /// overridden methods.
7920 ///
7921 /// \param DiagID the primary error to report.
7922 /// \param MD the overriding method.
7923 /// \param OEK which overrides to include as notes.
7924 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7925                             OverrideErrorKind OEK = OEK_All) {
7926   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7927   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7928     // This check (& the OEK parameter) could be replaced by a predicate, but
7929     // without lambdas that would be overkill. This is still nicer than writing
7930     // out the diag loop 3 times.
7931     if ((OEK == OEK_All) ||
7932         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7933         (OEK == OEK_Deleted && O->isDeleted()))
7934       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7935   }
7936 }
7937 
7938 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7939 /// and if so, check that it's a valid override and remember it.
7940 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7941   // Look for methods in base classes that this method might override.
7942   CXXBasePaths Paths;
7943   FindOverriddenMethod FOM;
7944   FOM.Method = MD;
7945   FOM.S = this;
7946   bool hasDeletedOverridenMethods = false;
7947   bool hasNonDeletedOverridenMethods = false;
7948   bool AddedAny = false;
7949   if (DC->lookupInBases(FOM, Paths)) {
7950     for (auto *I : Paths.found_decls()) {
7951       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7952         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7953         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7954             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7955             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7956             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7957           hasDeletedOverridenMethods |= OldMD->isDeleted();
7958           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7959           AddedAny = true;
7960         }
7961       }
7962     }
7963   }
7964 
7965   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7966     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7967   }
7968   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7969     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7970   }
7971 
7972   return AddedAny;
7973 }
7974 
7975 namespace {
7976   // Struct for holding all of the extra arguments needed by
7977   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7978   struct ActOnFDArgs {
7979     Scope *S;
7980     Declarator &D;
7981     MultiTemplateParamsArg TemplateParamLists;
7982     bool AddToScope;
7983   };
7984 } // end anonymous namespace
7985 
7986 namespace {
7987 
7988 // Callback to only accept typo corrections that have a non-zero edit distance.
7989 // Also only accept corrections that have the same parent decl.
7990 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7991  public:
7992   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7993                             CXXRecordDecl *Parent)
7994       : Context(Context), OriginalFD(TypoFD),
7995         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7996 
7997   bool ValidateCandidate(const TypoCorrection &candidate) override {
7998     if (candidate.getEditDistance() == 0)
7999       return false;
8000 
8001     SmallVector<unsigned, 1> MismatchedParams;
8002     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8003                                           CDeclEnd = candidate.end();
8004          CDecl != CDeclEnd; ++CDecl) {
8005       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8006 
8007       if (FD && !FD->hasBody() &&
8008           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8009         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8010           CXXRecordDecl *Parent = MD->getParent();
8011           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8012             return true;
8013         } else if (!ExpectedParent) {
8014           return true;
8015         }
8016       }
8017     }
8018 
8019     return false;
8020   }
8021 
8022   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8023     return std::make_unique<DifferentNameValidatorCCC>(*this);
8024   }
8025 
8026  private:
8027   ASTContext &Context;
8028   FunctionDecl *OriginalFD;
8029   CXXRecordDecl *ExpectedParent;
8030 };
8031 
8032 } // end anonymous namespace
8033 
8034 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8035   TypoCorrectedFunctionDefinitions.insert(F);
8036 }
8037 
8038 /// Generate diagnostics for an invalid function redeclaration.
8039 ///
8040 /// This routine handles generating the diagnostic messages for an invalid
8041 /// function redeclaration, including finding possible similar declarations
8042 /// or performing typo correction if there are no previous declarations with
8043 /// the same name.
8044 ///
8045 /// Returns a NamedDecl iff typo correction was performed and substituting in
8046 /// the new declaration name does not cause new errors.
8047 static NamedDecl *DiagnoseInvalidRedeclaration(
8048     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8049     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8050   DeclarationName Name = NewFD->getDeclName();
8051   DeclContext *NewDC = NewFD->getDeclContext();
8052   SmallVector<unsigned, 1> MismatchedParams;
8053   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8054   TypoCorrection Correction;
8055   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8056   unsigned DiagMsg =
8057     IsLocalFriend ? diag::err_no_matching_local_friend :
8058     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8059     diag::err_member_decl_does_not_match;
8060   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8061                     IsLocalFriend ? Sema::LookupLocalFriendName
8062                                   : Sema::LookupOrdinaryName,
8063                     Sema::ForVisibleRedeclaration);
8064 
8065   NewFD->setInvalidDecl();
8066   if (IsLocalFriend)
8067     SemaRef.LookupName(Prev, S);
8068   else
8069     SemaRef.LookupQualifiedName(Prev, NewDC);
8070   assert(!Prev.isAmbiguous() &&
8071          "Cannot have an ambiguity in previous-declaration lookup");
8072   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8073   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8074                                 MD ? MD->getParent() : nullptr);
8075   if (!Prev.empty()) {
8076     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8077          Func != FuncEnd; ++Func) {
8078       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8079       if (FD &&
8080           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8081         // Add 1 to the index so that 0 can mean the mismatch didn't
8082         // involve a parameter
8083         unsigned ParamNum =
8084             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8085         NearMatches.push_back(std::make_pair(FD, ParamNum));
8086       }
8087     }
8088   // If the qualified name lookup yielded nothing, try typo correction
8089   } else if ((Correction = SemaRef.CorrectTypo(
8090                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8091                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8092                   IsLocalFriend ? nullptr : NewDC))) {
8093     // Set up everything for the call to ActOnFunctionDeclarator
8094     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8095                               ExtraArgs.D.getIdentifierLoc());
8096     Previous.clear();
8097     Previous.setLookupName(Correction.getCorrection());
8098     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8099                                     CDeclEnd = Correction.end();
8100          CDecl != CDeclEnd; ++CDecl) {
8101       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8102       if (FD && !FD->hasBody() &&
8103           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8104         Previous.addDecl(FD);
8105       }
8106     }
8107     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8108 
8109     NamedDecl *Result;
8110     // Retry building the function declaration with the new previous
8111     // declarations, and with errors suppressed.
8112     {
8113       // Trap errors.
8114       Sema::SFINAETrap Trap(SemaRef);
8115 
8116       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8117       // pieces need to verify the typo-corrected C++ declaration and hopefully
8118       // eliminate the need for the parameter pack ExtraArgs.
8119       Result = SemaRef.ActOnFunctionDeclarator(
8120           ExtraArgs.S, ExtraArgs.D,
8121           Correction.getCorrectionDecl()->getDeclContext(),
8122           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8123           ExtraArgs.AddToScope);
8124 
8125       if (Trap.hasErrorOccurred())
8126         Result = nullptr;
8127     }
8128 
8129     if (Result) {
8130       // Determine which correction we picked.
8131       Decl *Canonical = Result->getCanonicalDecl();
8132       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8133            I != E; ++I)
8134         if ((*I)->getCanonicalDecl() == Canonical)
8135           Correction.setCorrectionDecl(*I);
8136 
8137       // Let Sema know about the correction.
8138       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8139       SemaRef.diagnoseTypo(
8140           Correction,
8141           SemaRef.PDiag(IsLocalFriend
8142                           ? diag::err_no_matching_local_friend_suggest
8143                           : diag::err_member_decl_does_not_match_suggest)
8144             << Name << NewDC << IsDefinition);
8145       return Result;
8146     }
8147 
8148     // Pretend the typo correction never occurred
8149     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8150                               ExtraArgs.D.getIdentifierLoc());
8151     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8152     Previous.clear();
8153     Previous.setLookupName(Name);
8154   }
8155 
8156   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8157       << Name << NewDC << IsDefinition << NewFD->getLocation();
8158 
8159   bool NewFDisConst = false;
8160   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8161     NewFDisConst = NewMD->isConst();
8162 
8163   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8164        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8165        NearMatch != NearMatchEnd; ++NearMatch) {
8166     FunctionDecl *FD = NearMatch->first;
8167     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8168     bool FDisConst = MD && MD->isConst();
8169     bool IsMember = MD || !IsLocalFriend;
8170 
8171     // FIXME: These notes are poorly worded for the local friend case.
8172     if (unsigned Idx = NearMatch->second) {
8173       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8174       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8175       if (Loc.isInvalid()) Loc = FD->getLocation();
8176       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8177                                  : diag::note_local_decl_close_param_match)
8178         << Idx << FDParam->getType()
8179         << NewFD->getParamDecl(Idx - 1)->getType();
8180     } else if (FDisConst != NewFDisConst) {
8181       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8182           << NewFDisConst << FD->getSourceRange().getEnd();
8183     } else
8184       SemaRef.Diag(FD->getLocation(),
8185                    IsMember ? diag::note_member_def_close_match
8186                             : diag::note_local_decl_close_match);
8187   }
8188   return nullptr;
8189 }
8190 
8191 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8192   switch (D.getDeclSpec().getStorageClassSpec()) {
8193   default: llvm_unreachable("Unknown storage class!");
8194   case DeclSpec::SCS_auto:
8195   case DeclSpec::SCS_register:
8196   case DeclSpec::SCS_mutable:
8197     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8198                  diag::err_typecheck_sclass_func);
8199     D.getMutableDeclSpec().ClearStorageClassSpecs();
8200     D.setInvalidType();
8201     break;
8202   case DeclSpec::SCS_unspecified: break;
8203   case DeclSpec::SCS_extern:
8204     if (D.getDeclSpec().isExternInLinkageSpec())
8205       return SC_None;
8206     return SC_Extern;
8207   case DeclSpec::SCS_static: {
8208     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8209       // C99 6.7.1p5:
8210       //   The declaration of an identifier for a function that has
8211       //   block scope shall have no explicit storage-class specifier
8212       //   other than extern
8213       // See also (C++ [dcl.stc]p4).
8214       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8215                    diag::err_static_block_func);
8216       break;
8217     } else
8218       return SC_Static;
8219   }
8220   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8221   }
8222 
8223   // No explicit storage class has already been returned
8224   return SC_None;
8225 }
8226 
8227 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8228                                            DeclContext *DC, QualType &R,
8229                                            TypeSourceInfo *TInfo,
8230                                            StorageClass SC,
8231                                            bool &IsVirtualOkay) {
8232   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8233   DeclarationName Name = NameInfo.getName();
8234 
8235   FunctionDecl *NewFD = nullptr;
8236   bool isInline = D.getDeclSpec().isInlineSpecified();
8237 
8238   if (!SemaRef.getLangOpts().CPlusPlus) {
8239     // Determine whether the function was written with a
8240     // prototype. This true when:
8241     //   - there is a prototype in the declarator, or
8242     //   - the type R of the function is some kind of typedef or other non-
8243     //     attributed reference to a type name (which eventually refers to a
8244     //     function type).
8245     bool HasPrototype =
8246       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8247       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8248 
8249     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8250                                  R, TInfo, SC, isInline, HasPrototype,
8251                                  CSK_unspecified,
8252                                  /*TrailingRequiresClause=*/nullptr);
8253     if (D.isInvalidType())
8254       NewFD->setInvalidDecl();
8255 
8256     return NewFD;
8257   }
8258 
8259   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8260 
8261   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8262   if (ConstexprKind == CSK_constinit) {
8263     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8264                  diag::err_constexpr_wrong_decl_kind)
8265         << ConstexprKind;
8266     ConstexprKind = CSK_unspecified;
8267     D.getMutableDeclSpec().ClearConstexprSpec();
8268   }
8269   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8270 
8271   // Check that the return type is not an abstract class type.
8272   // For record types, this is done by the AbstractClassUsageDiagnoser once
8273   // the class has been completely parsed.
8274   if (!DC->isRecord() &&
8275       SemaRef.RequireNonAbstractType(
8276           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8277           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8278     D.setInvalidType();
8279 
8280   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8281     // This is a C++ constructor declaration.
8282     assert(DC->isRecord() &&
8283            "Constructors can only be declared in a member context");
8284 
8285     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8286     return CXXConstructorDecl::Create(
8287         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8288         TInfo, ExplicitSpecifier, isInline,
8289         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8290         TrailingRequiresClause);
8291 
8292   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8293     // This is a C++ destructor declaration.
8294     if (DC->isRecord()) {
8295       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8296       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8297       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8298           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8299           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8300           TrailingRequiresClause);
8301 
8302       // If the destructor needs an implicit exception specification, set it
8303       // now. FIXME: It'd be nice to be able to create the right type to start
8304       // with, but the type needs to reference the destructor declaration.
8305       if (SemaRef.getLangOpts().CPlusPlus11)
8306         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8307 
8308       IsVirtualOkay = true;
8309       return NewDD;
8310 
8311     } else {
8312       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8313       D.setInvalidType();
8314 
8315       // Create a FunctionDecl to satisfy the function definition parsing
8316       // code path.
8317       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8318                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8319                                   isInline,
8320                                   /*hasPrototype=*/true, ConstexprKind,
8321                                   TrailingRequiresClause);
8322     }
8323 
8324   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8325     if (!DC->isRecord()) {
8326       SemaRef.Diag(D.getIdentifierLoc(),
8327            diag::err_conv_function_not_member);
8328       return nullptr;
8329     }
8330 
8331     SemaRef.CheckConversionDeclarator(D, R, SC);
8332     if (D.isInvalidType())
8333       return nullptr;
8334 
8335     IsVirtualOkay = true;
8336     return CXXConversionDecl::Create(
8337         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8338         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8339         TrailingRequiresClause);
8340 
8341   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8342     if (TrailingRequiresClause)
8343       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8344                    diag::err_trailing_requires_clause_on_deduction_guide)
8345           << TrailingRequiresClause->getSourceRange();
8346     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8347 
8348     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8349                                          ExplicitSpecifier, NameInfo, R, TInfo,
8350                                          D.getEndLoc());
8351   } else if (DC->isRecord()) {
8352     // If the name of the function is the same as the name of the record,
8353     // then this must be an invalid constructor that has a return type.
8354     // (The parser checks for a return type and makes the declarator a
8355     // constructor if it has no return type).
8356     if (Name.getAsIdentifierInfo() &&
8357         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8358       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8359         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8360         << SourceRange(D.getIdentifierLoc());
8361       return nullptr;
8362     }
8363 
8364     // This is a C++ method declaration.
8365     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8366         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8367         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8368         TrailingRequiresClause);
8369     IsVirtualOkay = !Ret->isStatic();
8370     return Ret;
8371   } else {
8372     bool isFriend =
8373         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8374     if (!isFriend && SemaRef.CurContext->isRecord())
8375       return nullptr;
8376 
8377     // Determine whether the function was written with a
8378     // prototype. This true when:
8379     //   - we're in C++ (where every function has a prototype),
8380     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8381                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8382                                 ConstexprKind, TrailingRequiresClause);
8383   }
8384 }
8385 
8386 enum OpenCLParamType {
8387   ValidKernelParam,
8388   PtrPtrKernelParam,
8389   PtrKernelParam,
8390   InvalidAddrSpacePtrKernelParam,
8391   InvalidKernelParam,
8392   RecordKernelParam
8393 };
8394 
8395 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8396   // Size dependent types are just typedefs to normal integer types
8397   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8398   // integers other than by their names.
8399   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8400 
8401   // Remove typedefs one by one until we reach a typedef
8402   // for a size dependent type.
8403   QualType DesugaredTy = Ty;
8404   do {
8405     ArrayRef<StringRef> Names(SizeTypeNames);
8406     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8407     if (Names.end() != Match)
8408       return true;
8409 
8410     Ty = DesugaredTy;
8411     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8412   } while (DesugaredTy != Ty);
8413 
8414   return false;
8415 }
8416 
8417 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8418   if (PT->isPointerType()) {
8419     QualType PointeeType = PT->getPointeeType();
8420     if (PointeeType->isPointerType())
8421       return PtrPtrKernelParam;
8422     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8423         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8424         PointeeType.getAddressSpace() == LangAS::Default)
8425       return InvalidAddrSpacePtrKernelParam;
8426     return PtrKernelParam;
8427   }
8428 
8429   // OpenCL v1.2 s6.9.k:
8430   // Arguments to kernel functions in a program cannot be declared with the
8431   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8432   // uintptr_t or a struct and/or union that contain fields declared to be one
8433   // of these built-in scalar types.
8434   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8435     return InvalidKernelParam;
8436 
8437   if (PT->isImageType())
8438     return PtrKernelParam;
8439 
8440   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8441     return InvalidKernelParam;
8442 
8443   // OpenCL extension spec v1.2 s9.5:
8444   // This extension adds support for half scalar and vector types as built-in
8445   // types that can be used for arithmetic operations, conversions etc.
8446   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8447     return InvalidKernelParam;
8448 
8449   if (PT->isRecordType())
8450     return RecordKernelParam;
8451 
8452   // Look into an array argument to check if it has a forbidden type.
8453   if (PT->isArrayType()) {
8454     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8455     // Call ourself to check an underlying type of an array. Since the
8456     // getPointeeOrArrayElementType returns an innermost type which is not an
8457     // array, this recursive call only happens once.
8458     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8459   }
8460 
8461   return ValidKernelParam;
8462 }
8463 
8464 static void checkIsValidOpenCLKernelParameter(
8465   Sema &S,
8466   Declarator &D,
8467   ParmVarDecl *Param,
8468   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8469   QualType PT = Param->getType();
8470 
8471   // Cache the valid types we encounter to avoid rechecking structs that are
8472   // used again
8473   if (ValidTypes.count(PT.getTypePtr()))
8474     return;
8475 
8476   switch (getOpenCLKernelParameterType(S, PT)) {
8477   case PtrPtrKernelParam:
8478     // OpenCL v1.2 s6.9.a:
8479     // A kernel function argument cannot be declared as a
8480     // pointer to a pointer type.
8481     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8482     D.setInvalidType();
8483     return;
8484 
8485   case InvalidAddrSpacePtrKernelParam:
8486     // OpenCL v1.0 s6.5:
8487     // __kernel function arguments declared to be a pointer of a type can point
8488     // to one of the following address spaces only : __global, __local or
8489     // __constant.
8490     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8491     D.setInvalidType();
8492     return;
8493 
8494     // OpenCL v1.2 s6.9.k:
8495     // Arguments to kernel functions in a program cannot be declared with the
8496     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8497     // uintptr_t or a struct and/or union that contain fields declared to be
8498     // one of these built-in scalar types.
8499 
8500   case InvalidKernelParam:
8501     // OpenCL v1.2 s6.8 n:
8502     // A kernel function argument cannot be declared
8503     // of event_t type.
8504     // Do not diagnose half type since it is diagnosed as invalid argument
8505     // type for any function elsewhere.
8506     if (!PT->isHalfType()) {
8507       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8508 
8509       // Explain what typedefs are involved.
8510       const TypedefType *Typedef = nullptr;
8511       while ((Typedef = PT->getAs<TypedefType>())) {
8512         SourceLocation Loc = Typedef->getDecl()->getLocation();
8513         // SourceLocation may be invalid for a built-in type.
8514         if (Loc.isValid())
8515           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8516         PT = Typedef->desugar();
8517       }
8518     }
8519 
8520     D.setInvalidType();
8521     return;
8522 
8523   case PtrKernelParam:
8524   case ValidKernelParam:
8525     ValidTypes.insert(PT.getTypePtr());
8526     return;
8527 
8528   case RecordKernelParam:
8529     break;
8530   }
8531 
8532   // Track nested structs we will inspect
8533   SmallVector<const Decl *, 4> VisitStack;
8534 
8535   // Track where we are in the nested structs. Items will migrate from
8536   // VisitStack to HistoryStack as we do the DFS for bad field.
8537   SmallVector<const FieldDecl *, 4> HistoryStack;
8538   HistoryStack.push_back(nullptr);
8539 
8540   // At this point we already handled everything except of a RecordType or
8541   // an ArrayType of a RecordType.
8542   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8543   const RecordType *RecTy =
8544       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8545   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8546 
8547   VisitStack.push_back(RecTy->getDecl());
8548   assert(VisitStack.back() && "First decl null?");
8549 
8550   do {
8551     const Decl *Next = VisitStack.pop_back_val();
8552     if (!Next) {
8553       assert(!HistoryStack.empty());
8554       // Found a marker, we have gone up a level
8555       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8556         ValidTypes.insert(Hist->getType().getTypePtr());
8557 
8558       continue;
8559     }
8560 
8561     // Adds everything except the original parameter declaration (which is not a
8562     // field itself) to the history stack.
8563     const RecordDecl *RD;
8564     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8565       HistoryStack.push_back(Field);
8566 
8567       QualType FieldTy = Field->getType();
8568       // Other field types (known to be valid or invalid) are handled while we
8569       // walk around RecordDecl::fields().
8570       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8571              "Unexpected type.");
8572       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8573 
8574       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8575     } else {
8576       RD = cast<RecordDecl>(Next);
8577     }
8578 
8579     // Add a null marker so we know when we've gone back up a level
8580     VisitStack.push_back(nullptr);
8581 
8582     for (const auto *FD : RD->fields()) {
8583       QualType QT = FD->getType();
8584 
8585       if (ValidTypes.count(QT.getTypePtr()))
8586         continue;
8587 
8588       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8589       if (ParamType == ValidKernelParam)
8590         continue;
8591 
8592       if (ParamType == RecordKernelParam) {
8593         VisitStack.push_back(FD);
8594         continue;
8595       }
8596 
8597       // OpenCL v1.2 s6.9.p:
8598       // Arguments to kernel functions that are declared to be a struct or union
8599       // do not allow OpenCL objects to be passed as elements of the struct or
8600       // union.
8601       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8602           ParamType == InvalidAddrSpacePtrKernelParam) {
8603         S.Diag(Param->getLocation(),
8604                diag::err_record_with_pointers_kernel_param)
8605           << PT->isUnionType()
8606           << PT;
8607       } else {
8608         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8609       }
8610 
8611       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8612           << OrigRecDecl->getDeclName();
8613 
8614       // We have an error, now let's go back up through history and show where
8615       // the offending field came from
8616       for (ArrayRef<const FieldDecl *>::const_iterator
8617                I = HistoryStack.begin() + 1,
8618                E = HistoryStack.end();
8619            I != E; ++I) {
8620         const FieldDecl *OuterField = *I;
8621         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8622           << OuterField->getType();
8623       }
8624 
8625       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8626         << QT->isPointerType()
8627         << QT;
8628       D.setInvalidType();
8629       return;
8630     }
8631   } while (!VisitStack.empty());
8632 }
8633 
8634 /// Find the DeclContext in which a tag is implicitly declared if we see an
8635 /// elaborated type specifier in the specified context, and lookup finds
8636 /// nothing.
8637 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8638   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8639     DC = DC->getParent();
8640   return DC;
8641 }
8642 
8643 /// Find the Scope in which a tag is implicitly declared if we see an
8644 /// elaborated type specifier in the specified context, and lookup finds
8645 /// nothing.
8646 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8647   while (S->isClassScope() ||
8648          (LangOpts.CPlusPlus &&
8649           S->isFunctionPrototypeScope()) ||
8650          ((S->getFlags() & Scope::DeclScope) == 0) ||
8651          (S->getEntity() && S->getEntity()->isTransparentContext()))
8652     S = S->getParent();
8653   return S;
8654 }
8655 
8656 NamedDecl*
8657 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8658                               TypeSourceInfo *TInfo, LookupResult &Previous,
8659                               MultiTemplateParamsArg TemplateParamLists,
8660                               bool &AddToScope) {
8661   QualType R = TInfo->getType();
8662 
8663   assert(R->isFunctionType());
8664 
8665   // TODO: consider using NameInfo for diagnostic.
8666   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8667   DeclarationName Name = NameInfo.getName();
8668   StorageClass SC = getFunctionStorageClass(*this, D);
8669 
8670   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8671     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8672          diag::err_invalid_thread)
8673       << DeclSpec::getSpecifierName(TSCS);
8674 
8675   if (D.isFirstDeclarationOfMember())
8676     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8677                            D.getIdentifierLoc());
8678 
8679   bool isFriend = false;
8680   FunctionTemplateDecl *FunctionTemplate = nullptr;
8681   bool isMemberSpecialization = false;
8682   bool isFunctionTemplateSpecialization = false;
8683 
8684   bool isDependentClassScopeExplicitSpecialization = false;
8685   bool HasExplicitTemplateArgs = false;
8686   TemplateArgumentListInfo TemplateArgs;
8687 
8688   bool isVirtualOkay = false;
8689 
8690   DeclContext *OriginalDC = DC;
8691   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8692 
8693   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8694                                               isVirtualOkay);
8695   if (!NewFD) return nullptr;
8696 
8697   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8698     NewFD->setTopLevelDeclInObjCContainer();
8699 
8700   // Set the lexical context. If this is a function-scope declaration, or has a
8701   // C++ scope specifier, or is the object of a friend declaration, the lexical
8702   // context will be different from the semantic context.
8703   NewFD->setLexicalDeclContext(CurContext);
8704 
8705   if (IsLocalExternDecl)
8706     NewFD->setLocalExternDecl();
8707 
8708   if (getLangOpts().CPlusPlus) {
8709     bool isInline = D.getDeclSpec().isInlineSpecified();
8710     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8711     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8712     isFriend = D.getDeclSpec().isFriendSpecified();
8713     if (isFriend && !isInline && D.isFunctionDefinition()) {
8714       // C++ [class.friend]p5
8715       //   A function can be defined in a friend declaration of a
8716       //   class . . . . Such a function is implicitly inline.
8717       NewFD->setImplicitlyInline();
8718     }
8719 
8720     // If this is a method defined in an __interface, and is not a constructor
8721     // or an overloaded operator, then set the pure flag (isVirtual will already
8722     // return true).
8723     if (const CXXRecordDecl *Parent =
8724           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8725       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8726         NewFD->setPure(true);
8727 
8728       // C++ [class.union]p2
8729       //   A union can have member functions, but not virtual functions.
8730       if (isVirtual && Parent->isUnion())
8731         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8732     }
8733 
8734     SetNestedNameSpecifier(*this, NewFD, D);
8735     isMemberSpecialization = false;
8736     isFunctionTemplateSpecialization = false;
8737     if (D.isInvalidType())
8738       NewFD->setInvalidDecl();
8739 
8740     // Match up the template parameter lists with the scope specifier, then
8741     // determine whether we have a template or a template specialization.
8742     bool Invalid = false;
8743     if (TemplateParameterList *TemplateParams =
8744             MatchTemplateParametersToScopeSpecifier(
8745                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8746                 D.getCXXScopeSpec(),
8747                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8748                     ? D.getName().TemplateId
8749                     : nullptr,
8750                 TemplateParamLists, isFriend, isMemberSpecialization,
8751                 Invalid)) {
8752       if (TemplateParams->size() > 0) {
8753         // This is a function template
8754 
8755         // Check that we can declare a template here.
8756         if (CheckTemplateDeclScope(S, TemplateParams))
8757           NewFD->setInvalidDecl();
8758 
8759         // A destructor cannot be a template.
8760         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8761           Diag(NewFD->getLocation(), diag::err_destructor_template);
8762           NewFD->setInvalidDecl();
8763         }
8764 
8765         // If we're adding a template to a dependent context, we may need to
8766         // rebuilding some of the types used within the template parameter list,
8767         // now that we know what the current instantiation is.
8768         if (DC->isDependentContext()) {
8769           ContextRAII SavedContext(*this, DC);
8770           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8771             Invalid = true;
8772         }
8773 
8774         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8775                                                         NewFD->getLocation(),
8776                                                         Name, TemplateParams,
8777                                                         NewFD);
8778         FunctionTemplate->setLexicalDeclContext(CurContext);
8779         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8780 
8781         // For source fidelity, store the other template param lists.
8782         if (TemplateParamLists.size() > 1) {
8783           NewFD->setTemplateParameterListsInfo(Context,
8784                                                TemplateParamLists.drop_back(1));
8785         }
8786       } else {
8787         // This is a function template specialization.
8788         isFunctionTemplateSpecialization = true;
8789         // For source fidelity, store all the template param lists.
8790         if (TemplateParamLists.size() > 0)
8791           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8792 
8793         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8794         if (isFriend) {
8795           // We want to remove the "template<>", found here.
8796           SourceRange RemoveRange = TemplateParams->getSourceRange();
8797 
8798           // If we remove the template<> and the name is not a
8799           // template-id, we're actually silently creating a problem:
8800           // the friend declaration will refer to an untemplated decl,
8801           // and clearly the user wants a template specialization.  So
8802           // we need to insert '<>' after the name.
8803           SourceLocation InsertLoc;
8804           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8805             InsertLoc = D.getName().getSourceRange().getEnd();
8806             InsertLoc = getLocForEndOfToken(InsertLoc);
8807           }
8808 
8809           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8810             << Name << RemoveRange
8811             << FixItHint::CreateRemoval(RemoveRange)
8812             << FixItHint::CreateInsertion(InsertLoc, "<>");
8813         }
8814       }
8815     } else {
8816       // All template param lists were matched against the scope specifier:
8817       // this is NOT (an explicit specialization of) a template.
8818       if (TemplateParamLists.size() > 0)
8819         // For source fidelity, store all the template param lists.
8820         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8821     }
8822 
8823     if (Invalid) {
8824       NewFD->setInvalidDecl();
8825       if (FunctionTemplate)
8826         FunctionTemplate->setInvalidDecl();
8827     }
8828 
8829     // C++ [dcl.fct.spec]p5:
8830     //   The virtual specifier shall only be used in declarations of
8831     //   nonstatic class member functions that appear within a
8832     //   member-specification of a class declaration; see 10.3.
8833     //
8834     if (isVirtual && !NewFD->isInvalidDecl()) {
8835       if (!isVirtualOkay) {
8836         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8837              diag::err_virtual_non_function);
8838       } else if (!CurContext->isRecord()) {
8839         // 'virtual' was specified outside of the class.
8840         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8841              diag::err_virtual_out_of_class)
8842           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8843       } else if (NewFD->getDescribedFunctionTemplate()) {
8844         // C++ [temp.mem]p3:
8845         //  A member function template shall not be virtual.
8846         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8847              diag::err_virtual_member_function_template)
8848           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8849       } else {
8850         // Okay: Add virtual to the method.
8851         NewFD->setVirtualAsWritten(true);
8852       }
8853 
8854       if (getLangOpts().CPlusPlus14 &&
8855           NewFD->getReturnType()->isUndeducedType())
8856         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8857     }
8858 
8859     if (getLangOpts().CPlusPlus14 &&
8860         (NewFD->isDependentContext() ||
8861          (isFriend && CurContext->isDependentContext())) &&
8862         NewFD->getReturnType()->isUndeducedType()) {
8863       // If the function template is referenced directly (for instance, as a
8864       // member of the current instantiation), pretend it has a dependent type.
8865       // This is not really justified by the standard, but is the only sane
8866       // thing to do.
8867       // FIXME: For a friend function, we have not marked the function as being
8868       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8869       const FunctionProtoType *FPT =
8870           NewFD->getType()->castAs<FunctionProtoType>();
8871       QualType Result =
8872           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8873       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8874                                              FPT->getExtProtoInfo()));
8875     }
8876 
8877     // C++ [dcl.fct.spec]p3:
8878     //  The inline specifier shall not appear on a block scope function
8879     //  declaration.
8880     if (isInline && !NewFD->isInvalidDecl()) {
8881       if (CurContext->isFunctionOrMethod()) {
8882         // 'inline' is not allowed on block scope function declaration.
8883         Diag(D.getDeclSpec().getInlineSpecLoc(),
8884              diag::err_inline_declaration_block_scope) << Name
8885           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8886       }
8887     }
8888 
8889     // C++ [dcl.fct.spec]p6:
8890     //  The explicit specifier shall be used only in the declaration of a
8891     //  constructor or conversion function within its class definition;
8892     //  see 12.3.1 and 12.3.2.
8893     if (hasExplicit && !NewFD->isInvalidDecl() &&
8894         !isa<CXXDeductionGuideDecl>(NewFD)) {
8895       if (!CurContext->isRecord()) {
8896         // 'explicit' was specified outside of the class.
8897         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8898              diag::err_explicit_out_of_class)
8899             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8900       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8901                  !isa<CXXConversionDecl>(NewFD)) {
8902         // 'explicit' was specified on a function that wasn't a constructor
8903         // or conversion function.
8904         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8905              diag::err_explicit_non_ctor_or_conv_function)
8906             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8907       }
8908     }
8909 
8910     if (ConstexprSpecKind ConstexprKind =
8911             D.getDeclSpec().getConstexprSpecifier()) {
8912       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8913       // are implicitly inline.
8914       NewFD->setImplicitlyInline();
8915 
8916       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8917       // be either constructors or to return a literal type. Therefore,
8918       // destructors cannot be declared constexpr.
8919       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8920         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8921             << ConstexprKind;
8922       }
8923     }
8924 
8925     // If __module_private__ was specified, mark the function accordingly.
8926     if (D.getDeclSpec().isModulePrivateSpecified()) {
8927       if (isFunctionTemplateSpecialization) {
8928         SourceLocation ModulePrivateLoc
8929           = D.getDeclSpec().getModulePrivateSpecLoc();
8930         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8931           << 0
8932           << FixItHint::CreateRemoval(ModulePrivateLoc);
8933       } else {
8934         NewFD->setModulePrivate();
8935         if (FunctionTemplate)
8936           FunctionTemplate->setModulePrivate();
8937       }
8938     }
8939 
8940     if (isFriend) {
8941       if (FunctionTemplate) {
8942         FunctionTemplate->setObjectOfFriendDecl();
8943         FunctionTemplate->setAccess(AS_public);
8944       }
8945       NewFD->setObjectOfFriendDecl();
8946       NewFD->setAccess(AS_public);
8947     }
8948 
8949     // If a function is defined as defaulted or deleted, mark it as such now.
8950     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8951     // definition kind to FDK_Definition.
8952     switch (D.getFunctionDefinitionKind()) {
8953       case FDK_Declaration:
8954       case FDK_Definition:
8955         break;
8956 
8957       case FDK_Defaulted:
8958         NewFD->setDefaulted();
8959         break;
8960 
8961       case FDK_Deleted:
8962         NewFD->setDeletedAsWritten();
8963         break;
8964     }
8965 
8966     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8967         D.isFunctionDefinition()) {
8968       // C++ [class.mfct]p2:
8969       //   A member function may be defined (8.4) in its class definition, in
8970       //   which case it is an inline member function (7.1.2)
8971       NewFD->setImplicitlyInline();
8972     }
8973 
8974     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8975         !CurContext->isRecord()) {
8976       // C++ [class.static]p1:
8977       //   A data or function member of a class may be declared static
8978       //   in a class definition, in which case it is a static member of
8979       //   the class.
8980 
8981       // Complain about the 'static' specifier if it's on an out-of-line
8982       // member function definition.
8983 
8984       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8985       // member function template declaration and class member template
8986       // declaration (MSVC versions before 2015), warn about this.
8987       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8988            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8989              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8990            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8991            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8992         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8993     }
8994 
8995     // C++11 [except.spec]p15:
8996     //   A deallocation function with no exception-specification is treated
8997     //   as if it were specified with noexcept(true).
8998     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8999     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9000          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9001         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9002       NewFD->setType(Context.getFunctionType(
9003           FPT->getReturnType(), FPT->getParamTypes(),
9004           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9005   }
9006 
9007   // Filter out previous declarations that don't match the scope.
9008   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9009                        D.getCXXScopeSpec().isNotEmpty() ||
9010                        isMemberSpecialization ||
9011                        isFunctionTemplateSpecialization);
9012 
9013   // Handle GNU asm-label extension (encoded as an attribute).
9014   if (Expr *E = (Expr*) D.getAsmLabel()) {
9015     // The parser guarantees this is a string.
9016     StringLiteral *SE = cast<StringLiteral>(E);
9017     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9018                                         /*IsLiteralLabel=*/true,
9019                                         SE->getStrTokenLoc(0)));
9020   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9021     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9022       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9023     if (I != ExtnameUndeclaredIdentifiers.end()) {
9024       if (isDeclExternC(NewFD)) {
9025         NewFD->addAttr(I->second);
9026         ExtnameUndeclaredIdentifiers.erase(I);
9027       } else
9028         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9029             << /*Variable*/0 << NewFD;
9030     }
9031   }
9032 
9033   // Copy the parameter declarations from the declarator D to the function
9034   // declaration NewFD, if they are available.  First scavenge them into Params.
9035   SmallVector<ParmVarDecl*, 16> Params;
9036   unsigned FTIIdx;
9037   if (D.isFunctionDeclarator(FTIIdx)) {
9038     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9039 
9040     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9041     // function that takes no arguments, not a function that takes a
9042     // single void argument.
9043     // We let through "const void" here because Sema::GetTypeForDeclarator
9044     // already checks for that case.
9045     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9046       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9047         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9048         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9049         Param->setDeclContext(NewFD);
9050         Params.push_back(Param);
9051 
9052         if (Param->isInvalidDecl())
9053           NewFD->setInvalidDecl();
9054       }
9055     }
9056 
9057     if (!getLangOpts().CPlusPlus) {
9058       // In C, find all the tag declarations from the prototype and move them
9059       // into the function DeclContext. Remove them from the surrounding tag
9060       // injection context of the function, which is typically but not always
9061       // the TU.
9062       DeclContext *PrototypeTagContext =
9063           getTagInjectionContext(NewFD->getLexicalDeclContext());
9064       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9065         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9066 
9067         // We don't want to reparent enumerators. Look at their parent enum
9068         // instead.
9069         if (!TD) {
9070           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9071             TD = cast<EnumDecl>(ECD->getDeclContext());
9072         }
9073         if (!TD)
9074           continue;
9075         DeclContext *TagDC = TD->getLexicalDeclContext();
9076         if (!TagDC->containsDecl(TD))
9077           continue;
9078         TagDC->removeDecl(TD);
9079         TD->setDeclContext(NewFD);
9080         NewFD->addDecl(TD);
9081 
9082         // Preserve the lexical DeclContext if it is not the surrounding tag
9083         // injection context of the FD. In this example, the semantic context of
9084         // E will be f and the lexical context will be S, while both the
9085         // semantic and lexical contexts of S will be f:
9086         //   void f(struct S { enum E { a } f; } s);
9087         if (TagDC != PrototypeTagContext)
9088           TD->setLexicalDeclContext(TagDC);
9089       }
9090     }
9091   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9092     // When we're declaring a function with a typedef, typeof, etc as in the
9093     // following example, we'll need to synthesize (unnamed)
9094     // parameters for use in the declaration.
9095     //
9096     // @code
9097     // typedef void fn(int);
9098     // fn f;
9099     // @endcode
9100 
9101     // Synthesize a parameter for each argument type.
9102     for (const auto &AI : FT->param_types()) {
9103       ParmVarDecl *Param =
9104           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9105       Param->setScopeInfo(0, Params.size());
9106       Params.push_back(Param);
9107     }
9108   } else {
9109     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9110            "Should not need args for typedef of non-prototype fn");
9111   }
9112 
9113   // Finally, we know we have the right number of parameters, install them.
9114   NewFD->setParams(Params);
9115 
9116   if (D.getDeclSpec().isNoreturnSpecified())
9117     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9118                                            D.getDeclSpec().getNoreturnSpecLoc(),
9119                                            AttributeCommonInfo::AS_Keyword));
9120 
9121   // Functions returning a variably modified type violate C99 6.7.5.2p2
9122   // because all functions have linkage.
9123   if (!NewFD->isInvalidDecl() &&
9124       NewFD->getReturnType()->isVariablyModifiedType()) {
9125     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9126     NewFD->setInvalidDecl();
9127   }
9128 
9129   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9130   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9131       !NewFD->hasAttr<SectionAttr>())
9132     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9133         Context, PragmaClangTextSection.SectionName,
9134         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9135 
9136   // Apply an implicit SectionAttr if #pragma code_seg is active.
9137   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9138       !NewFD->hasAttr<SectionAttr>()) {
9139     NewFD->addAttr(SectionAttr::CreateImplicit(
9140         Context, CodeSegStack.CurrentValue->getString(),
9141         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9142         SectionAttr::Declspec_allocate));
9143     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9144                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9145                          ASTContext::PSF_Read,
9146                      NewFD))
9147       NewFD->dropAttr<SectionAttr>();
9148   }
9149 
9150   // Apply an implicit CodeSegAttr from class declspec or
9151   // apply an implicit SectionAttr from #pragma code_seg if active.
9152   if (!NewFD->hasAttr<CodeSegAttr>()) {
9153     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9154                                                                  D.isFunctionDefinition())) {
9155       NewFD->addAttr(SAttr);
9156     }
9157   }
9158 
9159   // Handle attributes.
9160   ProcessDeclAttributes(S, NewFD, D);
9161 
9162   if (getLangOpts().OpenCL) {
9163     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9164     // type declaration will generate a compilation error.
9165     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9166     if (AddressSpace != LangAS::Default) {
9167       Diag(NewFD->getLocation(),
9168            diag::err_opencl_return_value_with_address_space);
9169       NewFD->setInvalidDecl();
9170     }
9171   }
9172 
9173   if (!getLangOpts().CPlusPlus) {
9174     // Perform semantic checking on the function declaration.
9175     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9176       CheckMain(NewFD, D.getDeclSpec());
9177 
9178     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9179       CheckMSVCRTEntryPoint(NewFD);
9180 
9181     if (!NewFD->isInvalidDecl())
9182       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9183                                                   isMemberSpecialization));
9184     else if (!Previous.empty())
9185       // Recover gracefully from an invalid redeclaration.
9186       D.setRedeclaration(true);
9187     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9188             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9189            "previous declaration set still overloaded");
9190 
9191     // Diagnose no-prototype function declarations with calling conventions that
9192     // don't support variadic calls. Only do this in C and do it after merging
9193     // possibly prototyped redeclarations.
9194     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9195     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9196       CallingConv CC = FT->getExtInfo().getCC();
9197       if (!supportsVariadicCall(CC)) {
9198         // Windows system headers sometimes accidentally use stdcall without
9199         // (void) parameters, so we relax this to a warning.
9200         int DiagID =
9201             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9202         Diag(NewFD->getLocation(), DiagID)
9203             << FunctionType::getNameForCallConv(CC);
9204       }
9205     }
9206 
9207    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9208        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9209      checkNonTrivialCUnion(NewFD->getReturnType(),
9210                            NewFD->getReturnTypeSourceRange().getBegin(),
9211                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9212   } else {
9213     // C++11 [replacement.functions]p3:
9214     //  The program's definitions shall not be specified as inline.
9215     //
9216     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9217     //
9218     // Suppress the diagnostic if the function is __attribute__((used)), since
9219     // that forces an external definition to be emitted.
9220     if (D.getDeclSpec().isInlineSpecified() &&
9221         NewFD->isReplaceableGlobalAllocationFunction() &&
9222         !NewFD->hasAttr<UsedAttr>())
9223       Diag(D.getDeclSpec().getInlineSpecLoc(),
9224            diag::ext_operator_new_delete_declared_inline)
9225         << NewFD->getDeclName();
9226 
9227     // If the declarator is a template-id, translate the parser's template
9228     // argument list into our AST format.
9229     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9230       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9231       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9232       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9233       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9234                                          TemplateId->NumArgs);
9235       translateTemplateArguments(TemplateArgsPtr,
9236                                  TemplateArgs);
9237 
9238       HasExplicitTemplateArgs = true;
9239 
9240       if (NewFD->isInvalidDecl()) {
9241         HasExplicitTemplateArgs = false;
9242       } else if (FunctionTemplate) {
9243         // Function template with explicit template arguments.
9244         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9245           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9246 
9247         HasExplicitTemplateArgs = false;
9248       } else {
9249         assert((isFunctionTemplateSpecialization ||
9250                 D.getDeclSpec().isFriendSpecified()) &&
9251                "should have a 'template<>' for this decl");
9252         // "friend void foo<>(int);" is an implicit specialization decl.
9253         isFunctionTemplateSpecialization = true;
9254       }
9255     } else if (isFriend && isFunctionTemplateSpecialization) {
9256       // This combination is only possible in a recovery case;  the user
9257       // wrote something like:
9258       //   template <> friend void foo(int);
9259       // which we're recovering from as if the user had written:
9260       //   friend void foo<>(int);
9261       // Go ahead and fake up a template id.
9262       HasExplicitTemplateArgs = true;
9263       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9264       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9265     }
9266 
9267     // We do not add HD attributes to specializations here because
9268     // they may have different constexpr-ness compared to their
9269     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9270     // may end up with different effective targets. Instead, a
9271     // specialization inherits its target attributes from its template
9272     // in the CheckFunctionTemplateSpecialization() call below.
9273     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9274       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9275 
9276     // If it's a friend (and only if it's a friend), it's possible
9277     // that either the specialized function type or the specialized
9278     // template is dependent, and therefore matching will fail.  In
9279     // this case, don't check the specialization yet.
9280     bool InstantiationDependent = false;
9281     if (isFunctionTemplateSpecialization && isFriend &&
9282         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9283          TemplateSpecializationType::anyDependentTemplateArguments(
9284             TemplateArgs,
9285             InstantiationDependent))) {
9286       assert(HasExplicitTemplateArgs &&
9287              "friend function specialization without template args");
9288       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9289                                                        Previous))
9290         NewFD->setInvalidDecl();
9291     } else if (isFunctionTemplateSpecialization) {
9292       if (CurContext->isDependentContext() && CurContext->isRecord()
9293           && !isFriend) {
9294         isDependentClassScopeExplicitSpecialization = true;
9295       } else if (!NewFD->isInvalidDecl() &&
9296                  CheckFunctionTemplateSpecialization(
9297                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9298                      Previous))
9299         NewFD->setInvalidDecl();
9300 
9301       // C++ [dcl.stc]p1:
9302       //   A storage-class-specifier shall not be specified in an explicit
9303       //   specialization (14.7.3)
9304       FunctionTemplateSpecializationInfo *Info =
9305           NewFD->getTemplateSpecializationInfo();
9306       if (Info && SC != SC_None) {
9307         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9308           Diag(NewFD->getLocation(),
9309                diag::err_explicit_specialization_inconsistent_storage_class)
9310             << SC
9311             << FixItHint::CreateRemoval(
9312                                       D.getDeclSpec().getStorageClassSpecLoc());
9313 
9314         else
9315           Diag(NewFD->getLocation(),
9316                diag::ext_explicit_specialization_storage_class)
9317             << FixItHint::CreateRemoval(
9318                                       D.getDeclSpec().getStorageClassSpecLoc());
9319       }
9320     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9321       if (CheckMemberSpecialization(NewFD, Previous))
9322           NewFD->setInvalidDecl();
9323     }
9324 
9325     // Perform semantic checking on the function declaration.
9326     if (!isDependentClassScopeExplicitSpecialization) {
9327       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9328         CheckMain(NewFD, D.getDeclSpec());
9329 
9330       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9331         CheckMSVCRTEntryPoint(NewFD);
9332 
9333       if (!NewFD->isInvalidDecl())
9334         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9335                                                     isMemberSpecialization));
9336       else if (!Previous.empty())
9337         // Recover gracefully from an invalid redeclaration.
9338         D.setRedeclaration(true);
9339     }
9340 
9341     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9342             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9343            "previous declaration set still overloaded");
9344 
9345     NamedDecl *PrincipalDecl = (FunctionTemplate
9346                                 ? cast<NamedDecl>(FunctionTemplate)
9347                                 : NewFD);
9348 
9349     if (isFriend && NewFD->getPreviousDecl()) {
9350       AccessSpecifier Access = AS_public;
9351       if (!NewFD->isInvalidDecl())
9352         Access = NewFD->getPreviousDecl()->getAccess();
9353 
9354       NewFD->setAccess(Access);
9355       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9356     }
9357 
9358     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9359         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9360       PrincipalDecl->setNonMemberOperator();
9361 
9362     // If we have a function template, check the template parameter
9363     // list. This will check and merge default template arguments.
9364     if (FunctionTemplate) {
9365       FunctionTemplateDecl *PrevTemplate =
9366                                      FunctionTemplate->getPreviousDecl();
9367       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9368                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9369                                     : nullptr,
9370                             D.getDeclSpec().isFriendSpecified()
9371                               ? (D.isFunctionDefinition()
9372                                    ? TPC_FriendFunctionTemplateDefinition
9373                                    : TPC_FriendFunctionTemplate)
9374                               : (D.getCXXScopeSpec().isSet() &&
9375                                  DC && DC->isRecord() &&
9376                                  DC->isDependentContext())
9377                                   ? TPC_ClassTemplateMember
9378                                   : TPC_FunctionTemplate);
9379     }
9380 
9381     if (NewFD->isInvalidDecl()) {
9382       // Ignore all the rest of this.
9383     } else if (!D.isRedeclaration()) {
9384       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9385                                        AddToScope };
9386       // Fake up an access specifier if it's supposed to be a class member.
9387       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9388         NewFD->setAccess(AS_public);
9389 
9390       // Qualified decls generally require a previous declaration.
9391       if (D.getCXXScopeSpec().isSet()) {
9392         // ...with the major exception of templated-scope or
9393         // dependent-scope friend declarations.
9394 
9395         // TODO: we currently also suppress this check in dependent
9396         // contexts because (1) the parameter depth will be off when
9397         // matching friend templates and (2) we might actually be
9398         // selecting a friend based on a dependent factor.  But there
9399         // are situations where these conditions don't apply and we
9400         // can actually do this check immediately.
9401         //
9402         // Unless the scope is dependent, it's always an error if qualified
9403         // redeclaration lookup found nothing at all. Diagnose that now;
9404         // nothing will diagnose that error later.
9405         if (isFriend &&
9406             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9407              (!Previous.empty() && CurContext->isDependentContext()))) {
9408           // ignore these
9409         } else {
9410           // The user tried to provide an out-of-line definition for a
9411           // function that is a member of a class or namespace, but there
9412           // was no such member function declared (C++ [class.mfct]p2,
9413           // C++ [namespace.memdef]p2). For example:
9414           //
9415           // class X {
9416           //   void f() const;
9417           // };
9418           //
9419           // void X::f() { } // ill-formed
9420           //
9421           // Complain about this problem, and attempt to suggest close
9422           // matches (e.g., those that differ only in cv-qualifiers and
9423           // whether the parameter types are references).
9424 
9425           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9426                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9427             AddToScope = ExtraArgs.AddToScope;
9428             return Result;
9429           }
9430         }
9431 
9432         // Unqualified local friend declarations are required to resolve
9433         // to something.
9434       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9435         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9436                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9437           AddToScope = ExtraArgs.AddToScope;
9438           return Result;
9439         }
9440       }
9441     } else if (!D.isFunctionDefinition() &&
9442                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9443                !isFriend && !isFunctionTemplateSpecialization &&
9444                !isMemberSpecialization) {
9445       // An out-of-line member function declaration must also be a
9446       // definition (C++ [class.mfct]p2).
9447       // Note that this is not the case for explicit specializations of
9448       // function templates or member functions of class templates, per
9449       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9450       // extension for compatibility with old SWIG code which likes to
9451       // generate them.
9452       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9453         << D.getCXXScopeSpec().getRange();
9454     }
9455   }
9456 
9457   ProcessPragmaWeak(S, NewFD);
9458   checkAttributesAfterMerging(*this, *NewFD);
9459 
9460   AddKnownFunctionAttributes(NewFD);
9461 
9462   if (NewFD->hasAttr<OverloadableAttr>() &&
9463       !NewFD->getType()->getAs<FunctionProtoType>()) {
9464     Diag(NewFD->getLocation(),
9465          diag::err_attribute_overloadable_no_prototype)
9466       << NewFD;
9467 
9468     // Turn this into a variadic function with no parameters.
9469     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9470     FunctionProtoType::ExtProtoInfo EPI(
9471         Context.getDefaultCallingConvention(true, false));
9472     EPI.Variadic = true;
9473     EPI.ExtInfo = FT->getExtInfo();
9474 
9475     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9476     NewFD->setType(R);
9477   }
9478 
9479   // If there's a #pragma GCC visibility in scope, and this isn't a class
9480   // member, set the visibility of this function.
9481   if (!DC->isRecord() && NewFD->isExternallyVisible())
9482     AddPushedVisibilityAttribute(NewFD);
9483 
9484   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9485   // marking the function.
9486   AddCFAuditedAttribute(NewFD);
9487 
9488   // If this is a function definition, check if we have to apply optnone due to
9489   // a pragma.
9490   if(D.isFunctionDefinition())
9491     AddRangeBasedOptnone(NewFD);
9492 
9493   // If this is the first declaration of an extern C variable, update
9494   // the map of such variables.
9495   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9496       isIncompleteDeclExternC(*this, NewFD))
9497     RegisterLocallyScopedExternCDecl(NewFD, S);
9498 
9499   // Set this FunctionDecl's range up to the right paren.
9500   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9501 
9502   if (D.isRedeclaration() && !Previous.empty()) {
9503     NamedDecl *Prev = Previous.getRepresentativeDecl();
9504     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9505                                    isMemberSpecialization ||
9506                                        isFunctionTemplateSpecialization,
9507                                    D.isFunctionDefinition());
9508   }
9509 
9510   if (getLangOpts().CUDA) {
9511     IdentifierInfo *II = NewFD->getIdentifier();
9512     if (II && II->isStr(getCudaConfigureFuncName()) &&
9513         !NewFD->isInvalidDecl() &&
9514         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9515       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9516         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9517             << getCudaConfigureFuncName();
9518       Context.setcudaConfigureCallDecl(NewFD);
9519     }
9520 
9521     // Variadic functions, other than a *declaration* of printf, are not allowed
9522     // in device-side CUDA code, unless someone passed
9523     // -fcuda-allow-variadic-functions.
9524     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9525         (NewFD->hasAttr<CUDADeviceAttr>() ||
9526          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9527         !(II && II->isStr("printf") && NewFD->isExternC() &&
9528           !D.isFunctionDefinition())) {
9529       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9530     }
9531   }
9532 
9533   MarkUnusedFileScopedDecl(NewFD);
9534 
9535 
9536 
9537   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9538     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9539     if ((getLangOpts().OpenCLVersion >= 120)
9540         && (SC == SC_Static)) {
9541       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9542       D.setInvalidType();
9543     }
9544 
9545     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9546     if (!NewFD->getReturnType()->isVoidType()) {
9547       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9548       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9549           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9550                                 : FixItHint());
9551       D.setInvalidType();
9552     }
9553 
9554     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9555     for (auto Param : NewFD->parameters())
9556       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9557 
9558     if (getLangOpts().OpenCLCPlusPlus) {
9559       if (DC->isRecord()) {
9560         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9561         D.setInvalidType();
9562       }
9563       if (FunctionTemplate) {
9564         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9565         D.setInvalidType();
9566       }
9567     }
9568   }
9569 
9570   if (getLangOpts().CPlusPlus) {
9571     if (FunctionTemplate) {
9572       if (NewFD->isInvalidDecl())
9573         FunctionTemplate->setInvalidDecl();
9574       return FunctionTemplate;
9575     }
9576 
9577     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9578       CompleteMemberSpecialization(NewFD, Previous);
9579   }
9580 
9581   for (const ParmVarDecl *Param : NewFD->parameters()) {
9582     QualType PT = Param->getType();
9583 
9584     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9585     // types.
9586     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9587       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9588         QualType ElemTy = PipeTy->getElementType();
9589           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9590             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9591             D.setInvalidType();
9592           }
9593       }
9594     }
9595   }
9596 
9597   // Here we have an function template explicit specialization at class scope.
9598   // The actual specialization will be postponed to template instatiation
9599   // time via the ClassScopeFunctionSpecializationDecl node.
9600   if (isDependentClassScopeExplicitSpecialization) {
9601     ClassScopeFunctionSpecializationDecl *NewSpec =
9602                          ClassScopeFunctionSpecializationDecl::Create(
9603                                 Context, CurContext, NewFD->getLocation(),
9604                                 cast<CXXMethodDecl>(NewFD),
9605                                 HasExplicitTemplateArgs, TemplateArgs);
9606     CurContext->addDecl(NewSpec);
9607     AddToScope = false;
9608   }
9609 
9610   // Diagnose availability attributes. Availability cannot be used on functions
9611   // that are run during load/unload.
9612   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9613     if (NewFD->hasAttr<ConstructorAttr>()) {
9614       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9615           << 1;
9616       NewFD->dropAttr<AvailabilityAttr>();
9617     }
9618     if (NewFD->hasAttr<DestructorAttr>()) {
9619       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9620           << 2;
9621       NewFD->dropAttr<AvailabilityAttr>();
9622     }
9623   }
9624 
9625   // Diagnose no_builtin attribute on function declaration that are not a
9626   // definition.
9627   // FIXME: We should really be doing this in
9628   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9629   // the FunctionDecl and at this point of the code
9630   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9631   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9632   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9633     switch (D.getFunctionDefinitionKind()) {
9634     case FDK_Defaulted:
9635     case FDK_Deleted:
9636       Diag(NBA->getLocation(),
9637            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9638           << NBA->getSpelling();
9639       break;
9640     case FDK_Declaration:
9641       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9642           << NBA->getSpelling();
9643       break;
9644     case FDK_Definition:
9645       break;
9646     }
9647 
9648   return NewFD;
9649 }
9650 
9651 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9652 /// when __declspec(code_seg) "is applied to a class, all member functions of
9653 /// the class and nested classes -- this includes compiler-generated special
9654 /// member functions -- are put in the specified segment."
9655 /// The actual behavior is a little more complicated. The Microsoft compiler
9656 /// won't check outer classes if there is an active value from #pragma code_seg.
9657 /// The CodeSeg is always applied from the direct parent but only from outer
9658 /// classes when the #pragma code_seg stack is empty. See:
9659 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9660 /// available since MS has removed the page.
9661 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9662   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9663   if (!Method)
9664     return nullptr;
9665   const CXXRecordDecl *Parent = Method->getParent();
9666   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9667     Attr *NewAttr = SAttr->clone(S.getASTContext());
9668     NewAttr->setImplicit(true);
9669     return NewAttr;
9670   }
9671 
9672   // The Microsoft compiler won't check outer classes for the CodeSeg
9673   // when the #pragma code_seg stack is active.
9674   if (S.CodeSegStack.CurrentValue)
9675    return nullptr;
9676 
9677   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9678     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9679       Attr *NewAttr = SAttr->clone(S.getASTContext());
9680       NewAttr->setImplicit(true);
9681       return NewAttr;
9682     }
9683   }
9684   return nullptr;
9685 }
9686 
9687 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9688 /// containing class. Otherwise it will return implicit SectionAttr if the
9689 /// function is a definition and there is an active value on CodeSegStack
9690 /// (from the current #pragma code-seg value).
9691 ///
9692 /// \param FD Function being declared.
9693 /// \param IsDefinition Whether it is a definition or just a declarartion.
9694 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9695 ///          nullptr if no attribute should be added.
9696 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9697                                                        bool IsDefinition) {
9698   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9699     return A;
9700   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9701       CodeSegStack.CurrentValue)
9702     return SectionAttr::CreateImplicit(
9703         getASTContext(), CodeSegStack.CurrentValue->getString(),
9704         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9705         SectionAttr::Declspec_allocate);
9706   return nullptr;
9707 }
9708 
9709 /// Determines if we can perform a correct type check for \p D as a
9710 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9711 /// best-effort check.
9712 ///
9713 /// \param NewD The new declaration.
9714 /// \param OldD The old declaration.
9715 /// \param NewT The portion of the type of the new declaration to check.
9716 /// \param OldT The portion of the type of the old declaration to check.
9717 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9718                                           QualType NewT, QualType OldT) {
9719   if (!NewD->getLexicalDeclContext()->isDependentContext())
9720     return true;
9721 
9722   // For dependently-typed local extern declarations and friends, we can't
9723   // perform a correct type check in general until instantiation:
9724   //
9725   //   int f();
9726   //   template<typename T> void g() { T f(); }
9727   //
9728   // (valid if g() is only instantiated with T = int).
9729   if (NewT->isDependentType() &&
9730       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9731     return false;
9732 
9733   // Similarly, if the previous declaration was a dependent local extern
9734   // declaration, we don't really know its type yet.
9735   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9736     return false;
9737 
9738   return true;
9739 }
9740 
9741 /// Checks if the new declaration declared in dependent context must be
9742 /// put in the same redeclaration chain as the specified declaration.
9743 ///
9744 /// \param D Declaration that is checked.
9745 /// \param PrevDecl Previous declaration found with proper lookup method for the
9746 ///                 same declaration name.
9747 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9748 ///          belongs to.
9749 ///
9750 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9751   if (!D->getLexicalDeclContext()->isDependentContext())
9752     return true;
9753 
9754   // Don't chain dependent friend function definitions until instantiation, to
9755   // permit cases like
9756   //
9757   //   void func();
9758   //   template<typename T> class C1 { friend void func() {} };
9759   //   template<typename T> class C2 { friend void func() {} };
9760   //
9761   // ... which is valid if only one of C1 and C2 is ever instantiated.
9762   //
9763   // FIXME: This need only apply to function definitions. For now, we proxy
9764   // this by checking for a file-scope function. We do not want this to apply
9765   // to friend declarations nominating member functions, because that gets in
9766   // the way of access checks.
9767   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9768     return false;
9769 
9770   auto *VD = dyn_cast<ValueDecl>(D);
9771   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9772   return !VD || !PrevVD ||
9773          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9774                                         PrevVD->getType());
9775 }
9776 
9777 /// Check the target attribute of the function for MultiVersion
9778 /// validity.
9779 ///
9780 /// Returns true if there was an error, false otherwise.
9781 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9782   const auto *TA = FD->getAttr<TargetAttr>();
9783   assert(TA && "MultiVersion Candidate requires a target attribute");
9784   ParsedTargetAttr ParseInfo = TA->parse();
9785   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9786   enum ErrType { Feature = 0, Architecture = 1 };
9787 
9788   if (!ParseInfo.Architecture.empty() &&
9789       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9790     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9791         << Architecture << ParseInfo.Architecture;
9792     return true;
9793   }
9794 
9795   for (const auto &Feat : ParseInfo.Features) {
9796     auto BareFeat = StringRef{Feat}.substr(1);
9797     if (Feat[0] == '-') {
9798       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9799           << Feature << ("no-" + BareFeat).str();
9800       return true;
9801     }
9802 
9803     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9804         !TargetInfo.isValidFeatureName(BareFeat)) {
9805       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9806           << Feature << BareFeat;
9807       return true;
9808     }
9809   }
9810   return false;
9811 }
9812 
9813 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9814                                          MultiVersionKind MVType) {
9815   for (const Attr *A : FD->attrs()) {
9816     switch (A->getKind()) {
9817     case attr::CPUDispatch:
9818     case attr::CPUSpecific:
9819       if (MVType != MultiVersionKind::CPUDispatch &&
9820           MVType != MultiVersionKind::CPUSpecific)
9821         return true;
9822       break;
9823     case attr::Target:
9824       if (MVType != MultiVersionKind::Target)
9825         return true;
9826       break;
9827     default:
9828       return true;
9829     }
9830   }
9831   return false;
9832 }
9833 
9834 bool Sema::areMultiversionVariantFunctionsCompatible(
9835     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9836     const PartialDiagnostic &NoProtoDiagID,
9837     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9838     const PartialDiagnosticAt &NoSupportDiagIDAt,
9839     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9840     bool ConstexprSupported, bool CLinkageMayDiffer) {
9841   enum DoesntSupport {
9842     FuncTemplates = 0,
9843     VirtFuncs = 1,
9844     DeducedReturn = 2,
9845     Constructors = 3,
9846     Destructors = 4,
9847     DeletedFuncs = 5,
9848     DefaultedFuncs = 6,
9849     ConstexprFuncs = 7,
9850     ConstevalFuncs = 8,
9851   };
9852   enum Different {
9853     CallingConv = 0,
9854     ReturnType = 1,
9855     ConstexprSpec = 2,
9856     InlineSpec = 3,
9857     StorageClass = 4,
9858     Linkage = 5,
9859   };
9860 
9861   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9862       !OldFD->getType()->getAs<FunctionProtoType>()) {
9863     Diag(OldFD->getLocation(), NoProtoDiagID);
9864     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9865     return true;
9866   }
9867 
9868   if (NoProtoDiagID.getDiagID() != 0 &&
9869       !NewFD->getType()->getAs<FunctionProtoType>())
9870     return Diag(NewFD->getLocation(), NoProtoDiagID);
9871 
9872   if (!TemplatesSupported &&
9873       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9874     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9875            << FuncTemplates;
9876 
9877   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9878     if (NewCXXFD->isVirtual())
9879       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9880              << VirtFuncs;
9881 
9882     if (isa<CXXConstructorDecl>(NewCXXFD))
9883       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9884              << Constructors;
9885 
9886     if (isa<CXXDestructorDecl>(NewCXXFD))
9887       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9888              << Destructors;
9889   }
9890 
9891   if (NewFD->isDeleted())
9892     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9893            << DeletedFuncs;
9894 
9895   if (NewFD->isDefaulted())
9896     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9897            << DefaultedFuncs;
9898 
9899   if (!ConstexprSupported && NewFD->isConstexpr())
9900     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9901            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9902 
9903   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9904   const auto *NewType = cast<FunctionType>(NewQType);
9905   QualType NewReturnType = NewType->getReturnType();
9906 
9907   if (NewReturnType->isUndeducedType())
9908     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9909            << DeducedReturn;
9910 
9911   // Ensure the return type is identical.
9912   if (OldFD) {
9913     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9914     const auto *OldType = cast<FunctionType>(OldQType);
9915     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9916     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9917 
9918     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9919       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9920 
9921     QualType OldReturnType = OldType->getReturnType();
9922 
9923     if (OldReturnType != NewReturnType)
9924       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9925 
9926     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9927       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9928 
9929     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9930       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9931 
9932     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9933       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9934 
9935     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9936       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9937 
9938     if (CheckEquivalentExceptionSpec(
9939             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9940             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9941       return true;
9942   }
9943   return false;
9944 }
9945 
9946 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9947                                              const FunctionDecl *NewFD,
9948                                              bool CausesMV,
9949                                              MultiVersionKind MVType) {
9950   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9951     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9952     if (OldFD)
9953       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9954     return true;
9955   }
9956 
9957   bool IsCPUSpecificCPUDispatchMVType =
9958       MVType == MultiVersionKind::CPUDispatch ||
9959       MVType == MultiVersionKind::CPUSpecific;
9960 
9961   // For now, disallow all other attributes.  These should be opt-in, but
9962   // an analysis of all of them is a future FIXME.
9963   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9964     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9965         << IsCPUSpecificCPUDispatchMVType;
9966     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9967     return true;
9968   }
9969 
9970   if (HasNonMultiVersionAttributes(NewFD, MVType))
9971     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9972            << IsCPUSpecificCPUDispatchMVType;
9973 
9974   // Only allow transition to MultiVersion if it hasn't been used.
9975   if (OldFD && CausesMV && OldFD->isUsed(false))
9976     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9977 
9978   return S.areMultiversionVariantFunctionsCompatible(
9979       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9980       PartialDiagnosticAt(NewFD->getLocation(),
9981                           S.PDiag(diag::note_multiversioning_caused_here)),
9982       PartialDiagnosticAt(NewFD->getLocation(),
9983                           S.PDiag(diag::err_multiversion_doesnt_support)
9984                               << IsCPUSpecificCPUDispatchMVType),
9985       PartialDiagnosticAt(NewFD->getLocation(),
9986                           S.PDiag(diag::err_multiversion_diff)),
9987       /*TemplatesSupported=*/false,
9988       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9989       /*CLinkageMayDiffer=*/false);
9990 }
9991 
9992 /// Check the validity of a multiversion function declaration that is the
9993 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9994 ///
9995 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9996 ///
9997 /// Returns true if there was an error, false otherwise.
9998 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9999                                            MultiVersionKind MVType,
10000                                            const TargetAttr *TA) {
10001   assert(MVType != MultiVersionKind::None &&
10002          "Function lacks multiversion attribute");
10003 
10004   // Target only causes MV if it is default, otherwise this is a normal
10005   // function.
10006   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10007     return false;
10008 
10009   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10010     FD->setInvalidDecl();
10011     return true;
10012   }
10013 
10014   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10015     FD->setInvalidDecl();
10016     return true;
10017   }
10018 
10019   FD->setIsMultiVersion();
10020   return false;
10021 }
10022 
10023 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10024   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10025     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10026       return true;
10027   }
10028 
10029   return false;
10030 }
10031 
10032 static bool CheckTargetCausesMultiVersioning(
10033     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10034     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10035     LookupResult &Previous) {
10036   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10037   ParsedTargetAttr NewParsed = NewTA->parse();
10038   // Sort order doesn't matter, it just needs to be consistent.
10039   llvm::sort(NewParsed.Features);
10040 
10041   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10042   // to change, this is a simple redeclaration.
10043   if (!NewTA->isDefaultVersion() &&
10044       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10045     return false;
10046 
10047   // Otherwise, this decl causes MultiVersioning.
10048   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10049     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10050     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10051     NewFD->setInvalidDecl();
10052     return true;
10053   }
10054 
10055   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10056                                        MultiVersionKind::Target)) {
10057     NewFD->setInvalidDecl();
10058     return true;
10059   }
10060 
10061   if (CheckMultiVersionValue(S, NewFD)) {
10062     NewFD->setInvalidDecl();
10063     return true;
10064   }
10065 
10066   // If this is 'default', permit the forward declaration.
10067   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10068     Redeclaration = true;
10069     OldDecl = OldFD;
10070     OldFD->setIsMultiVersion();
10071     NewFD->setIsMultiVersion();
10072     return false;
10073   }
10074 
10075   if (CheckMultiVersionValue(S, OldFD)) {
10076     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10077     NewFD->setInvalidDecl();
10078     return true;
10079   }
10080 
10081   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10082 
10083   if (OldParsed == NewParsed) {
10084     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10085     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10086     NewFD->setInvalidDecl();
10087     return true;
10088   }
10089 
10090   for (const auto *FD : OldFD->redecls()) {
10091     const auto *CurTA = FD->getAttr<TargetAttr>();
10092     // We allow forward declarations before ANY multiversioning attributes, but
10093     // nothing after the fact.
10094     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10095         (!CurTA || CurTA->isInherited())) {
10096       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10097           << 0;
10098       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10099       NewFD->setInvalidDecl();
10100       return true;
10101     }
10102   }
10103 
10104   OldFD->setIsMultiVersion();
10105   NewFD->setIsMultiVersion();
10106   Redeclaration = false;
10107   MergeTypeWithPrevious = false;
10108   OldDecl = nullptr;
10109   Previous.clear();
10110   return false;
10111 }
10112 
10113 /// Check the validity of a new function declaration being added to an existing
10114 /// multiversioned declaration collection.
10115 static bool CheckMultiVersionAdditionalDecl(
10116     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10117     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10118     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10119     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10120     LookupResult &Previous) {
10121 
10122   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10123   // Disallow mixing of multiversioning types.
10124   if ((OldMVType == MultiVersionKind::Target &&
10125        NewMVType != MultiVersionKind::Target) ||
10126       (NewMVType == MultiVersionKind::Target &&
10127        OldMVType != MultiVersionKind::Target)) {
10128     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10129     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10130     NewFD->setInvalidDecl();
10131     return true;
10132   }
10133 
10134   ParsedTargetAttr NewParsed;
10135   if (NewTA) {
10136     NewParsed = NewTA->parse();
10137     llvm::sort(NewParsed.Features);
10138   }
10139 
10140   bool UseMemberUsingDeclRules =
10141       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10142 
10143   // Next, check ALL non-overloads to see if this is a redeclaration of a
10144   // previous member of the MultiVersion set.
10145   for (NamedDecl *ND : Previous) {
10146     FunctionDecl *CurFD = ND->getAsFunction();
10147     if (!CurFD)
10148       continue;
10149     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10150       continue;
10151 
10152     if (NewMVType == MultiVersionKind::Target) {
10153       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10154       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10155         NewFD->setIsMultiVersion();
10156         Redeclaration = true;
10157         OldDecl = ND;
10158         return false;
10159       }
10160 
10161       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10162       if (CurParsed == NewParsed) {
10163         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10164         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10165         NewFD->setInvalidDecl();
10166         return true;
10167       }
10168     } else {
10169       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10170       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10171       // Handle CPUDispatch/CPUSpecific versions.
10172       // Only 1 CPUDispatch function is allowed, this will make it go through
10173       // the redeclaration errors.
10174       if (NewMVType == MultiVersionKind::CPUDispatch &&
10175           CurFD->hasAttr<CPUDispatchAttr>()) {
10176         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10177             std::equal(
10178                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10179                 NewCPUDisp->cpus_begin(),
10180                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10181                   return Cur->getName() == New->getName();
10182                 })) {
10183           NewFD->setIsMultiVersion();
10184           Redeclaration = true;
10185           OldDecl = ND;
10186           return false;
10187         }
10188 
10189         // If the declarations don't match, this is an error condition.
10190         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10191         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10192         NewFD->setInvalidDecl();
10193         return true;
10194       }
10195       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10196 
10197         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10198             std::equal(
10199                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10200                 NewCPUSpec->cpus_begin(),
10201                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10202                   return Cur->getName() == New->getName();
10203                 })) {
10204           NewFD->setIsMultiVersion();
10205           Redeclaration = true;
10206           OldDecl = ND;
10207           return false;
10208         }
10209 
10210         // Only 1 version of CPUSpecific is allowed for each CPU.
10211         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10212           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10213             if (CurII == NewII) {
10214               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10215                   << NewII;
10216               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10217               NewFD->setInvalidDecl();
10218               return true;
10219             }
10220           }
10221         }
10222       }
10223       // If the two decls aren't the same MVType, there is no possible error
10224       // condition.
10225     }
10226   }
10227 
10228   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10229   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10230   // handled in the attribute adding step.
10231   if (NewMVType == MultiVersionKind::Target &&
10232       CheckMultiVersionValue(S, NewFD)) {
10233     NewFD->setInvalidDecl();
10234     return true;
10235   }
10236 
10237   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10238                                        !OldFD->isMultiVersion(), NewMVType)) {
10239     NewFD->setInvalidDecl();
10240     return true;
10241   }
10242 
10243   // Permit forward declarations in the case where these two are compatible.
10244   if (!OldFD->isMultiVersion()) {
10245     OldFD->setIsMultiVersion();
10246     NewFD->setIsMultiVersion();
10247     Redeclaration = true;
10248     OldDecl = OldFD;
10249     return false;
10250   }
10251 
10252   NewFD->setIsMultiVersion();
10253   Redeclaration = false;
10254   MergeTypeWithPrevious = false;
10255   OldDecl = nullptr;
10256   Previous.clear();
10257   return false;
10258 }
10259 
10260 
10261 /// Check the validity of a mulitversion function declaration.
10262 /// Also sets the multiversion'ness' of the function itself.
10263 ///
10264 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10265 ///
10266 /// Returns true if there was an error, false otherwise.
10267 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10268                                       bool &Redeclaration, NamedDecl *&OldDecl,
10269                                       bool &MergeTypeWithPrevious,
10270                                       LookupResult &Previous) {
10271   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10272   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10273   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10274 
10275   // Mixing Multiversioning types is prohibited.
10276   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10277       (NewCPUDisp && NewCPUSpec)) {
10278     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10279     NewFD->setInvalidDecl();
10280     return true;
10281   }
10282 
10283   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10284 
10285   // Main isn't allowed to become a multiversion function, however it IS
10286   // permitted to have 'main' be marked with the 'target' optimization hint.
10287   if (NewFD->isMain()) {
10288     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10289         MVType == MultiVersionKind::CPUDispatch ||
10290         MVType == MultiVersionKind::CPUSpecific) {
10291       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10292       NewFD->setInvalidDecl();
10293       return true;
10294     }
10295     return false;
10296   }
10297 
10298   if (!OldDecl || !OldDecl->getAsFunction() ||
10299       OldDecl->getDeclContext()->getRedeclContext() !=
10300           NewFD->getDeclContext()->getRedeclContext()) {
10301     // If there's no previous declaration, AND this isn't attempting to cause
10302     // multiversioning, this isn't an error condition.
10303     if (MVType == MultiVersionKind::None)
10304       return false;
10305     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10306   }
10307 
10308   FunctionDecl *OldFD = OldDecl->getAsFunction();
10309 
10310   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10311     return false;
10312 
10313   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10314     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10315         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10316     NewFD->setInvalidDecl();
10317     return true;
10318   }
10319 
10320   // Handle the target potentially causes multiversioning case.
10321   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10322     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10323                                             Redeclaration, OldDecl,
10324                                             MergeTypeWithPrevious, Previous);
10325 
10326   // At this point, we have a multiversion function decl (in OldFD) AND an
10327   // appropriate attribute in the current function decl.  Resolve that these are
10328   // still compatible with previous declarations.
10329   return CheckMultiVersionAdditionalDecl(
10330       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10331       OldDecl, MergeTypeWithPrevious, Previous);
10332 }
10333 
10334 /// Perform semantic checking of a new function declaration.
10335 ///
10336 /// Performs semantic analysis of the new function declaration
10337 /// NewFD. This routine performs all semantic checking that does not
10338 /// require the actual declarator involved in the declaration, and is
10339 /// used both for the declaration of functions as they are parsed
10340 /// (called via ActOnDeclarator) and for the declaration of functions
10341 /// that have been instantiated via C++ template instantiation (called
10342 /// via InstantiateDecl).
10343 ///
10344 /// \param IsMemberSpecialization whether this new function declaration is
10345 /// a member specialization (that replaces any definition provided by the
10346 /// previous declaration).
10347 ///
10348 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10349 ///
10350 /// \returns true if the function declaration is a redeclaration.
10351 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10352                                     LookupResult &Previous,
10353                                     bool IsMemberSpecialization) {
10354   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10355          "Variably modified return types are not handled here");
10356 
10357   // Determine whether the type of this function should be merged with
10358   // a previous visible declaration. This never happens for functions in C++,
10359   // and always happens in C if the previous declaration was visible.
10360   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10361                                !Previous.isShadowed();
10362 
10363   bool Redeclaration = false;
10364   NamedDecl *OldDecl = nullptr;
10365   bool MayNeedOverloadableChecks = false;
10366 
10367   // Merge or overload the declaration with an existing declaration of
10368   // the same name, if appropriate.
10369   if (!Previous.empty()) {
10370     // Determine whether NewFD is an overload of PrevDecl or
10371     // a declaration that requires merging. If it's an overload,
10372     // there's no more work to do here; we'll just add the new
10373     // function to the scope.
10374     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10375       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10376       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10377         Redeclaration = true;
10378         OldDecl = Candidate;
10379       }
10380     } else {
10381       MayNeedOverloadableChecks = true;
10382       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10383                             /*NewIsUsingDecl*/ false)) {
10384       case Ovl_Match:
10385         Redeclaration = true;
10386         break;
10387 
10388       case Ovl_NonFunction:
10389         Redeclaration = true;
10390         break;
10391 
10392       case Ovl_Overload:
10393         Redeclaration = false;
10394         break;
10395       }
10396     }
10397   }
10398 
10399   // Check for a previous extern "C" declaration with this name.
10400   if (!Redeclaration &&
10401       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10402     if (!Previous.empty()) {
10403       // This is an extern "C" declaration with the same name as a previous
10404       // declaration, and thus redeclares that entity...
10405       Redeclaration = true;
10406       OldDecl = Previous.getFoundDecl();
10407       MergeTypeWithPrevious = false;
10408 
10409       // ... except in the presence of __attribute__((overloadable)).
10410       if (OldDecl->hasAttr<OverloadableAttr>() ||
10411           NewFD->hasAttr<OverloadableAttr>()) {
10412         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10413           MayNeedOverloadableChecks = true;
10414           Redeclaration = false;
10415           OldDecl = nullptr;
10416         }
10417       }
10418     }
10419   }
10420 
10421   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10422                                 MergeTypeWithPrevious, Previous))
10423     return Redeclaration;
10424 
10425   // C++11 [dcl.constexpr]p8:
10426   //   A constexpr specifier for a non-static member function that is not
10427   //   a constructor declares that member function to be const.
10428   //
10429   // This needs to be delayed until we know whether this is an out-of-line
10430   // definition of a static member function.
10431   //
10432   // This rule is not present in C++1y, so we produce a backwards
10433   // compatibility warning whenever it happens in C++11.
10434   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10435   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10436       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10437       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10438     CXXMethodDecl *OldMD = nullptr;
10439     if (OldDecl)
10440       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10441     if (!OldMD || !OldMD->isStatic()) {
10442       const FunctionProtoType *FPT =
10443         MD->getType()->castAs<FunctionProtoType>();
10444       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10445       EPI.TypeQuals.addConst();
10446       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10447                                           FPT->getParamTypes(), EPI));
10448 
10449       // Warn that we did this, if we're not performing template instantiation.
10450       // In that case, we'll have warned already when the template was defined.
10451       if (!inTemplateInstantiation()) {
10452         SourceLocation AddConstLoc;
10453         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10454                 .IgnoreParens().getAs<FunctionTypeLoc>())
10455           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10456 
10457         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10458           << FixItHint::CreateInsertion(AddConstLoc, " const");
10459       }
10460     }
10461   }
10462 
10463   if (Redeclaration) {
10464     // NewFD and OldDecl represent declarations that need to be
10465     // merged.
10466     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10467       NewFD->setInvalidDecl();
10468       return Redeclaration;
10469     }
10470 
10471     Previous.clear();
10472     Previous.addDecl(OldDecl);
10473 
10474     if (FunctionTemplateDecl *OldTemplateDecl =
10475             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10476       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10477       FunctionTemplateDecl *NewTemplateDecl
10478         = NewFD->getDescribedFunctionTemplate();
10479       assert(NewTemplateDecl && "Template/non-template mismatch");
10480 
10481       // The call to MergeFunctionDecl above may have created some state in
10482       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10483       // can add it as a redeclaration.
10484       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10485 
10486       NewFD->setPreviousDeclaration(OldFD);
10487       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10488       if (NewFD->isCXXClassMember()) {
10489         NewFD->setAccess(OldTemplateDecl->getAccess());
10490         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10491       }
10492 
10493       // If this is an explicit specialization of a member that is a function
10494       // template, mark it as a member specialization.
10495       if (IsMemberSpecialization &&
10496           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10497         NewTemplateDecl->setMemberSpecialization();
10498         assert(OldTemplateDecl->isMemberSpecialization());
10499         // Explicit specializations of a member template do not inherit deleted
10500         // status from the parent member template that they are specializing.
10501         if (OldFD->isDeleted()) {
10502           // FIXME: This assert will not hold in the presence of modules.
10503           assert(OldFD->getCanonicalDecl() == OldFD);
10504           // FIXME: We need an update record for this AST mutation.
10505           OldFD->setDeletedAsWritten(false);
10506         }
10507       }
10508 
10509     } else {
10510       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10511         auto *OldFD = cast<FunctionDecl>(OldDecl);
10512         // This needs to happen first so that 'inline' propagates.
10513         NewFD->setPreviousDeclaration(OldFD);
10514         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10515         if (NewFD->isCXXClassMember())
10516           NewFD->setAccess(OldFD->getAccess());
10517       }
10518     }
10519   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10520              !NewFD->getAttr<OverloadableAttr>()) {
10521     assert((Previous.empty() ||
10522             llvm::any_of(Previous,
10523                          [](const NamedDecl *ND) {
10524                            return ND->hasAttr<OverloadableAttr>();
10525                          })) &&
10526            "Non-redecls shouldn't happen without overloadable present");
10527 
10528     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10529       const auto *FD = dyn_cast<FunctionDecl>(ND);
10530       return FD && !FD->hasAttr<OverloadableAttr>();
10531     });
10532 
10533     if (OtherUnmarkedIter != Previous.end()) {
10534       Diag(NewFD->getLocation(),
10535            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10536       Diag((*OtherUnmarkedIter)->getLocation(),
10537            diag::note_attribute_overloadable_prev_overload)
10538           << false;
10539 
10540       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10541     }
10542   }
10543 
10544   // Semantic checking for this function declaration (in isolation).
10545 
10546   if (getLangOpts().CPlusPlus) {
10547     // C++-specific checks.
10548     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10549       CheckConstructor(Constructor);
10550     } else if (CXXDestructorDecl *Destructor =
10551                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10552       CXXRecordDecl *Record = Destructor->getParent();
10553       QualType ClassType = Context.getTypeDeclType(Record);
10554 
10555       // FIXME: Shouldn't we be able to perform this check even when the class
10556       // type is dependent? Both gcc and edg can handle that.
10557       if (!ClassType->isDependentType()) {
10558         DeclarationName Name
10559           = Context.DeclarationNames.getCXXDestructorName(
10560                                         Context.getCanonicalType(ClassType));
10561         if (NewFD->getDeclName() != Name) {
10562           Diag(NewFD->getLocation(), diag::err_destructor_name);
10563           NewFD->setInvalidDecl();
10564           return Redeclaration;
10565         }
10566       }
10567     } else if (CXXConversionDecl *Conversion
10568                = dyn_cast<CXXConversionDecl>(NewFD)) {
10569       ActOnConversionDeclarator(Conversion);
10570     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10571       if (auto *TD = Guide->getDescribedFunctionTemplate())
10572         CheckDeductionGuideTemplate(TD);
10573 
10574       // A deduction guide is not on the list of entities that can be
10575       // explicitly specialized.
10576       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10577         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10578             << /*explicit specialization*/ 1;
10579     }
10580 
10581     // Find any virtual functions that this function overrides.
10582     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10583       if (!Method->isFunctionTemplateSpecialization() &&
10584           !Method->getDescribedFunctionTemplate() &&
10585           Method->isCanonicalDecl()) {
10586         if (AddOverriddenMethods(Method->getParent(), Method)) {
10587           // If the function was marked as "static", we have a problem.
10588           if (NewFD->getStorageClass() == SC_Static) {
10589             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10590           }
10591         }
10592       }
10593       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10594         // C++2a [class.virtual]p6
10595         // A virtual method shall not have a requires-clause.
10596         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10597              diag::err_constrained_virtual_method);
10598 
10599       if (Method->isStatic())
10600         checkThisInStaticMemberFunctionType(Method);
10601     }
10602 
10603     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10604     if (NewFD->isOverloadedOperator() &&
10605         CheckOverloadedOperatorDeclaration(NewFD)) {
10606       NewFD->setInvalidDecl();
10607       return Redeclaration;
10608     }
10609 
10610     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10611     if (NewFD->getLiteralIdentifier() &&
10612         CheckLiteralOperatorDeclaration(NewFD)) {
10613       NewFD->setInvalidDecl();
10614       return Redeclaration;
10615     }
10616 
10617     // In C++, check default arguments now that we have merged decls. Unless
10618     // the lexical context is the class, because in this case this is done
10619     // during delayed parsing anyway.
10620     if (!CurContext->isRecord())
10621       CheckCXXDefaultArguments(NewFD);
10622 
10623     // If this function declares a builtin function, check the type of this
10624     // declaration against the expected type for the builtin.
10625     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10626       ASTContext::GetBuiltinTypeError Error;
10627       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10628       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10629       // If the type of the builtin differs only in its exception
10630       // specification, that's OK.
10631       // FIXME: If the types do differ in this way, it would be better to
10632       // retain the 'noexcept' form of the type.
10633       if (!T.isNull() &&
10634           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10635                                                             NewFD->getType()))
10636         // The type of this function differs from the type of the builtin,
10637         // so forget about the builtin entirely.
10638         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10639     }
10640 
10641     // If this function is declared as being extern "C", then check to see if
10642     // the function returns a UDT (class, struct, or union type) that is not C
10643     // compatible, and if it does, warn the user.
10644     // But, issue any diagnostic on the first declaration only.
10645     if (Previous.empty() && NewFD->isExternC()) {
10646       QualType R = NewFD->getReturnType();
10647       if (R->isIncompleteType() && !R->isVoidType())
10648         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10649             << NewFD << R;
10650       else if (!R.isPODType(Context) && !R->isVoidType() &&
10651                !R->isObjCObjectPointerType())
10652         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10653     }
10654 
10655     // C++1z [dcl.fct]p6:
10656     //   [...] whether the function has a non-throwing exception-specification
10657     //   [is] part of the function type
10658     //
10659     // This results in an ABI break between C++14 and C++17 for functions whose
10660     // declared type includes an exception-specification in a parameter or
10661     // return type. (Exception specifications on the function itself are OK in
10662     // most cases, and exception specifications are not permitted in most other
10663     // contexts where they could make it into a mangling.)
10664     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10665       auto HasNoexcept = [&](QualType T) -> bool {
10666         // Strip off declarator chunks that could be between us and a function
10667         // type. We don't need to look far, exception specifications are very
10668         // restricted prior to C++17.
10669         if (auto *RT = T->getAs<ReferenceType>())
10670           T = RT->getPointeeType();
10671         else if (T->isAnyPointerType())
10672           T = T->getPointeeType();
10673         else if (auto *MPT = T->getAs<MemberPointerType>())
10674           T = MPT->getPointeeType();
10675         if (auto *FPT = T->getAs<FunctionProtoType>())
10676           if (FPT->isNothrow())
10677             return true;
10678         return false;
10679       };
10680 
10681       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10682       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10683       for (QualType T : FPT->param_types())
10684         AnyNoexcept |= HasNoexcept(T);
10685       if (AnyNoexcept)
10686         Diag(NewFD->getLocation(),
10687              diag::warn_cxx17_compat_exception_spec_in_signature)
10688             << NewFD;
10689     }
10690 
10691     if (!Redeclaration && LangOpts.CUDA)
10692       checkCUDATargetOverload(NewFD, Previous);
10693   }
10694   return Redeclaration;
10695 }
10696 
10697 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10698   // C++11 [basic.start.main]p3:
10699   //   A program that [...] declares main to be inline, static or
10700   //   constexpr is ill-formed.
10701   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10702   //   appear in a declaration of main.
10703   // static main is not an error under C99, but we should warn about it.
10704   // We accept _Noreturn main as an extension.
10705   if (FD->getStorageClass() == SC_Static)
10706     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10707          ? diag::err_static_main : diag::warn_static_main)
10708       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10709   if (FD->isInlineSpecified())
10710     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10711       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10712   if (DS.isNoreturnSpecified()) {
10713     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10714     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10715     Diag(NoreturnLoc, diag::ext_noreturn_main);
10716     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10717       << FixItHint::CreateRemoval(NoreturnRange);
10718   }
10719   if (FD->isConstexpr()) {
10720     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10721         << FD->isConsteval()
10722         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10723     FD->setConstexprKind(CSK_unspecified);
10724   }
10725 
10726   if (getLangOpts().OpenCL) {
10727     Diag(FD->getLocation(), diag::err_opencl_no_main)
10728         << FD->hasAttr<OpenCLKernelAttr>();
10729     FD->setInvalidDecl();
10730     return;
10731   }
10732 
10733   QualType T = FD->getType();
10734   assert(T->isFunctionType() && "function decl is not of function type");
10735   const FunctionType* FT = T->castAs<FunctionType>();
10736 
10737   // Set default calling convention for main()
10738   if (FT->getCallConv() != CC_C) {
10739     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10740     FD->setType(QualType(FT, 0));
10741     T = Context.getCanonicalType(FD->getType());
10742   }
10743 
10744   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10745     // In C with GNU extensions we allow main() to have non-integer return
10746     // type, but we should warn about the extension, and we disable the
10747     // implicit-return-zero rule.
10748 
10749     // GCC in C mode accepts qualified 'int'.
10750     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10751       FD->setHasImplicitReturnZero(true);
10752     else {
10753       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10754       SourceRange RTRange = FD->getReturnTypeSourceRange();
10755       if (RTRange.isValid())
10756         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10757             << FixItHint::CreateReplacement(RTRange, "int");
10758     }
10759   } else {
10760     // In C and C++, main magically returns 0 if you fall off the end;
10761     // set the flag which tells us that.
10762     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10763 
10764     // All the standards say that main() should return 'int'.
10765     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10766       FD->setHasImplicitReturnZero(true);
10767     else {
10768       // Otherwise, this is just a flat-out error.
10769       SourceRange RTRange = FD->getReturnTypeSourceRange();
10770       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10771           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10772                                 : FixItHint());
10773       FD->setInvalidDecl(true);
10774     }
10775   }
10776 
10777   // Treat protoless main() as nullary.
10778   if (isa<FunctionNoProtoType>(FT)) return;
10779 
10780   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10781   unsigned nparams = FTP->getNumParams();
10782   assert(FD->getNumParams() == nparams);
10783 
10784   bool HasExtraParameters = (nparams > 3);
10785 
10786   if (FTP->isVariadic()) {
10787     Diag(FD->getLocation(), diag::ext_variadic_main);
10788     // FIXME: if we had information about the location of the ellipsis, we
10789     // could add a FixIt hint to remove it as a parameter.
10790   }
10791 
10792   // Darwin passes an undocumented fourth argument of type char**.  If
10793   // other platforms start sprouting these, the logic below will start
10794   // getting shifty.
10795   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10796     HasExtraParameters = false;
10797 
10798   if (HasExtraParameters) {
10799     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10800     FD->setInvalidDecl(true);
10801     nparams = 3;
10802   }
10803 
10804   // FIXME: a lot of the following diagnostics would be improved
10805   // if we had some location information about types.
10806 
10807   QualType CharPP =
10808     Context.getPointerType(Context.getPointerType(Context.CharTy));
10809   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10810 
10811   for (unsigned i = 0; i < nparams; ++i) {
10812     QualType AT = FTP->getParamType(i);
10813 
10814     bool mismatch = true;
10815 
10816     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10817       mismatch = false;
10818     else if (Expected[i] == CharPP) {
10819       // As an extension, the following forms are okay:
10820       //   char const **
10821       //   char const * const *
10822       //   char * const *
10823 
10824       QualifierCollector qs;
10825       const PointerType* PT;
10826       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10827           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10828           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10829                               Context.CharTy)) {
10830         qs.removeConst();
10831         mismatch = !qs.empty();
10832       }
10833     }
10834 
10835     if (mismatch) {
10836       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10837       // TODO: suggest replacing given type with expected type
10838       FD->setInvalidDecl(true);
10839     }
10840   }
10841 
10842   if (nparams == 1 && !FD->isInvalidDecl()) {
10843     Diag(FD->getLocation(), diag::warn_main_one_arg);
10844   }
10845 
10846   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10847     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10848     FD->setInvalidDecl();
10849   }
10850 }
10851 
10852 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10853   QualType T = FD->getType();
10854   assert(T->isFunctionType() && "function decl is not of function type");
10855   const FunctionType *FT = T->castAs<FunctionType>();
10856 
10857   // Set an implicit return of 'zero' if the function can return some integral,
10858   // enumeration, pointer or nullptr type.
10859   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10860       FT->getReturnType()->isAnyPointerType() ||
10861       FT->getReturnType()->isNullPtrType())
10862     // DllMain is exempt because a return value of zero means it failed.
10863     if (FD->getName() != "DllMain")
10864       FD->setHasImplicitReturnZero(true);
10865 
10866   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10867     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10868     FD->setInvalidDecl();
10869   }
10870 }
10871 
10872 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10873   // FIXME: Need strict checking.  In C89, we need to check for
10874   // any assignment, increment, decrement, function-calls, or
10875   // commas outside of a sizeof.  In C99, it's the same list,
10876   // except that the aforementioned are allowed in unevaluated
10877   // expressions.  Everything else falls under the
10878   // "may accept other forms of constant expressions" exception.
10879   // (We never end up here for C++, so the constant expression
10880   // rules there don't matter.)
10881   const Expr *Culprit;
10882   if (Init->isConstantInitializer(Context, false, &Culprit))
10883     return false;
10884   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10885     << Culprit->getSourceRange();
10886   return true;
10887 }
10888 
10889 namespace {
10890   // Visits an initialization expression to see if OrigDecl is evaluated in
10891   // its own initialization and throws a warning if it does.
10892   class SelfReferenceChecker
10893       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10894     Sema &S;
10895     Decl *OrigDecl;
10896     bool isRecordType;
10897     bool isPODType;
10898     bool isReferenceType;
10899 
10900     bool isInitList;
10901     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10902 
10903   public:
10904     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10905 
10906     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10907                                                     S(S), OrigDecl(OrigDecl) {
10908       isPODType = false;
10909       isRecordType = false;
10910       isReferenceType = false;
10911       isInitList = false;
10912       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10913         isPODType = VD->getType().isPODType(S.Context);
10914         isRecordType = VD->getType()->isRecordType();
10915         isReferenceType = VD->getType()->isReferenceType();
10916       }
10917     }
10918 
10919     // For most expressions, just call the visitor.  For initializer lists,
10920     // track the index of the field being initialized since fields are
10921     // initialized in order allowing use of previously initialized fields.
10922     void CheckExpr(Expr *E) {
10923       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10924       if (!InitList) {
10925         Visit(E);
10926         return;
10927       }
10928 
10929       // Track and increment the index here.
10930       isInitList = true;
10931       InitFieldIndex.push_back(0);
10932       for (auto Child : InitList->children()) {
10933         CheckExpr(cast<Expr>(Child));
10934         ++InitFieldIndex.back();
10935       }
10936       InitFieldIndex.pop_back();
10937     }
10938 
10939     // Returns true if MemberExpr is checked and no further checking is needed.
10940     // Returns false if additional checking is required.
10941     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10942       llvm::SmallVector<FieldDecl*, 4> Fields;
10943       Expr *Base = E;
10944       bool ReferenceField = false;
10945 
10946       // Get the field members used.
10947       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10948         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10949         if (!FD)
10950           return false;
10951         Fields.push_back(FD);
10952         if (FD->getType()->isReferenceType())
10953           ReferenceField = true;
10954         Base = ME->getBase()->IgnoreParenImpCasts();
10955       }
10956 
10957       // Keep checking only if the base Decl is the same.
10958       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10959       if (!DRE || DRE->getDecl() != OrigDecl)
10960         return false;
10961 
10962       // A reference field can be bound to an unininitialized field.
10963       if (CheckReference && !ReferenceField)
10964         return true;
10965 
10966       // Convert FieldDecls to their index number.
10967       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10968       for (const FieldDecl *I : llvm::reverse(Fields))
10969         UsedFieldIndex.push_back(I->getFieldIndex());
10970 
10971       // See if a warning is needed by checking the first difference in index
10972       // numbers.  If field being used has index less than the field being
10973       // initialized, then the use is safe.
10974       for (auto UsedIter = UsedFieldIndex.begin(),
10975                 UsedEnd = UsedFieldIndex.end(),
10976                 OrigIter = InitFieldIndex.begin(),
10977                 OrigEnd = InitFieldIndex.end();
10978            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10979         if (*UsedIter < *OrigIter)
10980           return true;
10981         if (*UsedIter > *OrigIter)
10982           break;
10983       }
10984 
10985       // TODO: Add a different warning which will print the field names.
10986       HandleDeclRefExpr(DRE);
10987       return true;
10988     }
10989 
10990     // For most expressions, the cast is directly above the DeclRefExpr.
10991     // For conditional operators, the cast can be outside the conditional
10992     // operator if both expressions are DeclRefExpr's.
10993     void HandleValue(Expr *E) {
10994       E = E->IgnoreParens();
10995       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10996         HandleDeclRefExpr(DRE);
10997         return;
10998       }
10999 
11000       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11001         Visit(CO->getCond());
11002         HandleValue(CO->getTrueExpr());
11003         HandleValue(CO->getFalseExpr());
11004         return;
11005       }
11006 
11007       if (BinaryConditionalOperator *BCO =
11008               dyn_cast<BinaryConditionalOperator>(E)) {
11009         Visit(BCO->getCond());
11010         HandleValue(BCO->getFalseExpr());
11011         return;
11012       }
11013 
11014       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11015         HandleValue(OVE->getSourceExpr());
11016         return;
11017       }
11018 
11019       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11020         if (BO->getOpcode() == BO_Comma) {
11021           Visit(BO->getLHS());
11022           HandleValue(BO->getRHS());
11023           return;
11024         }
11025       }
11026 
11027       if (isa<MemberExpr>(E)) {
11028         if (isInitList) {
11029           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11030                                       false /*CheckReference*/))
11031             return;
11032         }
11033 
11034         Expr *Base = E->IgnoreParenImpCasts();
11035         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11036           // Check for static member variables and don't warn on them.
11037           if (!isa<FieldDecl>(ME->getMemberDecl()))
11038             return;
11039           Base = ME->getBase()->IgnoreParenImpCasts();
11040         }
11041         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11042           HandleDeclRefExpr(DRE);
11043         return;
11044       }
11045 
11046       Visit(E);
11047     }
11048 
11049     // Reference types not handled in HandleValue are handled here since all
11050     // uses of references are bad, not just r-value uses.
11051     void VisitDeclRefExpr(DeclRefExpr *E) {
11052       if (isReferenceType)
11053         HandleDeclRefExpr(E);
11054     }
11055 
11056     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11057       if (E->getCastKind() == CK_LValueToRValue) {
11058         HandleValue(E->getSubExpr());
11059         return;
11060       }
11061 
11062       Inherited::VisitImplicitCastExpr(E);
11063     }
11064 
11065     void VisitMemberExpr(MemberExpr *E) {
11066       if (isInitList) {
11067         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11068           return;
11069       }
11070 
11071       // Don't warn on arrays since they can be treated as pointers.
11072       if (E->getType()->canDecayToPointerType()) return;
11073 
11074       // Warn when a non-static method call is followed by non-static member
11075       // field accesses, which is followed by a DeclRefExpr.
11076       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11077       bool Warn = (MD && !MD->isStatic());
11078       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11079       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11080         if (!isa<FieldDecl>(ME->getMemberDecl()))
11081           Warn = false;
11082         Base = ME->getBase()->IgnoreParenImpCasts();
11083       }
11084 
11085       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11086         if (Warn)
11087           HandleDeclRefExpr(DRE);
11088         return;
11089       }
11090 
11091       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11092       // Visit that expression.
11093       Visit(Base);
11094     }
11095 
11096     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11097       Expr *Callee = E->getCallee();
11098 
11099       if (isa<UnresolvedLookupExpr>(Callee))
11100         return Inherited::VisitCXXOperatorCallExpr(E);
11101 
11102       Visit(Callee);
11103       for (auto Arg: E->arguments())
11104         HandleValue(Arg->IgnoreParenImpCasts());
11105     }
11106 
11107     void VisitUnaryOperator(UnaryOperator *E) {
11108       // For POD record types, addresses of its own members are well-defined.
11109       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11110           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11111         if (!isPODType)
11112           HandleValue(E->getSubExpr());
11113         return;
11114       }
11115 
11116       if (E->isIncrementDecrementOp()) {
11117         HandleValue(E->getSubExpr());
11118         return;
11119       }
11120 
11121       Inherited::VisitUnaryOperator(E);
11122     }
11123 
11124     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11125 
11126     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11127       if (E->getConstructor()->isCopyConstructor()) {
11128         Expr *ArgExpr = E->getArg(0);
11129         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11130           if (ILE->getNumInits() == 1)
11131             ArgExpr = ILE->getInit(0);
11132         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11133           if (ICE->getCastKind() == CK_NoOp)
11134             ArgExpr = ICE->getSubExpr();
11135         HandleValue(ArgExpr);
11136         return;
11137       }
11138       Inherited::VisitCXXConstructExpr(E);
11139     }
11140 
11141     void VisitCallExpr(CallExpr *E) {
11142       // Treat std::move as a use.
11143       if (E->isCallToStdMove()) {
11144         HandleValue(E->getArg(0));
11145         return;
11146       }
11147 
11148       Inherited::VisitCallExpr(E);
11149     }
11150 
11151     void VisitBinaryOperator(BinaryOperator *E) {
11152       if (E->isCompoundAssignmentOp()) {
11153         HandleValue(E->getLHS());
11154         Visit(E->getRHS());
11155         return;
11156       }
11157 
11158       Inherited::VisitBinaryOperator(E);
11159     }
11160 
11161     // A custom visitor for BinaryConditionalOperator is needed because the
11162     // regular visitor would check the condition and true expression separately
11163     // but both point to the same place giving duplicate diagnostics.
11164     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11165       Visit(E->getCond());
11166       Visit(E->getFalseExpr());
11167     }
11168 
11169     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11170       Decl* ReferenceDecl = DRE->getDecl();
11171       if (OrigDecl != ReferenceDecl) return;
11172       unsigned diag;
11173       if (isReferenceType) {
11174         diag = diag::warn_uninit_self_reference_in_reference_init;
11175       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11176         diag = diag::warn_static_self_reference_in_init;
11177       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11178                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11179                  DRE->getDecl()->getType()->isRecordType()) {
11180         diag = diag::warn_uninit_self_reference_in_init;
11181       } else {
11182         // Local variables will be handled by the CFG analysis.
11183         return;
11184       }
11185 
11186       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11187                             S.PDiag(diag)
11188                                 << DRE->getDecl() << OrigDecl->getLocation()
11189                                 << DRE->getSourceRange());
11190     }
11191   };
11192 
11193   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11194   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11195                                  bool DirectInit) {
11196     // Parameters arguments are occassionially constructed with itself,
11197     // for instance, in recursive functions.  Skip them.
11198     if (isa<ParmVarDecl>(OrigDecl))
11199       return;
11200 
11201     E = E->IgnoreParens();
11202 
11203     // Skip checking T a = a where T is not a record or reference type.
11204     // Doing so is a way to silence uninitialized warnings.
11205     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11206       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11207         if (ICE->getCastKind() == CK_LValueToRValue)
11208           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11209             if (DRE->getDecl() == OrigDecl)
11210               return;
11211 
11212     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11213   }
11214 } // end anonymous namespace
11215 
11216 namespace {
11217   // Simple wrapper to add the name of a variable or (if no variable is
11218   // available) a DeclarationName into a diagnostic.
11219   struct VarDeclOrName {
11220     VarDecl *VDecl;
11221     DeclarationName Name;
11222 
11223     friend const Sema::SemaDiagnosticBuilder &
11224     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11225       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11226     }
11227   };
11228 } // end anonymous namespace
11229 
11230 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11231                                             DeclarationName Name, QualType Type,
11232                                             TypeSourceInfo *TSI,
11233                                             SourceRange Range, bool DirectInit,
11234                                             Expr *Init) {
11235   bool IsInitCapture = !VDecl;
11236   assert((!VDecl || !VDecl->isInitCapture()) &&
11237          "init captures are expected to be deduced prior to initialization");
11238 
11239   VarDeclOrName VN{VDecl, Name};
11240 
11241   DeducedType *Deduced = Type->getContainedDeducedType();
11242   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11243 
11244   // C++11 [dcl.spec.auto]p3
11245   if (!Init) {
11246     assert(VDecl && "no init for init capture deduction?");
11247 
11248     // Except for class argument deduction, and then for an initializing
11249     // declaration only, i.e. no static at class scope or extern.
11250     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11251         VDecl->hasExternalStorage() ||
11252         VDecl->isStaticDataMember()) {
11253       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11254         << VDecl->getDeclName() << Type;
11255       return QualType();
11256     }
11257   }
11258 
11259   ArrayRef<Expr*> DeduceInits;
11260   if (Init)
11261     DeduceInits = Init;
11262 
11263   if (DirectInit) {
11264     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11265       DeduceInits = PL->exprs();
11266   }
11267 
11268   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11269     assert(VDecl && "non-auto type for init capture deduction?");
11270     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11271     InitializationKind Kind = InitializationKind::CreateForInit(
11272         VDecl->getLocation(), DirectInit, Init);
11273     // FIXME: Initialization should not be taking a mutable list of inits.
11274     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11275     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11276                                                        InitsCopy);
11277   }
11278 
11279   if (DirectInit) {
11280     if (auto *IL = dyn_cast<InitListExpr>(Init))
11281       DeduceInits = IL->inits();
11282   }
11283 
11284   // Deduction only works if we have exactly one source expression.
11285   if (DeduceInits.empty()) {
11286     // It isn't possible to write this directly, but it is possible to
11287     // end up in this situation with "auto x(some_pack...);"
11288     Diag(Init->getBeginLoc(), IsInitCapture
11289                                   ? diag::err_init_capture_no_expression
11290                                   : diag::err_auto_var_init_no_expression)
11291         << VN << Type << Range;
11292     return QualType();
11293   }
11294 
11295   if (DeduceInits.size() > 1) {
11296     Diag(DeduceInits[1]->getBeginLoc(),
11297          IsInitCapture ? diag::err_init_capture_multiple_expressions
11298                        : diag::err_auto_var_init_multiple_expressions)
11299         << VN << Type << Range;
11300     return QualType();
11301   }
11302 
11303   Expr *DeduceInit = DeduceInits[0];
11304   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11305     Diag(Init->getBeginLoc(), IsInitCapture
11306                                   ? diag::err_init_capture_paren_braces
11307                                   : diag::err_auto_var_init_paren_braces)
11308         << isa<InitListExpr>(Init) << VN << Type << Range;
11309     return QualType();
11310   }
11311 
11312   // Expressions default to 'id' when we're in a debugger.
11313   bool DefaultedAnyToId = false;
11314   if (getLangOpts().DebuggerCastResultToId &&
11315       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11316     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11317     if (Result.isInvalid()) {
11318       return QualType();
11319     }
11320     Init = Result.get();
11321     DefaultedAnyToId = true;
11322   }
11323 
11324   // C++ [dcl.decomp]p1:
11325   //   If the assignment-expression [...] has array type A and no ref-qualifier
11326   //   is present, e has type cv A
11327   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11328       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11329       DeduceInit->getType()->isConstantArrayType())
11330     return Context.getQualifiedType(DeduceInit->getType(),
11331                                     Type.getQualifiers());
11332 
11333   QualType DeducedType;
11334   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11335     if (!IsInitCapture)
11336       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11337     else if (isa<InitListExpr>(Init))
11338       Diag(Range.getBegin(),
11339            diag::err_init_capture_deduction_failure_from_init_list)
11340           << VN
11341           << (DeduceInit->getType().isNull() ? TSI->getType()
11342                                              : DeduceInit->getType())
11343           << DeduceInit->getSourceRange();
11344     else
11345       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11346           << VN << TSI->getType()
11347           << (DeduceInit->getType().isNull() ? TSI->getType()
11348                                              : DeduceInit->getType())
11349           << DeduceInit->getSourceRange();
11350   }
11351 
11352   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11353   // 'id' instead of a specific object type prevents most of our usual
11354   // checks.
11355   // We only want to warn outside of template instantiations, though:
11356   // inside a template, the 'id' could have come from a parameter.
11357   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11358       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11359     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11360     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11361   }
11362 
11363   return DeducedType;
11364 }
11365 
11366 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11367                                          Expr *Init) {
11368   QualType DeducedType = deduceVarTypeFromInitializer(
11369       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11370       VDecl->getSourceRange(), DirectInit, Init);
11371   if (DeducedType.isNull()) {
11372     VDecl->setInvalidDecl();
11373     return true;
11374   }
11375 
11376   VDecl->setType(DeducedType);
11377   assert(VDecl->isLinkageValid());
11378 
11379   // In ARC, infer lifetime.
11380   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11381     VDecl->setInvalidDecl();
11382 
11383   if (getLangOpts().OpenCL)
11384     deduceOpenCLAddressSpace(VDecl);
11385 
11386   // If this is a redeclaration, check that the type we just deduced matches
11387   // the previously declared type.
11388   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11389     // We never need to merge the type, because we cannot form an incomplete
11390     // array of auto, nor deduce such a type.
11391     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11392   }
11393 
11394   // Check the deduced type is valid for a variable declaration.
11395   CheckVariableDeclarationType(VDecl);
11396   return VDecl->isInvalidDecl();
11397 }
11398 
11399 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11400                                               SourceLocation Loc) {
11401   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11402     Init = CE->getSubExpr();
11403 
11404   QualType InitType = Init->getType();
11405   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11406           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11407          "shouldn't be called if type doesn't have a non-trivial C struct");
11408   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11409     for (auto I : ILE->inits()) {
11410       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11411           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11412         continue;
11413       SourceLocation SL = I->getExprLoc();
11414       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11415     }
11416     return;
11417   }
11418 
11419   if (isa<ImplicitValueInitExpr>(Init)) {
11420     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11421       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11422                             NTCUK_Init);
11423   } else {
11424     // Assume all other explicit initializers involving copying some existing
11425     // object.
11426     // TODO: ignore any explicit initializers where we can guarantee
11427     // copy-elision.
11428     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11429       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11430   }
11431 }
11432 
11433 namespace {
11434 
11435 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11436   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11437   // in the source code or implicitly by the compiler if it is in a union
11438   // defined in a system header and has non-trivial ObjC ownership
11439   // qualifications. We don't want those fields to participate in determining
11440   // whether the containing union is non-trivial.
11441   return FD->hasAttr<UnavailableAttr>();
11442 }
11443 
11444 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11445     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11446                                     void> {
11447   using Super =
11448       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11449                                     void>;
11450 
11451   DiagNonTrivalCUnionDefaultInitializeVisitor(
11452       QualType OrigTy, SourceLocation OrigLoc,
11453       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11454       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11455 
11456   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11457                      const FieldDecl *FD, bool InNonTrivialUnion) {
11458     if (const auto *AT = S.Context.getAsArrayType(QT))
11459       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11460                                      InNonTrivialUnion);
11461     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11462   }
11463 
11464   void visitARCStrong(QualType QT, const FieldDecl *FD,
11465                       bool InNonTrivialUnion) {
11466     if (InNonTrivialUnion)
11467       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11468           << 1 << 0 << QT << FD->getName();
11469   }
11470 
11471   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11472     if (InNonTrivialUnion)
11473       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11474           << 1 << 0 << QT << FD->getName();
11475   }
11476 
11477   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11478     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11479     if (RD->isUnion()) {
11480       if (OrigLoc.isValid()) {
11481         bool IsUnion = false;
11482         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11483           IsUnion = OrigRD->isUnion();
11484         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11485             << 0 << OrigTy << IsUnion << UseContext;
11486         // Reset OrigLoc so that this diagnostic is emitted only once.
11487         OrigLoc = SourceLocation();
11488       }
11489       InNonTrivialUnion = true;
11490     }
11491 
11492     if (InNonTrivialUnion)
11493       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11494           << 0 << 0 << QT.getUnqualifiedType() << "";
11495 
11496     for (const FieldDecl *FD : RD->fields())
11497       if (!shouldIgnoreForRecordTriviality(FD))
11498         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11499   }
11500 
11501   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11502 
11503   // The non-trivial C union type or the struct/union type that contains a
11504   // non-trivial C union.
11505   QualType OrigTy;
11506   SourceLocation OrigLoc;
11507   Sema::NonTrivialCUnionContext UseContext;
11508   Sema &S;
11509 };
11510 
11511 struct DiagNonTrivalCUnionDestructedTypeVisitor
11512     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11513   using Super =
11514       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11515 
11516   DiagNonTrivalCUnionDestructedTypeVisitor(
11517       QualType OrigTy, SourceLocation OrigLoc,
11518       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11519       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11520 
11521   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11522                      const FieldDecl *FD, bool InNonTrivialUnion) {
11523     if (const auto *AT = S.Context.getAsArrayType(QT))
11524       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11525                                      InNonTrivialUnion);
11526     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11527   }
11528 
11529   void visitARCStrong(QualType QT, const FieldDecl *FD,
11530                       bool InNonTrivialUnion) {
11531     if (InNonTrivialUnion)
11532       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11533           << 1 << 1 << QT << FD->getName();
11534   }
11535 
11536   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11537     if (InNonTrivialUnion)
11538       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11539           << 1 << 1 << QT << FD->getName();
11540   }
11541 
11542   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11543     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11544     if (RD->isUnion()) {
11545       if (OrigLoc.isValid()) {
11546         bool IsUnion = false;
11547         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11548           IsUnion = OrigRD->isUnion();
11549         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11550             << 1 << OrigTy << IsUnion << UseContext;
11551         // Reset OrigLoc so that this diagnostic is emitted only once.
11552         OrigLoc = SourceLocation();
11553       }
11554       InNonTrivialUnion = true;
11555     }
11556 
11557     if (InNonTrivialUnion)
11558       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11559           << 0 << 1 << QT.getUnqualifiedType() << "";
11560 
11561     for (const FieldDecl *FD : RD->fields())
11562       if (!shouldIgnoreForRecordTriviality(FD))
11563         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11564   }
11565 
11566   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11567   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11568                           bool InNonTrivialUnion) {}
11569 
11570   // The non-trivial C union type or the struct/union type that contains a
11571   // non-trivial C union.
11572   QualType OrigTy;
11573   SourceLocation OrigLoc;
11574   Sema::NonTrivialCUnionContext UseContext;
11575   Sema &S;
11576 };
11577 
11578 struct DiagNonTrivalCUnionCopyVisitor
11579     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11580   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11581 
11582   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11583                                  Sema::NonTrivialCUnionContext UseContext,
11584                                  Sema &S)
11585       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11586 
11587   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11588                      const FieldDecl *FD, bool InNonTrivialUnion) {
11589     if (const auto *AT = S.Context.getAsArrayType(QT))
11590       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11591                                      InNonTrivialUnion);
11592     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11593   }
11594 
11595   void visitARCStrong(QualType QT, const FieldDecl *FD,
11596                       bool InNonTrivialUnion) {
11597     if (InNonTrivialUnion)
11598       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11599           << 1 << 2 << QT << FD->getName();
11600   }
11601 
11602   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11603     if (InNonTrivialUnion)
11604       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11605           << 1 << 2 << QT << FD->getName();
11606   }
11607 
11608   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11609     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11610     if (RD->isUnion()) {
11611       if (OrigLoc.isValid()) {
11612         bool IsUnion = false;
11613         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11614           IsUnion = OrigRD->isUnion();
11615         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11616             << 2 << OrigTy << IsUnion << UseContext;
11617         // Reset OrigLoc so that this diagnostic is emitted only once.
11618         OrigLoc = SourceLocation();
11619       }
11620       InNonTrivialUnion = true;
11621     }
11622 
11623     if (InNonTrivialUnion)
11624       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11625           << 0 << 2 << QT.getUnqualifiedType() << "";
11626 
11627     for (const FieldDecl *FD : RD->fields())
11628       if (!shouldIgnoreForRecordTriviality(FD))
11629         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11630   }
11631 
11632   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11633                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11634   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11635   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11636                             bool InNonTrivialUnion) {}
11637 
11638   // The non-trivial C union type or the struct/union type that contains a
11639   // non-trivial C union.
11640   QualType OrigTy;
11641   SourceLocation OrigLoc;
11642   Sema::NonTrivialCUnionContext UseContext;
11643   Sema &S;
11644 };
11645 
11646 } // namespace
11647 
11648 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11649                                  NonTrivialCUnionContext UseContext,
11650                                  unsigned NonTrivialKind) {
11651   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11652           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11653           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11654          "shouldn't be called if type doesn't have a non-trivial C union");
11655 
11656   if ((NonTrivialKind & NTCUK_Init) &&
11657       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11658     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11659         .visit(QT, nullptr, false);
11660   if ((NonTrivialKind & NTCUK_Destruct) &&
11661       QT.hasNonTrivialToPrimitiveDestructCUnion())
11662     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11663         .visit(QT, nullptr, false);
11664   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11665     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11666         .visit(QT, nullptr, false);
11667 }
11668 
11669 /// AddInitializerToDecl - Adds the initializer Init to the
11670 /// declaration dcl. If DirectInit is true, this is C++ direct
11671 /// initialization rather than copy initialization.
11672 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11673   // If there is no declaration, there was an error parsing it.  Just ignore
11674   // the initializer.
11675   if (!RealDecl || RealDecl->isInvalidDecl()) {
11676     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11677     return;
11678   }
11679 
11680   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11681     // Pure-specifiers are handled in ActOnPureSpecifier.
11682     Diag(Method->getLocation(), diag::err_member_function_initialization)
11683       << Method->getDeclName() << Init->getSourceRange();
11684     Method->setInvalidDecl();
11685     return;
11686   }
11687 
11688   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11689   if (!VDecl) {
11690     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11691     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11692     RealDecl->setInvalidDecl();
11693     return;
11694   }
11695 
11696   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11697   if (VDecl->getType()->isUndeducedType()) {
11698     // Attempt typo correction early so that the type of the init expression can
11699     // be deduced based on the chosen correction if the original init contains a
11700     // TypoExpr.
11701     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11702     if (!Res.isUsable()) {
11703       RealDecl->setInvalidDecl();
11704       return;
11705     }
11706     Init = Res.get();
11707 
11708     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11709       return;
11710   }
11711 
11712   // dllimport cannot be used on variable definitions.
11713   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11714     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11715     VDecl->setInvalidDecl();
11716     return;
11717   }
11718 
11719   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11720     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11721     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11722     VDecl->setInvalidDecl();
11723     return;
11724   }
11725 
11726   if (!VDecl->getType()->isDependentType()) {
11727     // A definition must end up with a complete type, which means it must be
11728     // complete with the restriction that an array type might be completed by
11729     // the initializer; note that later code assumes this restriction.
11730     QualType BaseDeclType = VDecl->getType();
11731     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11732       BaseDeclType = Array->getElementType();
11733     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11734                             diag::err_typecheck_decl_incomplete_type)) {
11735       RealDecl->setInvalidDecl();
11736       return;
11737     }
11738 
11739     // The variable can not have an abstract class type.
11740     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11741                                diag::err_abstract_type_in_decl,
11742                                AbstractVariableType))
11743       VDecl->setInvalidDecl();
11744   }
11745 
11746   // If adding the initializer will turn this declaration into a definition,
11747   // and we already have a definition for this variable, diagnose or otherwise
11748   // handle the situation.
11749   VarDecl *Def;
11750   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11751       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11752       !VDecl->isThisDeclarationADemotedDefinition() &&
11753       checkVarDeclRedefinition(Def, VDecl))
11754     return;
11755 
11756   if (getLangOpts().CPlusPlus) {
11757     // C++ [class.static.data]p4
11758     //   If a static data member is of const integral or const
11759     //   enumeration type, its declaration in the class definition can
11760     //   specify a constant-initializer which shall be an integral
11761     //   constant expression (5.19). In that case, the member can appear
11762     //   in integral constant expressions. The member shall still be
11763     //   defined in a namespace scope if it is used in the program and the
11764     //   namespace scope definition shall not contain an initializer.
11765     //
11766     // We already performed a redefinition check above, but for static
11767     // data members we also need to check whether there was an in-class
11768     // declaration with an initializer.
11769     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11770       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11771           << VDecl->getDeclName();
11772       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11773            diag::note_previous_initializer)
11774           << 0;
11775       return;
11776     }
11777 
11778     if (VDecl->hasLocalStorage())
11779       setFunctionHasBranchProtectedScope();
11780 
11781     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11782       VDecl->setInvalidDecl();
11783       return;
11784     }
11785   }
11786 
11787   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11788   // a kernel function cannot be initialized."
11789   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11790     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11791     VDecl->setInvalidDecl();
11792     return;
11793   }
11794 
11795   // Get the decls type and save a reference for later, since
11796   // CheckInitializerTypes may change it.
11797   QualType DclT = VDecl->getType(), SavT = DclT;
11798 
11799   // Expressions default to 'id' when we're in a debugger
11800   // and we are assigning it to a variable of Objective-C pointer type.
11801   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11802       Init->getType() == Context.UnknownAnyTy) {
11803     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11804     if (Result.isInvalid()) {
11805       VDecl->setInvalidDecl();
11806       return;
11807     }
11808     Init = Result.get();
11809   }
11810 
11811   // Perform the initialization.
11812   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11813   if (!VDecl->isInvalidDecl()) {
11814     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11815     InitializationKind Kind = InitializationKind::CreateForInit(
11816         VDecl->getLocation(), DirectInit, Init);
11817 
11818     MultiExprArg Args = Init;
11819     if (CXXDirectInit)
11820       Args = MultiExprArg(CXXDirectInit->getExprs(),
11821                           CXXDirectInit->getNumExprs());
11822 
11823     // Try to correct any TypoExprs in the initialization arguments.
11824     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11825       ExprResult Res = CorrectDelayedTyposInExpr(
11826           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11827             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11828             return Init.Failed() ? ExprError() : E;
11829           });
11830       if (Res.isInvalid()) {
11831         VDecl->setInvalidDecl();
11832       } else if (Res.get() != Args[Idx]) {
11833         Args[Idx] = Res.get();
11834       }
11835     }
11836     if (VDecl->isInvalidDecl())
11837       return;
11838 
11839     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11840                                    /*TopLevelOfInitList=*/false,
11841                                    /*TreatUnavailableAsInvalid=*/false);
11842     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11843     if (Result.isInvalid()) {
11844       VDecl->setInvalidDecl();
11845       return;
11846     }
11847 
11848     Init = Result.getAs<Expr>();
11849   }
11850 
11851   // Check for self-references within variable initializers.
11852   // Variables declared within a function/method body (except for references)
11853   // are handled by a dataflow analysis.
11854   // This is undefined behavior in C++, but valid in C.
11855   if (getLangOpts().CPlusPlus) {
11856     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11857         VDecl->getType()->isReferenceType()) {
11858       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11859     }
11860   }
11861 
11862   // If the type changed, it means we had an incomplete type that was
11863   // completed by the initializer. For example:
11864   //   int ary[] = { 1, 3, 5 };
11865   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11866   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11867     VDecl->setType(DclT);
11868 
11869   if (!VDecl->isInvalidDecl()) {
11870     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11871 
11872     if (VDecl->hasAttr<BlocksAttr>())
11873       checkRetainCycles(VDecl, Init);
11874 
11875     // It is safe to assign a weak reference into a strong variable.
11876     // Although this code can still have problems:
11877     //   id x = self.weakProp;
11878     //   id y = self.weakProp;
11879     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11880     // paths through the function. This should be revisited if
11881     // -Wrepeated-use-of-weak is made flow-sensitive.
11882     if (FunctionScopeInfo *FSI = getCurFunction())
11883       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11884            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11885           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11886                            Init->getBeginLoc()))
11887         FSI->markSafeWeakUse(Init);
11888   }
11889 
11890   // The initialization is usually a full-expression.
11891   //
11892   // FIXME: If this is a braced initialization of an aggregate, it is not
11893   // an expression, and each individual field initializer is a separate
11894   // full-expression. For instance, in:
11895   //
11896   //   struct Temp { ~Temp(); };
11897   //   struct S { S(Temp); };
11898   //   struct T { S a, b; } t = { Temp(), Temp() }
11899   //
11900   // we should destroy the first Temp before constructing the second.
11901   ExprResult Result =
11902       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11903                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11904   if (Result.isInvalid()) {
11905     VDecl->setInvalidDecl();
11906     return;
11907   }
11908   Init = Result.get();
11909 
11910   // Attach the initializer to the decl.
11911   VDecl->setInit(Init);
11912 
11913   if (VDecl->isLocalVarDecl()) {
11914     // Don't check the initializer if the declaration is malformed.
11915     if (VDecl->isInvalidDecl()) {
11916       // do nothing
11917 
11918     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11919     // This is true even in C++ for OpenCL.
11920     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11921       CheckForConstantInitializer(Init, DclT);
11922 
11923     // Otherwise, C++ does not restrict the initializer.
11924     } else if (getLangOpts().CPlusPlus) {
11925       // do nothing
11926 
11927     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11928     // static storage duration shall be constant expressions or string literals.
11929     } else if (VDecl->getStorageClass() == SC_Static) {
11930       CheckForConstantInitializer(Init, DclT);
11931 
11932     // C89 is stricter than C99 for aggregate initializers.
11933     // C89 6.5.7p3: All the expressions [...] in an initializer list
11934     // for an object that has aggregate or union type shall be
11935     // constant expressions.
11936     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11937                isa<InitListExpr>(Init)) {
11938       const Expr *Culprit;
11939       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11940         Diag(Culprit->getExprLoc(),
11941              diag::ext_aggregate_init_not_constant)
11942           << Culprit->getSourceRange();
11943       }
11944     }
11945 
11946     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11947       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11948         if (VDecl->hasLocalStorage())
11949           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11950   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11951              VDecl->getLexicalDeclContext()->isRecord()) {
11952     // This is an in-class initialization for a static data member, e.g.,
11953     //
11954     // struct S {
11955     //   static const int value = 17;
11956     // };
11957 
11958     // C++ [class.mem]p4:
11959     //   A member-declarator can contain a constant-initializer only
11960     //   if it declares a static member (9.4) of const integral or
11961     //   const enumeration type, see 9.4.2.
11962     //
11963     // C++11 [class.static.data]p3:
11964     //   If a non-volatile non-inline const static data member is of integral
11965     //   or enumeration type, its declaration in the class definition can
11966     //   specify a brace-or-equal-initializer in which every initializer-clause
11967     //   that is an assignment-expression is a constant expression. A static
11968     //   data member of literal type can be declared in the class definition
11969     //   with the constexpr specifier; if so, its declaration shall specify a
11970     //   brace-or-equal-initializer in which every initializer-clause that is
11971     //   an assignment-expression is a constant expression.
11972 
11973     // Do nothing on dependent types.
11974     if (DclT->isDependentType()) {
11975 
11976     // Allow any 'static constexpr' members, whether or not they are of literal
11977     // type. We separately check that every constexpr variable is of literal
11978     // type.
11979     } else if (VDecl->isConstexpr()) {
11980 
11981     // Require constness.
11982     } else if (!DclT.isConstQualified()) {
11983       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11984         << Init->getSourceRange();
11985       VDecl->setInvalidDecl();
11986 
11987     // We allow integer constant expressions in all cases.
11988     } else if (DclT->isIntegralOrEnumerationType()) {
11989       // Check whether the expression is a constant expression.
11990       SourceLocation Loc;
11991       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11992         // In C++11, a non-constexpr const static data member with an
11993         // in-class initializer cannot be volatile.
11994         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11995       else if (Init->isValueDependent())
11996         ; // Nothing to check.
11997       else if (Init->isIntegerConstantExpr(Context, &Loc))
11998         ; // Ok, it's an ICE!
11999       else if (Init->getType()->isScopedEnumeralType() &&
12000                Init->isCXX11ConstantExpr(Context))
12001         ; // Ok, it is a scoped-enum constant expression.
12002       else if (Init->isEvaluatable(Context)) {
12003         // If we can constant fold the initializer through heroics, accept it,
12004         // but report this as a use of an extension for -pedantic.
12005         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12006           << Init->getSourceRange();
12007       } else {
12008         // Otherwise, this is some crazy unknown case.  Report the issue at the
12009         // location provided by the isIntegerConstantExpr failed check.
12010         Diag(Loc, diag::err_in_class_initializer_non_constant)
12011           << Init->getSourceRange();
12012         VDecl->setInvalidDecl();
12013       }
12014 
12015     // We allow foldable floating-point constants as an extension.
12016     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12017       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12018       // it anyway and provide a fixit to add the 'constexpr'.
12019       if (getLangOpts().CPlusPlus11) {
12020         Diag(VDecl->getLocation(),
12021              diag::ext_in_class_initializer_float_type_cxx11)
12022             << DclT << Init->getSourceRange();
12023         Diag(VDecl->getBeginLoc(),
12024              diag::note_in_class_initializer_float_type_cxx11)
12025             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12026       } else {
12027         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12028           << DclT << Init->getSourceRange();
12029 
12030         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12031           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12032             << Init->getSourceRange();
12033           VDecl->setInvalidDecl();
12034         }
12035       }
12036 
12037     // Suggest adding 'constexpr' in C++11 for literal types.
12038     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12039       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12040           << DclT << Init->getSourceRange()
12041           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12042       VDecl->setConstexpr(true);
12043 
12044     } else {
12045       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12046         << DclT << Init->getSourceRange();
12047       VDecl->setInvalidDecl();
12048     }
12049   } else if (VDecl->isFileVarDecl()) {
12050     // In C, extern is typically used to avoid tentative definitions when
12051     // declaring variables in headers, but adding an intializer makes it a
12052     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12053     // In C++, extern is often used to give implictly static const variables
12054     // external linkage, so don't warn in that case. If selectany is present,
12055     // this might be header code intended for C and C++ inclusion, so apply the
12056     // C++ rules.
12057     if (VDecl->getStorageClass() == SC_Extern &&
12058         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12059          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12060         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12061         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12062       Diag(VDecl->getLocation(), diag::warn_extern_init);
12063 
12064     // In Microsoft C++ mode, a const variable defined in namespace scope has
12065     // external linkage by default if the variable is declared with
12066     // __declspec(dllexport).
12067     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12068         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12069         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12070       VDecl->setStorageClass(SC_Extern);
12071 
12072     // C99 6.7.8p4. All file scoped initializers need to be constant.
12073     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12074       CheckForConstantInitializer(Init, DclT);
12075   }
12076 
12077   QualType InitType = Init->getType();
12078   if (!InitType.isNull() &&
12079       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12080        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12081     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12082 
12083   // We will represent direct-initialization similarly to copy-initialization:
12084   //    int x(1);  -as-> int x = 1;
12085   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12086   //
12087   // Clients that want to distinguish between the two forms, can check for
12088   // direct initializer using VarDecl::getInitStyle().
12089   // A major benefit is that clients that don't particularly care about which
12090   // exactly form was it (like the CodeGen) can handle both cases without
12091   // special case code.
12092 
12093   // C++ 8.5p11:
12094   // The form of initialization (using parentheses or '=') is generally
12095   // insignificant, but does matter when the entity being initialized has a
12096   // class type.
12097   if (CXXDirectInit) {
12098     assert(DirectInit && "Call-style initializer must be direct init.");
12099     VDecl->setInitStyle(VarDecl::CallInit);
12100   } else if (DirectInit) {
12101     // This must be list-initialization. No other way is direct-initialization.
12102     VDecl->setInitStyle(VarDecl::ListInit);
12103   }
12104 
12105   CheckCompleteVariableDeclaration(VDecl);
12106 }
12107 
12108 /// ActOnInitializerError - Given that there was an error parsing an
12109 /// initializer for the given declaration, try to return to some form
12110 /// of sanity.
12111 void Sema::ActOnInitializerError(Decl *D) {
12112   // Our main concern here is re-establishing invariants like "a
12113   // variable's type is either dependent or complete".
12114   if (!D || D->isInvalidDecl()) return;
12115 
12116   VarDecl *VD = dyn_cast<VarDecl>(D);
12117   if (!VD) return;
12118 
12119   // Bindings are not usable if we can't make sense of the initializer.
12120   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12121     for (auto *BD : DD->bindings())
12122       BD->setInvalidDecl();
12123 
12124   // Auto types are meaningless if we can't make sense of the initializer.
12125   if (ParsingInitForAutoVars.count(D)) {
12126     D->setInvalidDecl();
12127     return;
12128   }
12129 
12130   QualType Ty = VD->getType();
12131   if (Ty->isDependentType()) return;
12132 
12133   // Require a complete type.
12134   if (RequireCompleteType(VD->getLocation(),
12135                           Context.getBaseElementType(Ty),
12136                           diag::err_typecheck_decl_incomplete_type)) {
12137     VD->setInvalidDecl();
12138     return;
12139   }
12140 
12141   // Require a non-abstract type.
12142   if (RequireNonAbstractType(VD->getLocation(), Ty,
12143                              diag::err_abstract_type_in_decl,
12144                              AbstractVariableType)) {
12145     VD->setInvalidDecl();
12146     return;
12147   }
12148 
12149   // Don't bother complaining about constructors or destructors,
12150   // though.
12151 }
12152 
12153 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12154   // If there is no declaration, there was an error parsing it. Just ignore it.
12155   if (!RealDecl)
12156     return;
12157 
12158   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12159     QualType Type = Var->getType();
12160 
12161     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12162     if (isa<DecompositionDecl>(RealDecl)) {
12163       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12164       Var->setInvalidDecl();
12165       return;
12166     }
12167 
12168     if (Type->isUndeducedType() &&
12169         DeduceVariableDeclarationType(Var, false, nullptr))
12170       return;
12171 
12172     // C++11 [class.static.data]p3: A static data member can be declared with
12173     // the constexpr specifier; if so, its declaration shall specify
12174     // a brace-or-equal-initializer.
12175     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12176     // the definition of a variable [...] or the declaration of a static data
12177     // member.
12178     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12179         !Var->isThisDeclarationADemotedDefinition()) {
12180       if (Var->isStaticDataMember()) {
12181         // C++1z removes the relevant rule; the in-class declaration is always
12182         // a definition there.
12183         if (!getLangOpts().CPlusPlus17 &&
12184             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12185           Diag(Var->getLocation(),
12186                diag::err_constexpr_static_mem_var_requires_init)
12187             << Var->getDeclName();
12188           Var->setInvalidDecl();
12189           return;
12190         }
12191       } else {
12192         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12193         Var->setInvalidDecl();
12194         return;
12195       }
12196     }
12197 
12198     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12199     // be initialized.
12200     if (!Var->isInvalidDecl() &&
12201         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12202         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12203       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12204       Var->setInvalidDecl();
12205       return;
12206     }
12207 
12208     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12209     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12210         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12211       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12212                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12213 
12214 
12215     switch (DefKind) {
12216     case VarDecl::Definition:
12217       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12218         break;
12219 
12220       // We have an out-of-line definition of a static data member
12221       // that has an in-class initializer, so we type-check this like
12222       // a declaration.
12223       //
12224       LLVM_FALLTHROUGH;
12225 
12226     case VarDecl::DeclarationOnly:
12227       // It's only a declaration.
12228 
12229       // Block scope. C99 6.7p7: If an identifier for an object is
12230       // declared with no linkage (C99 6.2.2p6), the type for the
12231       // object shall be complete.
12232       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12233           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12234           RequireCompleteType(Var->getLocation(), Type,
12235                               diag::err_typecheck_decl_incomplete_type))
12236         Var->setInvalidDecl();
12237 
12238       // Make sure that the type is not abstract.
12239       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12240           RequireNonAbstractType(Var->getLocation(), Type,
12241                                  diag::err_abstract_type_in_decl,
12242                                  AbstractVariableType))
12243         Var->setInvalidDecl();
12244       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12245           Var->getStorageClass() == SC_PrivateExtern) {
12246         Diag(Var->getLocation(), diag::warn_private_extern);
12247         Diag(Var->getLocation(), diag::note_private_extern);
12248       }
12249 
12250       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12251           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12252         ExternalDeclarations.push_back(Var);
12253 
12254       return;
12255 
12256     case VarDecl::TentativeDefinition:
12257       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12258       // object that has file scope without an initializer, and without a
12259       // storage-class specifier or with the storage-class specifier "static",
12260       // constitutes a tentative definition. Note: A tentative definition with
12261       // external linkage is valid (C99 6.2.2p5).
12262       if (!Var->isInvalidDecl()) {
12263         if (const IncompleteArrayType *ArrayT
12264                                     = Context.getAsIncompleteArrayType(Type)) {
12265           if (RequireCompleteType(Var->getLocation(),
12266                                   ArrayT->getElementType(),
12267                                   diag::err_illegal_decl_array_incomplete_type))
12268             Var->setInvalidDecl();
12269         } else if (Var->getStorageClass() == SC_Static) {
12270           // C99 6.9.2p3: If the declaration of an identifier for an object is
12271           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12272           // declared type shall not be an incomplete type.
12273           // NOTE: code such as the following
12274           //     static struct s;
12275           //     struct s { int a; };
12276           // is accepted by gcc. Hence here we issue a warning instead of
12277           // an error and we do not invalidate the static declaration.
12278           // NOTE: to avoid multiple warnings, only check the first declaration.
12279           if (Var->isFirstDecl())
12280             RequireCompleteType(Var->getLocation(), Type,
12281                                 diag::ext_typecheck_decl_incomplete_type);
12282         }
12283       }
12284 
12285       // Record the tentative definition; we're done.
12286       if (!Var->isInvalidDecl())
12287         TentativeDefinitions.push_back(Var);
12288       return;
12289     }
12290 
12291     // Provide a specific diagnostic for uninitialized variable
12292     // definitions with incomplete array type.
12293     if (Type->isIncompleteArrayType()) {
12294       Diag(Var->getLocation(),
12295            diag::err_typecheck_incomplete_array_needs_initializer);
12296       Var->setInvalidDecl();
12297       return;
12298     }
12299 
12300     // Provide a specific diagnostic for uninitialized variable
12301     // definitions with reference type.
12302     if (Type->isReferenceType()) {
12303       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12304         << Var->getDeclName()
12305         << SourceRange(Var->getLocation(), Var->getLocation());
12306       Var->setInvalidDecl();
12307       return;
12308     }
12309 
12310     // Do not attempt to type-check the default initializer for a
12311     // variable with dependent type.
12312     if (Type->isDependentType())
12313       return;
12314 
12315     if (Var->isInvalidDecl())
12316       return;
12317 
12318     if (!Var->hasAttr<AliasAttr>()) {
12319       if (RequireCompleteType(Var->getLocation(),
12320                               Context.getBaseElementType(Type),
12321                               diag::err_typecheck_decl_incomplete_type)) {
12322         Var->setInvalidDecl();
12323         return;
12324       }
12325     } else {
12326       return;
12327     }
12328 
12329     // The variable can not have an abstract class type.
12330     if (RequireNonAbstractType(Var->getLocation(), Type,
12331                                diag::err_abstract_type_in_decl,
12332                                AbstractVariableType)) {
12333       Var->setInvalidDecl();
12334       return;
12335     }
12336 
12337     // Check for jumps past the implicit initializer.  C++0x
12338     // clarifies that this applies to a "variable with automatic
12339     // storage duration", not a "local variable".
12340     // C++11 [stmt.dcl]p3
12341     //   A program that jumps from a point where a variable with automatic
12342     //   storage duration is not in scope to a point where it is in scope is
12343     //   ill-formed unless the variable has scalar type, class type with a
12344     //   trivial default constructor and a trivial destructor, a cv-qualified
12345     //   version of one of these types, or an array of one of the preceding
12346     //   types and is declared without an initializer.
12347     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12348       if (const RecordType *Record
12349             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12350         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12351         // Mark the function (if we're in one) for further checking even if the
12352         // looser rules of C++11 do not require such checks, so that we can
12353         // diagnose incompatibilities with C++98.
12354         if (!CXXRecord->isPOD())
12355           setFunctionHasBranchProtectedScope();
12356       }
12357     }
12358     // In OpenCL, we can't initialize objects in the __local address space,
12359     // even implicitly, so don't synthesize an implicit initializer.
12360     if (getLangOpts().OpenCL &&
12361         Var->getType().getAddressSpace() == LangAS::opencl_local)
12362       return;
12363     // C++03 [dcl.init]p9:
12364     //   If no initializer is specified for an object, and the
12365     //   object is of (possibly cv-qualified) non-POD class type (or
12366     //   array thereof), the object shall be default-initialized; if
12367     //   the object is of const-qualified type, the underlying class
12368     //   type shall have a user-declared default
12369     //   constructor. Otherwise, if no initializer is specified for
12370     //   a non- static object, the object and its subobjects, if
12371     //   any, have an indeterminate initial value); if the object
12372     //   or any of its subobjects are of const-qualified type, the
12373     //   program is ill-formed.
12374     // C++0x [dcl.init]p11:
12375     //   If no initializer is specified for an object, the object is
12376     //   default-initialized; [...].
12377     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12378     InitializationKind Kind
12379       = InitializationKind::CreateDefault(Var->getLocation());
12380 
12381     InitializationSequence InitSeq(*this, Entity, Kind, None);
12382     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12383     if (Init.isInvalid())
12384       Var->setInvalidDecl();
12385     else if (Init.get()) {
12386       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12387       // This is important for template substitution.
12388       Var->setInitStyle(VarDecl::CallInit);
12389     }
12390 
12391     CheckCompleteVariableDeclaration(Var);
12392   }
12393 }
12394 
12395 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12396   // If there is no declaration, there was an error parsing it. Ignore it.
12397   if (!D)
12398     return;
12399 
12400   VarDecl *VD = dyn_cast<VarDecl>(D);
12401   if (!VD) {
12402     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12403     D->setInvalidDecl();
12404     return;
12405   }
12406 
12407   VD->setCXXForRangeDecl(true);
12408 
12409   // for-range-declaration cannot be given a storage class specifier.
12410   int Error = -1;
12411   switch (VD->getStorageClass()) {
12412   case SC_None:
12413     break;
12414   case SC_Extern:
12415     Error = 0;
12416     break;
12417   case SC_Static:
12418     Error = 1;
12419     break;
12420   case SC_PrivateExtern:
12421     Error = 2;
12422     break;
12423   case SC_Auto:
12424     Error = 3;
12425     break;
12426   case SC_Register:
12427     Error = 4;
12428     break;
12429   }
12430   if (Error != -1) {
12431     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12432       << VD->getDeclName() << Error;
12433     D->setInvalidDecl();
12434   }
12435 }
12436 
12437 StmtResult
12438 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12439                                  IdentifierInfo *Ident,
12440                                  ParsedAttributes &Attrs,
12441                                  SourceLocation AttrEnd) {
12442   // C++1y [stmt.iter]p1:
12443   //   A range-based for statement of the form
12444   //      for ( for-range-identifier : for-range-initializer ) statement
12445   //   is equivalent to
12446   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12447   DeclSpec DS(Attrs.getPool().getFactory());
12448 
12449   const char *PrevSpec;
12450   unsigned DiagID;
12451   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12452                      getPrintingPolicy());
12453 
12454   Declarator D(DS, DeclaratorContext::ForContext);
12455   D.SetIdentifier(Ident, IdentLoc);
12456   D.takeAttributes(Attrs, AttrEnd);
12457 
12458   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12459                 IdentLoc);
12460   Decl *Var = ActOnDeclarator(S, D);
12461   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12462   FinalizeDeclaration(Var);
12463   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12464                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12465 }
12466 
12467 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12468   if (var->isInvalidDecl()) return;
12469 
12470   if (getLangOpts().OpenCL) {
12471     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12472     // initialiser
12473     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12474         !var->hasInit()) {
12475       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12476           << 1 /*Init*/;
12477       var->setInvalidDecl();
12478       return;
12479     }
12480   }
12481 
12482   // In Objective-C, don't allow jumps past the implicit initialization of a
12483   // local retaining variable.
12484   if (getLangOpts().ObjC &&
12485       var->hasLocalStorage()) {
12486     switch (var->getType().getObjCLifetime()) {
12487     case Qualifiers::OCL_None:
12488     case Qualifiers::OCL_ExplicitNone:
12489     case Qualifiers::OCL_Autoreleasing:
12490       break;
12491 
12492     case Qualifiers::OCL_Weak:
12493     case Qualifiers::OCL_Strong:
12494       setFunctionHasBranchProtectedScope();
12495       break;
12496     }
12497   }
12498 
12499   if (var->hasLocalStorage() &&
12500       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12501     setFunctionHasBranchProtectedScope();
12502 
12503   // Warn about externally-visible variables being defined without a
12504   // prior declaration.  We only want to do this for global
12505   // declarations, but we also specifically need to avoid doing it for
12506   // class members because the linkage of an anonymous class can
12507   // change if it's later given a typedef name.
12508   if (var->isThisDeclarationADefinition() &&
12509       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12510       var->isExternallyVisible() && var->hasLinkage() &&
12511       !var->isInline() && !var->getDescribedVarTemplate() &&
12512       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12513       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12514                                   var->getLocation())) {
12515     // Find a previous declaration that's not a definition.
12516     VarDecl *prev = var->getPreviousDecl();
12517     while (prev && prev->isThisDeclarationADefinition())
12518       prev = prev->getPreviousDecl();
12519 
12520     if (!prev) {
12521       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12522       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12523           << /* variable */ 0;
12524     }
12525   }
12526 
12527   // Cache the result of checking for constant initialization.
12528   Optional<bool> CacheHasConstInit;
12529   const Expr *CacheCulprit = nullptr;
12530   auto checkConstInit = [&]() mutable {
12531     if (!CacheHasConstInit)
12532       CacheHasConstInit = var->getInit()->isConstantInitializer(
12533             Context, var->getType()->isReferenceType(), &CacheCulprit);
12534     return *CacheHasConstInit;
12535   };
12536 
12537   if (var->getTLSKind() == VarDecl::TLS_Static) {
12538     if (var->getType().isDestructedType()) {
12539       // GNU C++98 edits for __thread, [basic.start.term]p3:
12540       //   The type of an object with thread storage duration shall not
12541       //   have a non-trivial destructor.
12542       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12543       if (getLangOpts().CPlusPlus11)
12544         Diag(var->getLocation(), diag::note_use_thread_local);
12545     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12546       if (!checkConstInit()) {
12547         // GNU C++98 edits for __thread, [basic.start.init]p4:
12548         //   An object of thread storage duration shall not require dynamic
12549         //   initialization.
12550         // FIXME: Need strict checking here.
12551         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12552           << CacheCulprit->getSourceRange();
12553         if (getLangOpts().CPlusPlus11)
12554           Diag(var->getLocation(), diag::note_use_thread_local);
12555       }
12556     }
12557   }
12558 
12559   // Apply section attributes and pragmas to global variables.
12560   bool GlobalStorage = var->hasGlobalStorage();
12561   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12562       !inTemplateInstantiation()) {
12563     PragmaStack<StringLiteral *> *Stack = nullptr;
12564     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12565     if (var->getType().isConstQualified())
12566       Stack = &ConstSegStack;
12567     else if (!var->getInit()) {
12568       Stack = &BSSSegStack;
12569       SectionFlags |= ASTContext::PSF_Write;
12570     } else {
12571       Stack = &DataSegStack;
12572       SectionFlags |= ASTContext::PSF_Write;
12573     }
12574     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12575       var->addAttr(SectionAttr::CreateImplicit(
12576           Context, Stack->CurrentValue->getString(),
12577           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12578           SectionAttr::Declspec_allocate));
12579     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12580       if (UnifySection(SA->getName(), SectionFlags, var))
12581         var->dropAttr<SectionAttr>();
12582 
12583     // Apply the init_seg attribute if this has an initializer.  If the
12584     // initializer turns out to not be dynamic, we'll end up ignoring this
12585     // attribute.
12586     if (CurInitSeg && var->getInit())
12587       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12588                                                CurInitSegLoc,
12589                                                AttributeCommonInfo::AS_Pragma));
12590   }
12591 
12592   // All the following checks are C++ only.
12593   if (!getLangOpts().CPlusPlus) {
12594       // If this variable must be emitted, add it as an initializer for the
12595       // current module.
12596      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12597        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12598      return;
12599   }
12600 
12601   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12602     CheckCompleteDecompositionDeclaration(DD);
12603 
12604   QualType type = var->getType();
12605   if (type->isDependentType()) return;
12606 
12607   if (var->hasAttr<BlocksAttr>())
12608     getCurFunction()->addByrefBlockVar(var);
12609 
12610   Expr *Init = var->getInit();
12611   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12612   QualType baseType = Context.getBaseElementType(type);
12613 
12614   if (Init && !Init->isValueDependent()) {
12615     if (var->isConstexpr()) {
12616       SmallVector<PartialDiagnosticAt, 8> Notes;
12617       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12618         SourceLocation DiagLoc = var->getLocation();
12619         // If the note doesn't add any useful information other than a source
12620         // location, fold it into the primary diagnostic.
12621         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12622               diag::note_invalid_subexpr_in_const_expr) {
12623           DiagLoc = Notes[0].first;
12624           Notes.clear();
12625         }
12626         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12627           << var << Init->getSourceRange();
12628         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12629           Diag(Notes[I].first, Notes[I].second);
12630       }
12631     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12632       // Check whether the initializer of a const variable of integral or
12633       // enumeration type is an ICE now, since we can't tell whether it was
12634       // initialized by a constant expression if we check later.
12635       var->checkInitIsICE();
12636     }
12637 
12638     // Don't emit further diagnostics about constexpr globals since they
12639     // were just diagnosed.
12640     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12641       // FIXME: Need strict checking in C++03 here.
12642       bool DiagErr = getLangOpts().CPlusPlus11
12643           ? !var->checkInitIsICE() : !checkConstInit();
12644       if (DiagErr) {
12645         auto *Attr = var->getAttr<ConstInitAttr>();
12646         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12647           << Init->getSourceRange();
12648         Diag(Attr->getLocation(),
12649              diag::note_declared_required_constant_init_here)
12650             << Attr->getRange() << Attr->isConstinit();
12651         if (getLangOpts().CPlusPlus11) {
12652           APValue Value;
12653           SmallVector<PartialDiagnosticAt, 8> Notes;
12654           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12655           for (auto &it : Notes)
12656             Diag(it.first, it.second);
12657         } else {
12658           Diag(CacheCulprit->getExprLoc(),
12659                diag::note_invalid_subexpr_in_const_expr)
12660               << CacheCulprit->getSourceRange();
12661         }
12662       }
12663     }
12664     else if (!var->isConstexpr() && IsGlobal &&
12665              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12666                                     var->getLocation())) {
12667       // Warn about globals which don't have a constant initializer.  Don't
12668       // warn about globals with a non-trivial destructor because we already
12669       // warned about them.
12670       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12671       if (!(RD && !RD->hasTrivialDestructor())) {
12672         if (!checkConstInit())
12673           Diag(var->getLocation(), diag::warn_global_constructor)
12674             << Init->getSourceRange();
12675       }
12676     }
12677   }
12678 
12679   // Require the destructor.
12680   if (const RecordType *recordType = baseType->getAs<RecordType>())
12681     FinalizeVarWithDestructor(var, recordType);
12682 
12683   // If this variable must be emitted, add it as an initializer for the current
12684   // module.
12685   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12686     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12687 }
12688 
12689 /// Determines if a variable's alignment is dependent.
12690 static bool hasDependentAlignment(VarDecl *VD) {
12691   if (VD->getType()->isDependentType())
12692     return true;
12693   for (auto *I : VD->specific_attrs<AlignedAttr>())
12694     if (I->isAlignmentDependent())
12695       return true;
12696   return false;
12697 }
12698 
12699 /// Check if VD needs to be dllexport/dllimport due to being in a
12700 /// dllexport/import function.
12701 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12702   assert(VD->isStaticLocal());
12703 
12704   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12705 
12706   // Find outermost function when VD is in lambda function.
12707   while (FD && !getDLLAttr(FD) &&
12708          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12709          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12710     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12711   }
12712 
12713   if (!FD)
12714     return;
12715 
12716   // Static locals inherit dll attributes from their function.
12717   if (Attr *A = getDLLAttr(FD)) {
12718     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12719     NewAttr->setInherited(true);
12720     VD->addAttr(NewAttr);
12721   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12722     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12723     NewAttr->setInherited(true);
12724     VD->addAttr(NewAttr);
12725 
12726     // Export this function to enforce exporting this static variable even
12727     // if it is not used in this compilation unit.
12728     if (!FD->hasAttr<DLLExportAttr>())
12729       FD->addAttr(NewAttr);
12730 
12731   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12732     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12733     NewAttr->setInherited(true);
12734     VD->addAttr(NewAttr);
12735   }
12736 }
12737 
12738 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12739 /// any semantic actions necessary after any initializer has been attached.
12740 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12741   // Note that we are no longer parsing the initializer for this declaration.
12742   ParsingInitForAutoVars.erase(ThisDecl);
12743 
12744   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12745   if (!VD)
12746     return;
12747 
12748   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12749   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12750       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12751     if (PragmaClangBSSSection.Valid)
12752       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12753           Context, PragmaClangBSSSection.SectionName,
12754           PragmaClangBSSSection.PragmaLocation,
12755           AttributeCommonInfo::AS_Pragma));
12756     if (PragmaClangDataSection.Valid)
12757       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12758           Context, PragmaClangDataSection.SectionName,
12759           PragmaClangDataSection.PragmaLocation,
12760           AttributeCommonInfo::AS_Pragma));
12761     if (PragmaClangRodataSection.Valid)
12762       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12763           Context, PragmaClangRodataSection.SectionName,
12764           PragmaClangRodataSection.PragmaLocation,
12765           AttributeCommonInfo::AS_Pragma));
12766     if (PragmaClangRelroSection.Valid)
12767       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12768           Context, PragmaClangRelroSection.SectionName,
12769           PragmaClangRelroSection.PragmaLocation,
12770           AttributeCommonInfo::AS_Pragma));
12771   }
12772 
12773   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12774     for (auto *BD : DD->bindings()) {
12775       FinalizeDeclaration(BD);
12776     }
12777   }
12778 
12779   checkAttributesAfterMerging(*this, *VD);
12780 
12781   // Perform TLS alignment check here after attributes attached to the variable
12782   // which may affect the alignment have been processed. Only perform the check
12783   // if the target has a maximum TLS alignment (zero means no constraints).
12784   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12785     // Protect the check so that it's not performed on dependent types and
12786     // dependent alignments (we can't determine the alignment in that case).
12787     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12788         !VD->isInvalidDecl()) {
12789       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12790       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12791         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12792           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12793           << (unsigned)MaxAlignChars.getQuantity();
12794       }
12795     }
12796   }
12797 
12798   if (VD->isStaticLocal()) {
12799     CheckStaticLocalForDllExport(VD);
12800 
12801     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12802       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12803       // function, only __shared__ variables or variables without any device
12804       // memory qualifiers may be declared with static storage class.
12805       // Note: It is unclear how a function-scope non-const static variable
12806       // without device memory qualifier is implemented, therefore only static
12807       // const variable without device memory qualifier is allowed.
12808       [&]() {
12809         if (!getLangOpts().CUDA)
12810           return;
12811         if (VD->hasAttr<CUDASharedAttr>())
12812           return;
12813         if (VD->getType().isConstQualified() &&
12814             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12815           return;
12816         if (CUDADiagIfDeviceCode(VD->getLocation(),
12817                                  diag::err_device_static_local_var)
12818             << CurrentCUDATarget())
12819           VD->setInvalidDecl();
12820       }();
12821     }
12822   }
12823 
12824   // Perform check for initializers of device-side global variables.
12825   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12826   // 7.5). We must also apply the same checks to all __shared__
12827   // variables whether they are local or not. CUDA also allows
12828   // constant initializers for __constant__ and __device__ variables.
12829   if (getLangOpts().CUDA)
12830     checkAllowedCUDAInitializer(VD);
12831 
12832   // Grab the dllimport or dllexport attribute off of the VarDecl.
12833   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12834 
12835   // Imported static data members cannot be defined out-of-line.
12836   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12837     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12838         VD->isThisDeclarationADefinition()) {
12839       // We allow definitions of dllimport class template static data members
12840       // with a warning.
12841       CXXRecordDecl *Context =
12842         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12843       bool IsClassTemplateMember =
12844           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12845           Context->getDescribedClassTemplate();
12846 
12847       Diag(VD->getLocation(),
12848            IsClassTemplateMember
12849                ? diag::warn_attribute_dllimport_static_field_definition
12850                : diag::err_attribute_dllimport_static_field_definition);
12851       Diag(IA->getLocation(), diag::note_attribute);
12852       if (!IsClassTemplateMember)
12853         VD->setInvalidDecl();
12854     }
12855   }
12856 
12857   // dllimport/dllexport variables cannot be thread local, their TLS index
12858   // isn't exported with the variable.
12859   if (DLLAttr && VD->getTLSKind()) {
12860     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12861     if (F && getDLLAttr(F)) {
12862       assert(VD->isStaticLocal());
12863       // But if this is a static local in a dlimport/dllexport function, the
12864       // function will never be inlined, which means the var would never be
12865       // imported, so having it marked import/export is safe.
12866     } else {
12867       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12868                                                                     << DLLAttr;
12869       VD->setInvalidDecl();
12870     }
12871   }
12872 
12873   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12874     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12875       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12876       VD->dropAttr<UsedAttr>();
12877     }
12878   }
12879 
12880   const DeclContext *DC = VD->getDeclContext();
12881   // If there's a #pragma GCC visibility in scope, and this isn't a class
12882   // member, set the visibility of this variable.
12883   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12884     AddPushedVisibilityAttribute(VD);
12885 
12886   // FIXME: Warn on unused var template partial specializations.
12887   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12888     MarkUnusedFileScopedDecl(VD);
12889 
12890   // Now we have parsed the initializer and can update the table of magic
12891   // tag values.
12892   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12893       !VD->getType()->isIntegralOrEnumerationType())
12894     return;
12895 
12896   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12897     const Expr *MagicValueExpr = VD->getInit();
12898     if (!MagicValueExpr) {
12899       continue;
12900     }
12901     llvm::APSInt MagicValueInt;
12902     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12903       Diag(I->getRange().getBegin(),
12904            diag::err_type_tag_for_datatype_not_ice)
12905         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12906       continue;
12907     }
12908     if (MagicValueInt.getActiveBits() > 64) {
12909       Diag(I->getRange().getBegin(),
12910            diag::err_type_tag_for_datatype_too_large)
12911         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12912       continue;
12913     }
12914     uint64_t MagicValue = MagicValueInt.getZExtValue();
12915     RegisterTypeTagForDatatype(I->getArgumentKind(),
12916                                MagicValue,
12917                                I->getMatchingCType(),
12918                                I->getLayoutCompatible(),
12919                                I->getMustBeNull());
12920   }
12921 }
12922 
12923 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12924   auto *VD = dyn_cast<VarDecl>(DD);
12925   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12926 }
12927 
12928 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12929                                                    ArrayRef<Decl *> Group) {
12930   SmallVector<Decl*, 8> Decls;
12931 
12932   if (DS.isTypeSpecOwned())
12933     Decls.push_back(DS.getRepAsDecl());
12934 
12935   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12936   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12937   bool DiagnosedMultipleDecomps = false;
12938   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12939   bool DiagnosedNonDeducedAuto = false;
12940 
12941   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12942     if (Decl *D = Group[i]) {
12943       // For declarators, there are some additional syntactic-ish checks we need
12944       // to perform.
12945       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12946         if (!FirstDeclaratorInGroup)
12947           FirstDeclaratorInGroup = DD;
12948         if (!FirstDecompDeclaratorInGroup)
12949           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12950         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12951             !hasDeducedAuto(DD))
12952           FirstNonDeducedAutoInGroup = DD;
12953 
12954         if (FirstDeclaratorInGroup != DD) {
12955           // A decomposition declaration cannot be combined with any other
12956           // declaration in the same group.
12957           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12958             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12959                  diag::err_decomp_decl_not_alone)
12960                 << FirstDeclaratorInGroup->getSourceRange()
12961                 << DD->getSourceRange();
12962             DiagnosedMultipleDecomps = true;
12963           }
12964 
12965           // A declarator that uses 'auto' in any way other than to declare a
12966           // variable with a deduced type cannot be combined with any other
12967           // declarator in the same group.
12968           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12969             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12970                  diag::err_auto_non_deduced_not_alone)
12971                 << FirstNonDeducedAutoInGroup->getType()
12972                        ->hasAutoForTrailingReturnType()
12973                 << FirstDeclaratorInGroup->getSourceRange()
12974                 << DD->getSourceRange();
12975             DiagnosedNonDeducedAuto = true;
12976           }
12977         }
12978       }
12979 
12980       Decls.push_back(D);
12981     }
12982   }
12983 
12984   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12985     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12986       handleTagNumbering(Tag, S);
12987       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12988           getLangOpts().CPlusPlus)
12989         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12990     }
12991   }
12992 
12993   return BuildDeclaratorGroup(Decls);
12994 }
12995 
12996 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12997 /// group, performing any necessary semantic checking.
12998 Sema::DeclGroupPtrTy
12999 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13000   // C++14 [dcl.spec.auto]p7: (DR1347)
13001   //   If the type that replaces the placeholder type is not the same in each
13002   //   deduction, the program is ill-formed.
13003   if (Group.size() > 1) {
13004     QualType Deduced;
13005     VarDecl *DeducedDecl = nullptr;
13006     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13007       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13008       if (!D || D->isInvalidDecl())
13009         break;
13010       DeducedType *DT = D->getType()->getContainedDeducedType();
13011       if (!DT || DT->getDeducedType().isNull())
13012         continue;
13013       if (Deduced.isNull()) {
13014         Deduced = DT->getDeducedType();
13015         DeducedDecl = D;
13016       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13017         auto *AT = dyn_cast<AutoType>(DT);
13018         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13019              diag::err_auto_different_deductions)
13020           << (AT ? (unsigned)AT->getKeyword() : 3)
13021           << Deduced << DeducedDecl->getDeclName()
13022           << DT->getDeducedType() << D->getDeclName()
13023           << DeducedDecl->getInit()->getSourceRange()
13024           << D->getInit()->getSourceRange();
13025         D->setInvalidDecl();
13026         break;
13027       }
13028     }
13029   }
13030 
13031   ActOnDocumentableDecls(Group);
13032 
13033   return DeclGroupPtrTy::make(
13034       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13035 }
13036 
13037 void Sema::ActOnDocumentableDecl(Decl *D) {
13038   ActOnDocumentableDecls(D);
13039 }
13040 
13041 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13042   // Don't parse the comment if Doxygen diagnostics are ignored.
13043   if (Group.empty() || !Group[0])
13044     return;
13045 
13046   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13047                       Group[0]->getLocation()) &&
13048       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13049                       Group[0]->getLocation()))
13050     return;
13051 
13052   if (Group.size() >= 2) {
13053     // This is a decl group.  Normally it will contain only declarations
13054     // produced from declarator list.  But in case we have any definitions or
13055     // additional declaration references:
13056     //   'typedef struct S {} S;'
13057     //   'typedef struct S *S;'
13058     //   'struct S *pS;'
13059     // FinalizeDeclaratorGroup adds these as separate declarations.
13060     Decl *MaybeTagDecl = Group[0];
13061     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13062       Group = Group.slice(1);
13063     }
13064   }
13065 
13066   // FIMXE: We assume every Decl in the group is in the same file.
13067   // This is false when preprocessor constructs the group from decls in
13068   // different files (e. g. macros or #include).
13069   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13070 }
13071 
13072 /// Common checks for a parameter-declaration that should apply to both function
13073 /// parameters and non-type template parameters.
13074 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13075   // Check that there are no default arguments inside the type of this
13076   // parameter.
13077   if (getLangOpts().CPlusPlus)
13078     CheckExtraCXXDefaultArguments(D);
13079 
13080   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13081   if (D.getCXXScopeSpec().isSet()) {
13082     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13083       << D.getCXXScopeSpec().getRange();
13084   }
13085 
13086   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13087   // simple identifier except [...irrelevant cases...].
13088   switch (D.getName().getKind()) {
13089   case UnqualifiedIdKind::IK_Identifier:
13090     break;
13091 
13092   case UnqualifiedIdKind::IK_OperatorFunctionId:
13093   case UnqualifiedIdKind::IK_ConversionFunctionId:
13094   case UnqualifiedIdKind::IK_LiteralOperatorId:
13095   case UnqualifiedIdKind::IK_ConstructorName:
13096   case UnqualifiedIdKind::IK_DestructorName:
13097   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13098   case UnqualifiedIdKind::IK_DeductionGuideName:
13099     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13100       << GetNameForDeclarator(D).getName();
13101     break;
13102 
13103   case UnqualifiedIdKind::IK_TemplateId:
13104   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13105     // GetNameForDeclarator would not produce a useful name in this case.
13106     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13107     break;
13108   }
13109 }
13110 
13111 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13112 /// to introduce parameters into function prototype scope.
13113 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13114   const DeclSpec &DS = D.getDeclSpec();
13115 
13116   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13117 
13118   // C++03 [dcl.stc]p2 also permits 'auto'.
13119   StorageClass SC = SC_None;
13120   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13121     SC = SC_Register;
13122     // In C++11, the 'register' storage class specifier is deprecated.
13123     // In C++17, it is not allowed, but we tolerate it as an extension.
13124     if (getLangOpts().CPlusPlus11) {
13125       Diag(DS.getStorageClassSpecLoc(),
13126            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13127                                      : diag::warn_deprecated_register)
13128         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13129     }
13130   } else if (getLangOpts().CPlusPlus &&
13131              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13132     SC = SC_Auto;
13133   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13134     Diag(DS.getStorageClassSpecLoc(),
13135          diag::err_invalid_storage_class_in_func_decl);
13136     D.getMutableDeclSpec().ClearStorageClassSpecs();
13137   }
13138 
13139   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13140     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13141       << DeclSpec::getSpecifierName(TSCS);
13142   if (DS.isInlineSpecified())
13143     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13144         << getLangOpts().CPlusPlus17;
13145   if (DS.hasConstexprSpecifier())
13146     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13147         << 0 << D.getDeclSpec().getConstexprSpecifier();
13148 
13149   DiagnoseFunctionSpecifiers(DS);
13150 
13151   CheckFunctionOrTemplateParamDeclarator(S, D);
13152 
13153   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13154   QualType parmDeclType = TInfo->getType();
13155 
13156   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13157   IdentifierInfo *II = D.getIdentifier();
13158   if (II) {
13159     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13160                    ForVisibleRedeclaration);
13161     LookupName(R, S);
13162     if (R.isSingleResult()) {
13163       NamedDecl *PrevDecl = R.getFoundDecl();
13164       if (PrevDecl->isTemplateParameter()) {
13165         // Maybe we will complain about the shadowed template parameter.
13166         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13167         // Just pretend that we didn't see the previous declaration.
13168         PrevDecl = nullptr;
13169       } else if (S->isDeclScope(PrevDecl)) {
13170         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13171         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13172 
13173         // Recover by removing the name
13174         II = nullptr;
13175         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13176         D.setInvalidType(true);
13177       }
13178     }
13179   }
13180 
13181   // Temporarily put parameter variables in the translation unit, not
13182   // the enclosing context.  This prevents them from accidentally
13183   // looking like class members in C++.
13184   ParmVarDecl *New =
13185       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13186                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13187 
13188   if (D.isInvalidType())
13189     New->setInvalidDecl();
13190 
13191   assert(S->isFunctionPrototypeScope());
13192   assert(S->getFunctionPrototypeDepth() >= 1);
13193   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13194                     S->getNextFunctionPrototypeIndex());
13195 
13196   // Add the parameter declaration into this scope.
13197   S->AddDecl(New);
13198   if (II)
13199     IdResolver.AddDecl(New);
13200 
13201   ProcessDeclAttributes(S, New, D);
13202 
13203   if (D.getDeclSpec().isModulePrivateSpecified())
13204     Diag(New->getLocation(), diag::err_module_private_local)
13205       << 1 << New->getDeclName()
13206       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13207       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13208 
13209   if (New->hasAttr<BlocksAttr>()) {
13210     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13211   }
13212 
13213   if (getLangOpts().OpenCL)
13214     deduceOpenCLAddressSpace(New);
13215 
13216   return New;
13217 }
13218 
13219 /// Synthesizes a variable for a parameter arising from a
13220 /// typedef.
13221 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13222                                               SourceLocation Loc,
13223                                               QualType T) {
13224   /* FIXME: setting StartLoc == Loc.
13225      Would it be worth to modify callers so as to provide proper source
13226      location for the unnamed parameters, embedding the parameter's type? */
13227   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13228                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13229                                            SC_None, nullptr);
13230   Param->setImplicit();
13231   return Param;
13232 }
13233 
13234 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13235   // Don't diagnose unused-parameter errors in template instantiations; we
13236   // will already have done so in the template itself.
13237   if (inTemplateInstantiation())
13238     return;
13239 
13240   for (const ParmVarDecl *Parameter : Parameters) {
13241     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13242         !Parameter->hasAttr<UnusedAttr>()) {
13243       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13244         << Parameter->getDeclName();
13245     }
13246   }
13247 }
13248 
13249 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13250     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13251   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13252     return;
13253 
13254   // Warn if the return value is pass-by-value and larger than the specified
13255   // threshold.
13256   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13257     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13258     if (Size > LangOpts.NumLargeByValueCopy)
13259       Diag(D->getLocation(), diag::warn_return_value_size)
13260           << D->getDeclName() << Size;
13261   }
13262 
13263   // Warn if any parameter is pass-by-value and larger than the specified
13264   // threshold.
13265   for (const ParmVarDecl *Parameter : Parameters) {
13266     QualType T = Parameter->getType();
13267     if (T->isDependentType() || !T.isPODType(Context))
13268       continue;
13269     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13270     if (Size > LangOpts.NumLargeByValueCopy)
13271       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13272           << Parameter->getDeclName() << Size;
13273   }
13274 }
13275 
13276 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13277                                   SourceLocation NameLoc, IdentifierInfo *Name,
13278                                   QualType T, TypeSourceInfo *TSInfo,
13279                                   StorageClass SC) {
13280   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13281   if (getLangOpts().ObjCAutoRefCount &&
13282       T.getObjCLifetime() == Qualifiers::OCL_None &&
13283       T->isObjCLifetimeType()) {
13284 
13285     Qualifiers::ObjCLifetime lifetime;
13286 
13287     // Special cases for arrays:
13288     //   - if it's const, use __unsafe_unretained
13289     //   - otherwise, it's an error
13290     if (T->isArrayType()) {
13291       if (!T.isConstQualified()) {
13292         if (DelayedDiagnostics.shouldDelayDiagnostics())
13293           DelayedDiagnostics.add(
13294               sema::DelayedDiagnostic::makeForbiddenType(
13295               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13296         else
13297           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13298               << TSInfo->getTypeLoc().getSourceRange();
13299       }
13300       lifetime = Qualifiers::OCL_ExplicitNone;
13301     } else {
13302       lifetime = T->getObjCARCImplicitLifetime();
13303     }
13304     T = Context.getLifetimeQualifiedType(T, lifetime);
13305   }
13306 
13307   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13308                                          Context.getAdjustedParameterType(T),
13309                                          TSInfo, SC, nullptr);
13310 
13311   // Make a note if we created a new pack in the scope of a lambda, so that
13312   // we know that references to that pack must also be expanded within the
13313   // lambda scope.
13314   if (New->isParameterPack())
13315     if (auto *LSI = getEnclosingLambda())
13316       LSI->LocalPacks.push_back(New);
13317 
13318   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13319       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13320     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13321                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13322 
13323   // Parameters can not be abstract class types.
13324   // For record types, this is done by the AbstractClassUsageDiagnoser once
13325   // the class has been completely parsed.
13326   if (!CurContext->isRecord() &&
13327       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13328                              AbstractParamType))
13329     New->setInvalidDecl();
13330 
13331   // Parameter declarators cannot be interface types. All ObjC objects are
13332   // passed by reference.
13333   if (T->isObjCObjectType()) {
13334     SourceLocation TypeEndLoc =
13335         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13336     Diag(NameLoc,
13337          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13338       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13339     T = Context.getObjCObjectPointerType(T);
13340     New->setType(T);
13341   }
13342 
13343   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13344   // duration shall not be qualified by an address-space qualifier."
13345   // Since all parameters have automatic store duration, they can not have
13346   // an address space.
13347   if (T.getAddressSpace() != LangAS::Default &&
13348       // OpenCL allows function arguments declared to be an array of a type
13349       // to be qualified with an address space.
13350       !(getLangOpts().OpenCL &&
13351         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13352     Diag(NameLoc, diag::err_arg_with_address_space);
13353     New->setInvalidDecl();
13354   }
13355 
13356   return New;
13357 }
13358 
13359 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13360                                            SourceLocation LocAfterDecls) {
13361   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13362 
13363   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13364   // for a K&R function.
13365   if (!FTI.hasPrototype) {
13366     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13367       --i;
13368       if (FTI.Params[i].Param == nullptr) {
13369         SmallString<256> Code;
13370         llvm::raw_svector_ostream(Code)
13371             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13372         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13373             << FTI.Params[i].Ident
13374             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13375 
13376         // Implicitly declare the argument as type 'int' for lack of a better
13377         // type.
13378         AttributeFactory attrs;
13379         DeclSpec DS(attrs);
13380         const char* PrevSpec; // unused
13381         unsigned DiagID; // unused
13382         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13383                            DiagID, Context.getPrintingPolicy());
13384         // Use the identifier location for the type source range.
13385         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13386         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13387         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13388         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13389         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13390       }
13391     }
13392   }
13393 }
13394 
13395 Decl *
13396 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13397                               MultiTemplateParamsArg TemplateParameterLists,
13398                               SkipBodyInfo *SkipBody) {
13399   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13400   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13401   Scope *ParentScope = FnBodyScope->getParent();
13402 
13403   D.setFunctionDefinitionKind(FDK_Definition);
13404   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13405   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13406 }
13407 
13408 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13409   Consumer.HandleInlineFunctionDefinition(D);
13410 }
13411 
13412 static bool
13413 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13414                                 const FunctionDecl *&PossiblePrototype) {
13415   // Don't warn about invalid declarations.
13416   if (FD->isInvalidDecl())
13417     return false;
13418 
13419   // Or declarations that aren't global.
13420   if (!FD->isGlobal())
13421     return false;
13422 
13423   // Don't warn about C++ member functions.
13424   if (isa<CXXMethodDecl>(FD))
13425     return false;
13426 
13427   // Don't warn about 'main'.
13428   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13429     if (IdentifierInfo *II = FD->getIdentifier())
13430       if (II->isStr("main"))
13431         return false;
13432 
13433   // Don't warn about inline functions.
13434   if (FD->isInlined())
13435     return false;
13436 
13437   // Don't warn about function templates.
13438   if (FD->getDescribedFunctionTemplate())
13439     return false;
13440 
13441   // Don't warn about function template specializations.
13442   if (FD->isFunctionTemplateSpecialization())
13443     return false;
13444 
13445   // Don't warn for OpenCL kernels.
13446   if (FD->hasAttr<OpenCLKernelAttr>())
13447     return false;
13448 
13449   // Don't warn on explicitly deleted functions.
13450   if (FD->isDeleted())
13451     return false;
13452 
13453   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13454        Prev; Prev = Prev->getPreviousDecl()) {
13455     // Ignore any declarations that occur in function or method
13456     // scope, because they aren't visible from the header.
13457     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13458       continue;
13459 
13460     PossiblePrototype = Prev;
13461     return Prev->getType()->isFunctionNoProtoType();
13462   }
13463 
13464   return true;
13465 }
13466 
13467 void
13468 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13469                                    const FunctionDecl *EffectiveDefinition,
13470                                    SkipBodyInfo *SkipBody) {
13471   const FunctionDecl *Definition = EffectiveDefinition;
13472   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13473     // If this is a friend function defined in a class template, it does not
13474     // have a body until it is used, nevertheless it is a definition, see
13475     // [temp.inst]p2:
13476     //
13477     // ... for the purpose of determining whether an instantiated redeclaration
13478     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13479     // corresponds to a definition in the template is considered to be a
13480     // definition.
13481     //
13482     // The following code must produce redefinition error:
13483     //
13484     //     template<typename T> struct C20 { friend void func_20() {} };
13485     //     C20<int> c20i;
13486     //     void func_20() {}
13487     //
13488     for (auto I : FD->redecls()) {
13489       if (I != FD && !I->isInvalidDecl() &&
13490           I->getFriendObjectKind() != Decl::FOK_None) {
13491         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13492           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13493             // A merged copy of the same function, instantiated as a member of
13494             // the same class, is OK.
13495             if (declaresSameEntity(OrigFD, Original) &&
13496                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13497                                    cast<Decl>(FD->getLexicalDeclContext())))
13498               continue;
13499           }
13500 
13501           if (Original->isThisDeclarationADefinition()) {
13502             Definition = I;
13503             break;
13504           }
13505         }
13506       }
13507     }
13508   }
13509 
13510   if (!Definition)
13511     // Similar to friend functions a friend function template may be a
13512     // definition and do not have a body if it is instantiated in a class
13513     // template.
13514     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13515       for (auto I : FTD->redecls()) {
13516         auto D = cast<FunctionTemplateDecl>(I);
13517         if (D != FTD) {
13518           assert(!D->isThisDeclarationADefinition() &&
13519                  "More than one definition in redeclaration chain");
13520           if (D->getFriendObjectKind() != Decl::FOK_None)
13521             if (FunctionTemplateDecl *FT =
13522                                        D->getInstantiatedFromMemberTemplate()) {
13523               if (FT->isThisDeclarationADefinition()) {
13524                 Definition = D->getTemplatedDecl();
13525                 break;
13526               }
13527             }
13528         }
13529       }
13530     }
13531 
13532   if (!Definition)
13533     return;
13534 
13535   if (canRedefineFunction(Definition, getLangOpts()))
13536     return;
13537 
13538   // Don't emit an error when this is redefinition of a typo-corrected
13539   // definition.
13540   if (TypoCorrectedFunctionDefinitions.count(Definition))
13541     return;
13542 
13543   // If we don't have a visible definition of the function, and it's inline or
13544   // a template, skip the new definition.
13545   if (SkipBody && !hasVisibleDefinition(Definition) &&
13546       (Definition->getFormalLinkage() == InternalLinkage ||
13547        Definition->isInlined() ||
13548        Definition->getDescribedFunctionTemplate() ||
13549        Definition->getNumTemplateParameterLists())) {
13550     SkipBody->ShouldSkip = true;
13551     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13552     if (auto *TD = Definition->getDescribedFunctionTemplate())
13553       makeMergedDefinitionVisible(TD);
13554     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13555     return;
13556   }
13557 
13558   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13559       Definition->getStorageClass() == SC_Extern)
13560     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13561         << FD->getDeclName() << getLangOpts().CPlusPlus;
13562   else
13563     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13564 
13565   Diag(Definition->getLocation(), diag::note_previous_definition);
13566   FD->setInvalidDecl();
13567 }
13568 
13569 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13570                                    Sema &S) {
13571   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13572 
13573   LambdaScopeInfo *LSI = S.PushLambdaScope();
13574   LSI->CallOperator = CallOperator;
13575   LSI->Lambda = LambdaClass;
13576   LSI->ReturnType = CallOperator->getReturnType();
13577   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13578 
13579   if (LCD == LCD_None)
13580     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13581   else if (LCD == LCD_ByCopy)
13582     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13583   else if (LCD == LCD_ByRef)
13584     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13585   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13586 
13587   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13588   LSI->Mutable = !CallOperator->isConst();
13589 
13590   // Add the captures to the LSI so they can be noted as already
13591   // captured within tryCaptureVar.
13592   auto I = LambdaClass->field_begin();
13593   for (const auto &C : LambdaClass->captures()) {
13594     if (C.capturesVariable()) {
13595       VarDecl *VD = C.getCapturedVar();
13596       if (VD->isInitCapture())
13597         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13598       QualType CaptureType = VD->getType();
13599       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13600       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13601           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13602           /*EllipsisLoc*/C.isPackExpansion()
13603                          ? C.getEllipsisLoc() : SourceLocation(),
13604           CaptureType, /*Invalid*/false);
13605 
13606     } else if (C.capturesThis()) {
13607       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13608                           C.getCaptureKind() == LCK_StarThis);
13609     } else {
13610       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13611                              I->getType());
13612     }
13613     ++I;
13614   }
13615 }
13616 
13617 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13618                                     SkipBodyInfo *SkipBody) {
13619   if (!D) {
13620     // Parsing the function declaration failed in some way. Push on a fake scope
13621     // anyway so we can try to parse the function body.
13622     PushFunctionScope();
13623     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13624     return D;
13625   }
13626 
13627   FunctionDecl *FD = nullptr;
13628 
13629   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13630     FD = FunTmpl->getTemplatedDecl();
13631   else
13632     FD = cast<FunctionDecl>(D);
13633 
13634   // Do not push if it is a lambda because one is already pushed when building
13635   // the lambda in ActOnStartOfLambdaDefinition().
13636   if (!isLambdaCallOperator(FD))
13637     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13638 
13639   // Check for defining attributes before the check for redefinition.
13640   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13641     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13642     FD->dropAttr<AliasAttr>();
13643     FD->setInvalidDecl();
13644   }
13645   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13646     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13647     FD->dropAttr<IFuncAttr>();
13648     FD->setInvalidDecl();
13649   }
13650 
13651   // See if this is a redefinition. If 'will have body' is already set, then
13652   // these checks were already performed when it was set.
13653   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13654     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13655 
13656     // If we're skipping the body, we're done. Don't enter the scope.
13657     if (SkipBody && SkipBody->ShouldSkip)
13658       return D;
13659   }
13660 
13661   // Mark this function as "will have a body eventually".  This lets users to
13662   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13663   // this function.
13664   FD->setWillHaveBody();
13665 
13666   // If we are instantiating a generic lambda call operator, push
13667   // a LambdaScopeInfo onto the function stack.  But use the information
13668   // that's already been calculated (ActOnLambdaExpr) to prime the current
13669   // LambdaScopeInfo.
13670   // When the template operator is being specialized, the LambdaScopeInfo,
13671   // has to be properly restored so that tryCaptureVariable doesn't try
13672   // and capture any new variables. In addition when calculating potential
13673   // captures during transformation of nested lambdas, it is necessary to
13674   // have the LSI properly restored.
13675   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13676     assert(inTemplateInstantiation() &&
13677            "There should be an active template instantiation on the stack "
13678            "when instantiating a generic lambda!");
13679     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13680   } else {
13681     // Enter a new function scope
13682     PushFunctionScope();
13683   }
13684 
13685   // Builtin functions cannot be defined.
13686   if (unsigned BuiltinID = FD->getBuiltinID()) {
13687     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13688         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13689       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13690       FD->setInvalidDecl();
13691     }
13692   }
13693 
13694   // The return type of a function definition must be complete
13695   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13696   QualType ResultType = FD->getReturnType();
13697   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13698       !FD->isInvalidDecl() &&
13699       RequireCompleteType(FD->getLocation(), ResultType,
13700                           diag::err_func_def_incomplete_result))
13701     FD->setInvalidDecl();
13702 
13703   if (FnBodyScope)
13704     PushDeclContext(FnBodyScope, FD);
13705 
13706   // Check the validity of our function parameters
13707   CheckParmsForFunctionDef(FD->parameters(),
13708                            /*CheckParameterNames=*/true);
13709 
13710   // Add non-parameter declarations already in the function to the current
13711   // scope.
13712   if (FnBodyScope) {
13713     for (Decl *NPD : FD->decls()) {
13714       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13715       if (!NonParmDecl)
13716         continue;
13717       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13718              "parameters should not be in newly created FD yet");
13719 
13720       // If the decl has a name, make it accessible in the current scope.
13721       if (NonParmDecl->getDeclName())
13722         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13723 
13724       // Similarly, dive into enums and fish their constants out, making them
13725       // accessible in this scope.
13726       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13727         for (auto *EI : ED->enumerators())
13728           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13729       }
13730     }
13731   }
13732 
13733   // Introduce our parameters into the function scope
13734   for (auto Param : FD->parameters()) {
13735     Param->setOwningFunction(FD);
13736 
13737     // If this has an identifier, add it to the scope stack.
13738     if (Param->getIdentifier() && FnBodyScope) {
13739       CheckShadow(FnBodyScope, Param);
13740 
13741       PushOnScopeChains(Param, FnBodyScope);
13742     }
13743   }
13744 
13745   // Ensure that the function's exception specification is instantiated.
13746   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13747     ResolveExceptionSpec(D->getLocation(), FPT);
13748 
13749   // dllimport cannot be applied to non-inline function definitions.
13750   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13751       !FD->isTemplateInstantiation()) {
13752     assert(!FD->hasAttr<DLLExportAttr>());
13753     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13754     FD->setInvalidDecl();
13755     return D;
13756   }
13757   // We want to attach documentation to original Decl (which might be
13758   // a function template).
13759   ActOnDocumentableDecl(D);
13760   if (getCurLexicalContext()->isObjCContainer() &&
13761       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13762       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13763     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13764 
13765   return D;
13766 }
13767 
13768 /// Given the set of return statements within a function body,
13769 /// compute the variables that are subject to the named return value
13770 /// optimization.
13771 ///
13772 /// Each of the variables that is subject to the named return value
13773 /// optimization will be marked as NRVO variables in the AST, and any
13774 /// return statement that has a marked NRVO variable as its NRVO candidate can
13775 /// use the named return value optimization.
13776 ///
13777 /// This function applies a very simplistic algorithm for NRVO: if every return
13778 /// statement in the scope of a variable has the same NRVO candidate, that
13779 /// candidate is an NRVO variable.
13780 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13781   ReturnStmt **Returns = Scope->Returns.data();
13782 
13783   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13784     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13785       if (!NRVOCandidate->isNRVOVariable())
13786         Returns[I]->setNRVOCandidate(nullptr);
13787     }
13788   }
13789 }
13790 
13791 bool Sema::canDelayFunctionBody(const Declarator &D) {
13792   // We can't delay parsing the body of a constexpr function template (yet).
13793   if (D.getDeclSpec().hasConstexprSpecifier())
13794     return false;
13795 
13796   // We can't delay parsing the body of a function template with a deduced
13797   // return type (yet).
13798   if (D.getDeclSpec().hasAutoTypeSpec()) {
13799     // If the placeholder introduces a non-deduced trailing return type,
13800     // we can still delay parsing it.
13801     if (D.getNumTypeObjects()) {
13802       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13803       if (Outer.Kind == DeclaratorChunk::Function &&
13804           Outer.Fun.hasTrailingReturnType()) {
13805         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13806         return Ty.isNull() || !Ty->isUndeducedType();
13807       }
13808     }
13809     return false;
13810   }
13811 
13812   return true;
13813 }
13814 
13815 bool Sema::canSkipFunctionBody(Decl *D) {
13816   // We cannot skip the body of a function (or function template) which is
13817   // constexpr, since we may need to evaluate its body in order to parse the
13818   // rest of the file.
13819   // We cannot skip the body of a function with an undeduced return type,
13820   // because any callers of that function need to know the type.
13821   if (const FunctionDecl *FD = D->getAsFunction()) {
13822     if (FD->isConstexpr())
13823       return false;
13824     // We can't simply call Type::isUndeducedType here, because inside template
13825     // auto can be deduced to a dependent type, which is not considered
13826     // "undeduced".
13827     if (FD->getReturnType()->getContainedDeducedType())
13828       return false;
13829   }
13830   return Consumer.shouldSkipFunctionBody(D);
13831 }
13832 
13833 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13834   if (!Decl)
13835     return nullptr;
13836   if (FunctionDecl *FD = Decl->getAsFunction())
13837     FD->setHasSkippedBody();
13838   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13839     MD->setHasSkippedBody();
13840   return Decl;
13841 }
13842 
13843 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13844   return ActOnFinishFunctionBody(D, BodyArg, false);
13845 }
13846 
13847 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13848 /// body.
13849 class ExitFunctionBodyRAII {
13850 public:
13851   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13852   ~ExitFunctionBodyRAII() {
13853     if (!IsLambda)
13854       S.PopExpressionEvaluationContext();
13855   }
13856 
13857 private:
13858   Sema &S;
13859   bool IsLambda = false;
13860 };
13861 
13862 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13863   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13864 
13865   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13866     if (EscapeInfo.count(BD))
13867       return EscapeInfo[BD];
13868 
13869     bool R = false;
13870     const BlockDecl *CurBD = BD;
13871 
13872     do {
13873       R = !CurBD->doesNotEscape();
13874       if (R)
13875         break;
13876       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13877     } while (CurBD);
13878 
13879     return EscapeInfo[BD] = R;
13880   };
13881 
13882   // If the location where 'self' is implicitly retained is inside a escaping
13883   // block, emit a diagnostic.
13884   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13885        S.ImplicitlyRetainedSelfLocs)
13886     if (IsOrNestedInEscapingBlock(P.second))
13887       S.Diag(P.first, diag::warn_implicitly_retains_self)
13888           << FixItHint::CreateInsertion(P.first, "self->");
13889 }
13890 
13891 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13892                                     bool IsInstantiation) {
13893   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13894 
13895   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13896   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13897 
13898   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13899     CheckCompletedCoroutineBody(FD, Body);
13900 
13901   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13902   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13903   // meant to pop the context added in ActOnStartOfFunctionDef().
13904   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13905 
13906   if (FD) {
13907     FD->setBody(Body);
13908     FD->setWillHaveBody(false);
13909 
13910     if (getLangOpts().CPlusPlus14) {
13911       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13912           FD->getReturnType()->isUndeducedType()) {
13913         // If the function has a deduced result type but contains no 'return'
13914         // statements, the result type as written must be exactly 'auto', and
13915         // the deduced result type is 'void'.
13916         if (!FD->getReturnType()->getAs<AutoType>()) {
13917           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13918               << FD->getReturnType();
13919           FD->setInvalidDecl();
13920         } else {
13921           // Substitute 'void' for the 'auto' in the type.
13922           TypeLoc ResultType = getReturnTypeLoc(FD);
13923           Context.adjustDeducedFunctionResultType(
13924               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13925         }
13926       }
13927     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13928       // In C++11, we don't use 'auto' deduction rules for lambda call
13929       // operators because we don't support return type deduction.
13930       auto *LSI = getCurLambda();
13931       if (LSI->HasImplicitReturnType) {
13932         deduceClosureReturnType(*LSI);
13933 
13934         // C++11 [expr.prim.lambda]p4:
13935         //   [...] if there are no return statements in the compound-statement
13936         //   [the deduced type is] the type void
13937         QualType RetType =
13938             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13939 
13940         // Update the return type to the deduced type.
13941         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13942         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13943                                             Proto->getExtProtoInfo()));
13944       }
13945     }
13946 
13947     // If the function implicitly returns zero (like 'main') or is naked,
13948     // don't complain about missing return statements.
13949     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13950       WP.disableCheckFallThrough();
13951 
13952     // MSVC permits the use of pure specifier (=0) on function definition,
13953     // defined at class scope, warn about this non-standard construct.
13954     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13955       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13956 
13957     if (!FD->isInvalidDecl()) {
13958       // Don't diagnose unused parameters of defaulted or deleted functions.
13959       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13960         DiagnoseUnusedParameters(FD->parameters());
13961       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13962                                              FD->getReturnType(), FD);
13963 
13964       // If this is a structor, we need a vtable.
13965       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13966         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13967       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13968         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13969 
13970       // Try to apply the named return value optimization. We have to check
13971       // if we can do this here because lambdas keep return statements around
13972       // to deduce an implicit return type.
13973       if (FD->getReturnType()->isRecordType() &&
13974           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13975         computeNRVO(Body, getCurFunction());
13976     }
13977 
13978     // GNU warning -Wmissing-prototypes:
13979     //   Warn if a global function is defined without a previous
13980     //   prototype declaration. This warning is issued even if the
13981     //   definition itself provides a prototype. The aim is to detect
13982     //   global functions that fail to be declared in header files.
13983     const FunctionDecl *PossiblePrototype = nullptr;
13984     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13985       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13986 
13987       if (PossiblePrototype) {
13988         // We found a declaration that is not a prototype,
13989         // but that could be a zero-parameter prototype
13990         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13991           TypeLoc TL = TI->getTypeLoc();
13992           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13993             Diag(PossiblePrototype->getLocation(),
13994                  diag::note_declaration_not_a_prototype)
13995                 << (FD->getNumParams() != 0)
13996                 << (FD->getNumParams() == 0
13997                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13998                         : FixItHint{});
13999         }
14000       } else {
14001         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14002             << /* function */ 1
14003             << (FD->getStorageClass() == SC_None
14004                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14005                                                  "static ")
14006                     : FixItHint{});
14007       }
14008 
14009       // GNU warning -Wstrict-prototypes
14010       //   Warn if K&R function is defined without a previous declaration.
14011       //   This warning is issued only if the definition itself does not provide
14012       //   a prototype. Only K&R definitions do not provide a prototype.
14013       //   An empty list in a function declarator that is part of a definition
14014       //   of that function specifies that the function has no parameters
14015       //   (C99 6.7.5.3p14)
14016       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14017           !LangOpts.CPlusPlus) {
14018         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14019         TypeLoc TL = TI->getTypeLoc();
14020         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14021         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14022       }
14023     }
14024 
14025     // Warn on CPUDispatch with an actual body.
14026     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14027       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14028         if (!CmpndBody->body_empty())
14029           Diag(CmpndBody->body_front()->getBeginLoc(),
14030                diag::warn_dispatch_body_ignored);
14031 
14032     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14033       const CXXMethodDecl *KeyFunction;
14034       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14035           MD->isVirtual() &&
14036           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14037           MD == KeyFunction->getCanonicalDecl()) {
14038         // Update the key-function state if necessary for this ABI.
14039         if (FD->isInlined() &&
14040             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14041           Context.setNonKeyFunction(MD);
14042 
14043           // If the newly-chosen key function is already defined, then we
14044           // need to mark the vtable as used retroactively.
14045           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14046           const FunctionDecl *Definition;
14047           if (KeyFunction && KeyFunction->isDefined(Definition))
14048             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14049         } else {
14050           // We just defined they key function; mark the vtable as used.
14051           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14052         }
14053       }
14054     }
14055 
14056     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14057            "Function parsing confused");
14058   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14059     assert(MD == getCurMethodDecl() && "Method parsing confused");
14060     MD->setBody(Body);
14061     if (!MD->isInvalidDecl()) {
14062       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14063                                              MD->getReturnType(), MD);
14064 
14065       if (Body)
14066         computeNRVO(Body, getCurFunction());
14067     }
14068     if (getCurFunction()->ObjCShouldCallSuper) {
14069       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14070           << MD->getSelector().getAsString();
14071       getCurFunction()->ObjCShouldCallSuper = false;
14072     }
14073     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14074       const ObjCMethodDecl *InitMethod = nullptr;
14075       bool isDesignated =
14076           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14077       assert(isDesignated && InitMethod);
14078       (void)isDesignated;
14079 
14080       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14081         auto IFace = MD->getClassInterface();
14082         if (!IFace)
14083           return false;
14084         auto SuperD = IFace->getSuperClass();
14085         if (!SuperD)
14086           return false;
14087         return SuperD->getIdentifier() ==
14088             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14089       };
14090       // Don't issue this warning for unavailable inits or direct subclasses
14091       // of NSObject.
14092       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14093         Diag(MD->getLocation(),
14094              diag::warn_objc_designated_init_missing_super_call);
14095         Diag(InitMethod->getLocation(),
14096              diag::note_objc_designated_init_marked_here);
14097       }
14098       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14099     }
14100     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14101       // Don't issue this warning for unavaialable inits.
14102       if (!MD->isUnavailable())
14103         Diag(MD->getLocation(),
14104              diag::warn_objc_secondary_init_missing_init_call);
14105       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14106     }
14107 
14108     diagnoseImplicitlyRetainedSelf(*this);
14109   } else {
14110     // Parsing the function declaration failed in some way. Pop the fake scope
14111     // we pushed on.
14112     PopFunctionScopeInfo(ActivePolicy, dcl);
14113     return nullptr;
14114   }
14115 
14116   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14117     DiagnoseUnguardedAvailabilityViolations(dcl);
14118 
14119   assert(!getCurFunction()->ObjCShouldCallSuper &&
14120          "This should only be set for ObjC methods, which should have been "
14121          "handled in the block above.");
14122 
14123   // Verify and clean out per-function state.
14124   if (Body && (!FD || !FD->isDefaulted())) {
14125     // C++ constructors that have function-try-blocks can't have return
14126     // statements in the handlers of that block. (C++ [except.handle]p14)
14127     // Verify this.
14128     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14129       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14130 
14131     // Verify that gotos and switch cases don't jump into scopes illegally.
14132     if (getCurFunction()->NeedsScopeChecking() &&
14133         !PP.isCodeCompletionEnabled())
14134       DiagnoseInvalidJumps(Body);
14135 
14136     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14137       if (!Destructor->getParent()->isDependentType())
14138         CheckDestructor(Destructor);
14139 
14140       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14141                                              Destructor->getParent());
14142     }
14143 
14144     // If any errors have occurred, clear out any temporaries that may have
14145     // been leftover. This ensures that these temporaries won't be picked up for
14146     // deletion in some later function.
14147     if (getDiagnostics().hasErrorOccurred() ||
14148         getDiagnostics().getSuppressAllDiagnostics()) {
14149       DiscardCleanupsInEvaluationContext();
14150     }
14151     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14152         !isa<FunctionTemplateDecl>(dcl)) {
14153       // Since the body is valid, issue any analysis-based warnings that are
14154       // enabled.
14155       ActivePolicy = &WP;
14156     }
14157 
14158     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14159         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14160       FD->setInvalidDecl();
14161 
14162     if (FD && FD->hasAttr<NakedAttr>()) {
14163       for (const Stmt *S : Body->children()) {
14164         // Allow local register variables without initializer as they don't
14165         // require prologue.
14166         bool RegisterVariables = false;
14167         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14168           for (const auto *Decl : DS->decls()) {
14169             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14170               RegisterVariables =
14171                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14172               if (!RegisterVariables)
14173                 break;
14174             }
14175           }
14176         }
14177         if (RegisterVariables)
14178           continue;
14179         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14180           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14181           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14182           FD->setInvalidDecl();
14183           break;
14184         }
14185       }
14186     }
14187 
14188     assert(ExprCleanupObjects.size() ==
14189                ExprEvalContexts.back().NumCleanupObjects &&
14190            "Leftover temporaries in function");
14191     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14192     assert(MaybeODRUseExprs.empty() &&
14193            "Leftover expressions for odr-use checking");
14194   }
14195 
14196   if (!IsInstantiation)
14197     PopDeclContext();
14198 
14199   PopFunctionScopeInfo(ActivePolicy, dcl);
14200   // If any errors have occurred, clear out any temporaries that may have
14201   // been leftover. This ensures that these temporaries won't be picked up for
14202   // deletion in some later function.
14203   if (getDiagnostics().hasErrorOccurred()) {
14204     DiscardCleanupsInEvaluationContext();
14205   }
14206 
14207   return dcl;
14208 }
14209 
14210 /// When we finish delayed parsing of an attribute, we must attach it to the
14211 /// relevant Decl.
14212 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14213                                        ParsedAttributes &Attrs) {
14214   // Always attach attributes to the underlying decl.
14215   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14216     D = TD->getTemplatedDecl();
14217   ProcessDeclAttributeList(S, D, Attrs);
14218 
14219   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14220     if (Method->isStatic())
14221       checkThisInStaticMemberFunctionAttributes(Method);
14222 }
14223 
14224 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14225 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14226 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14227                                           IdentifierInfo &II, Scope *S) {
14228   // Find the scope in which the identifier is injected and the corresponding
14229   // DeclContext.
14230   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14231   // In that case, we inject the declaration into the translation unit scope
14232   // instead.
14233   Scope *BlockScope = S;
14234   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14235     BlockScope = BlockScope->getParent();
14236 
14237   Scope *ContextScope = BlockScope;
14238   while (!ContextScope->getEntity())
14239     ContextScope = ContextScope->getParent();
14240   ContextRAII SavedContext(*this, ContextScope->getEntity());
14241 
14242   // Before we produce a declaration for an implicitly defined
14243   // function, see whether there was a locally-scoped declaration of
14244   // this name as a function or variable. If so, use that
14245   // (non-visible) declaration, and complain about it.
14246   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14247   if (ExternCPrev) {
14248     // We still need to inject the function into the enclosing block scope so
14249     // that later (non-call) uses can see it.
14250     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14251 
14252     // C89 footnote 38:
14253     //   If in fact it is not defined as having type "function returning int",
14254     //   the behavior is undefined.
14255     if (!isa<FunctionDecl>(ExternCPrev) ||
14256         !Context.typesAreCompatible(
14257             cast<FunctionDecl>(ExternCPrev)->getType(),
14258             Context.getFunctionNoProtoType(Context.IntTy))) {
14259       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14260           << ExternCPrev << !getLangOpts().C99;
14261       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14262       return ExternCPrev;
14263     }
14264   }
14265 
14266   // Extension in C99.  Legal in C90, but warn about it.
14267   unsigned diag_id;
14268   if (II.getName().startswith("__builtin_"))
14269     diag_id = diag::warn_builtin_unknown;
14270   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14271   else if (getLangOpts().OpenCL)
14272     diag_id = diag::err_opencl_implicit_function_decl;
14273   else if (getLangOpts().C99)
14274     diag_id = diag::ext_implicit_function_decl;
14275   else
14276     diag_id = diag::warn_implicit_function_decl;
14277   Diag(Loc, diag_id) << &II;
14278 
14279   // If we found a prior declaration of this function, don't bother building
14280   // another one. We've already pushed that one into scope, so there's nothing
14281   // more to do.
14282   if (ExternCPrev)
14283     return ExternCPrev;
14284 
14285   // Because typo correction is expensive, only do it if the implicit
14286   // function declaration is going to be treated as an error.
14287   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14288     TypoCorrection Corrected;
14289     DeclFilterCCC<FunctionDecl> CCC{};
14290     if (S && (Corrected =
14291                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14292                               S, nullptr, CCC, CTK_NonError)))
14293       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14294                    /*ErrorRecovery*/false);
14295   }
14296 
14297   // Set a Declarator for the implicit definition: int foo();
14298   const char *Dummy;
14299   AttributeFactory attrFactory;
14300   DeclSpec DS(attrFactory);
14301   unsigned DiagID;
14302   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14303                                   Context.getPrintingPolicy());
14304   (void)Error; // Silence warning.
14305   assert(!Error && "Error setting up implicit decl!");
14306   SourceLocation NoLoc;
14307   Declarator D(DS, DeclaratorContext::BlockContext);
14308   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14309                                              /*IsAmbiguous=*/false,
14310                                              /*LParenLoc=*/NoLoc,
14311                                              /*Params=*/nullptr,
14312                                              /*NumParams=*/0,
14313                                              /*EllipsisLoc=*/NoLoc,
14314                                              /*RParenLoc=*/NoLoc,
14315                                              /*RefQualifierIsLvalueRef=*/true,
14316                                              /*RefQualifierLoc=*/NoLoc,
14317                                              /*MutableLoc=*/NoLoc, EST_None,
14318                                              /*ESpecRange=*/SourceRange(),
14319                                              /*Exceptions=*/nullptr,
14320                                              /*ExceptionRanges=*/nullptr,
14321                                              /*NumExceptions=*/0,
14322                                              /*NoexceptExpr=*/nullptr,
14323                                              /*ExceptionSpecTokens=*/nullptr,
14324                                              /*DeclsInPrototype=*/None, Loc,
14325                                              Loc, D),
14326                 std::move(DS.getAttributes()), SourceLocation());
14327   D.SetIdentifier(&II, Loc);
14328 
14329   // Insert this function into the enclosing block scope.
14330   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14331   FD->setImplicit();
14332 
14333   AddKnownFunctionAttributes(FD);
14334 
14335   return FD;
14336 }
14337 
14338 /// Adds any function attributes that we know a priori based on
14339 /// the declaration of this function.
14340 ///
14341 /// These attributes can apply both to implicitly-declared builtins
14342 /// (like __builtin___printf_chk) or to library-declared functions
14343 /// like NSLog or printf.
14344 ///
14345 /// We need to check for duplicate attributes both here and where user-written
14346 /// attributes are applied to declarations.
14347 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14348   if (FD->isInvalidDecl())
14349     return;
14350 
14351   // If this is a built-in function, map its builtin attributes to
14352   // actual attributes.
14353   if (unsigned BuiltinID = FD->getBuiltinID()) {
14354     // Handle printf-formatting attributes.
14355     unsigned FormatIdx;
14356     bool HasVAListArg;
14357     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14358       if (!FD->hasAttr<FormatAttr>()) {
14359         const char *fmt = "printf";
14360         unsigned int NumParams = FD->getNumParams();
14361         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14362             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14363           fmt = "NSString";
14364         FD->addAttr(FormatAttr::CreateImplicit(Context,
14365                                                &Context.Idents.get(fmt),
14366                                                FormatIdx+1,
14367                                                HasVAListArg ? 0 : FormatIdx+2,
14368                                                FD->getLocation()));
14369       }
14370     }
14371     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14372                                              HasVAListArg)) {
14373      if (!FD->hasAttr<FormatAttr>())
14374        FD->addAttr(FormatAttr::CreateImplicit(Context,
14375                                               &Context.Idents.get("scanf"),
14376                                               FormatIdx+1,
14377                                               HasVAListArg ? 0 : FormatIdx+2,
14378                                               FD->getLocation()));
14379     }
14380 
14381     // Handle automatically recognized callbacks.
14382     SmallVector<int, 4> Encoding;
14383     if (!FD->hasAttr<CallbackAttr>() &&
14384         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14385       FD->addAttr(CallbackAttr::CreateImplicit(
14386           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14387 
14388     // Mark const if we don't care about errno and that is the only thing
14389     // preventing the function from being const. This allows IRgen to use LLVM
14390     // intrinsics for such functions.
14391     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14392         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14393       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14394 
14395     // We make "fma" on some platforms const because we know it does not set
14396     // errno in those environments even though it could set errno based on the
14397     // C standard.
14398     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14399     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14400         !FD->hasAttr<ConstAttr>()) {
14401       switch (BuiltinID) {
14402       case Builtin::BI__builtin_fma:
14403       case Builtin::BI__builtin_fmaf:
14404       case Builtin::BI__builtin_fmal:
14405       case Builtin::BIfma:
14406       case Builtin::BIfmaf:
14407       case Builtin::BIfmal:
14408         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14409         break;
14410       default:
14411         break;
14412       }
14413     }
14414 
14415     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14416         !FD->hasAttr<ReturnsTwiceAttr>())
14417       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14418                                          FD->getLocation()));
14419     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14420       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14421     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14422       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14423     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14424       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14425     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14426         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14427       // Add the appropriate attribute, depending on the CUDA compilation mode
14428       // and which target the builtin belongs to. For example, during host
14429       // compilation, aux builtins are __device__, while the rest are __host__.
14430       if (getLangOpts().CUDAIsDevice !=
14431           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14432         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14433       else
14434         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14435     }
14436   }
14437 
14438   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14439   // throw, add an implicit nothrow attribute to any extern "C" function we come
14440   // across.
14441   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14442       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14443     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14444     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14445       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14446   }
14447 
14448   IdentifierInfo *Name = FD->getIdentifier();
14449   if (!Name)
14450     return;
14451   if ((!getLangOpts().CPlusPlus &&
14452        FD->getDeclContext()->isTranslationUnit()) ||
14453       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14454        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14455        LinkageSpecDecl::lang_c)) {
14456     // Okay: this could be a libc/libm/Objective-C function we know
14457     // about.
14458   } else
14459     return;
14460 
14461   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14462     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14463     // target-specific builtins, perhaps?
14464     if (!FD->hasAttr<FormatAttr>())
14465       FD->addAttr(FormatAttr::CreateImplicit(Context,
14466                                              &Context.Idents.get("printf"), 2,
14467                                              Name->isStr("vasprintf") ? 0 : 3,
14468                                              FD->getLocation()));
14469   }
14470 
14471   if (Name->isStr("__CFStringMakeConstantString")) {
14472     // We already have a __builtin___CFStringMakeConstantString,
14473     // but builds that use -fno-constant-cfstrings don't go through that.
14474     if (!FD->hasAttr<FormatArgAttr>())
14475       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14476                                                 FD->getLocation()));
14477   }
14478 }
14479 
14480 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14481                                     TypeSourceInfo *TInfo) {
14482   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14483   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14484 
14485   if (!TInfo) {
14486     assert(D.isInvalidType() && "no declarator info for valid type");
14487     TInfo = Context.getTrivialTypeSourceInfo(T);
14488   }
14489 
14490   // Scope manipulation handled by caller.
14491   TypedefDecl *NewTD =
14492       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14493                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14494 
14495   // Bail out immediately if we have an invalid declaration.
14496   if (D.isInvalidType()) {
14497     NewTD->setInvalidDecl();
14498     return NewTD;
14499   }
14500 
14501   if (D.getDeclSpec().isModulePrivateSpecified()) {
14502     if (CurContext->isFunctionOrMethod())
14503       Diag(NewTD->getLocation(), diag::err_module_private_local)
14504         << 2 << NewTD->getDeclName()
14505         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14506         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14507     else
14508       NewTD->setModulePrivate();
14509   }
14510 
14511   // C++ [dcl.typedef]p8:
14512   //   If the typedef declaration defines an unnamed class (or
14513   //   enum), the first typedef-name declared by the declaration
14514   //   to be that class type (or enum type) is used to denote the
14515   //   class type (or enum type) for linkage purposes only.
14516   // We need to check whether the type was declared in the declaration.
14517   switch (D.getDeclSpec().getTypeSpecType()) {
14518   case TST_enum:
14519   case TST_struct:
14520   case TST_interface:
14521   case TST_union:
14522   case TST_class: {
14523     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14524     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14525     break;
14526   }
14527 
14528   default:
14529     break;
14530   }
14531 
14532   return NewTD;
14533 }
14534 
14535 /// Check that this is a valid underlying type for an enum declaration.
14536 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14537   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14538   QualType T = TI->getType();
14539 
14540   if (T->isDependentType())
14541     return false;
14542 
14543   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14544     if (BT->isInteger())
14545       return false;
14546 
14547   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14548   return true;
14549 }
14550 
14551 /// Check whether this is a valid redeclaration of a previous enumeration.
14552 /// \return true if the redeclaration was invalid.
14553 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14554                                   QualType EnumUnderlyingTy, bool IsFixed,
14555                                   const EnumDecl *Prev) {
14556   if (IsScoped != Prev->isScoped()) {
14557     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14558       << Prev->isScoped();
14559     Diag(Prev->getLocation(), diag::note_previous_declaration);
14560     return true;
14561   }
14562 
14563   if (IsFixed && Prev->isFixed()) {
14564     if (!EnumUnderlyingTy->isDependentType() &&
14565         !Prev->getIntegerType()->isDependentType() &&
14566         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14567                                         Prev->getIntegerType())) {
14568       // TODO: Highlight the underlying type of the redeclaration.
14569       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14570         << EnumUnderlyingTy << Prev->getIntegerType();
14571       Diag(Prev->getLocation(), diag::note_previous_declaration)
14572           << Prev->getIntegerTypeRange();
14573       return true;
14574     }
14575   } else if (IsFixed != Prev->isFixed()) {
14576     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14577       << Prev->isFixed();
14578     Diag(Prev->getLocation(), diag::note_previous_declaration);
14579     return true;
14580   }
14581 
14582   return false;
14583 }
14584 
14585 /// Get diagnostic %select index for tag kind for
14586 /// redeclaration diagnostic message.
14587 /// WARNING: Indexes apply to particular diagnostics only!
14588 ///
14589 /// \returns diagnostic %select index.
14590 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14591   switch (Tag) {
14592   case TTK_Struct: return 0;
14593   case TTK_Interface: return 1;
14594   case TTK_Class:  return 2;
14595   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14596   }
14597 }
14598 
14599 /// Determine if tag kind is a class-key compatible with
14600 /// class for redeclaration (class, struct, or __interface).
14601 ///
14602 /// \returns true iff the tag kind is compatible.
14603 static bool isClassCompatTagKind(TagTypeKind Tag)
14604 {
14605   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14606 }
14607 
14608 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14609                                              TagTypeKind TTK) {
14610   if (isa<TypedefDecl>(PrevDecl))
14611     return NTK_Typedef;
14612   else if (isa<TypeAliasDecl>(PrevDecl))
14613     return NTK_TypeAlias;
14614   else if (isa<ClassTemplateDecl>(PrevDecl))
14615     return NTK_Template;
14616   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14617     return NTK_TypeAliasTemplate;
14618   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14619     return NTK_TemplateTemplateArgument;
14620   switch (TTK) {
14621   case TTK_Struct:
14622   case TTK_Interface:
14623   case TTK_Class:
14624     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14625   case TTK_Union:
14626     return NTK_NonUnion;
14627   case TTK_Enum:
14628     return NTK_NonEnum;
14629   }
14630   llvm_unreachable("invalid TTK");
14631 }
14632 
14633 /// Determine whether a tag with a given kind is acceptable
14634 /// as a redeclaration of the given tag declaration.
14635 ///
14636 /// \returns true if the new tag kind is acceptable, false otherwise.
14637 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14638                                         TagTypeKind NewTag, bool isDefinition,
14639                                         SourceLocation NewTagLoc,
14640                                         const IdentifierInfo *Name) {
14641   // C++ [dcl.type.elab]p3:
14642   //   The class-key or enum keyword present in the
14643   //   elaborated-type-specifier shall agree in kind with the
14644   //   declaration to which the name in the elaborated-type-specifier
14645   //   refers. This rule also applies to the form of
14646   //   elaborated-type-specifier that declares a class-name or
14647   //   friend class since it can be construed as referring to the
14648   //   definition of the class. Thus, in any
14649   //   elaborated-type-specifier, the enum keyword shall be used to
14650   //   refer to an enumeration (7.2), the union class-key shall be
14651   //   used to refer to a union (clause 9), and either the class or
14652   //   struct class-key shall be used to refer to a class (clause 9)
14653   //   declared using the class or struct class-key.
14654   TagTypeKind OldTag = Previous->getTagKind();
14655   if (OldTag != NewTag &&
14656       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14657     return false;
14658 
14659   // Tags are compatible, but we might still want to warn on mismatched tags.
14660   // Non-class tags can't be mismatched at this point.
14661   if (!isClassCompatTagKind(NewTag))
14662     return true;
14663 
14664   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14665   // by our warning analysis. We don't want to warn about mismatches with (eg)
14666   // declarations in system headers that are designed to be specialized, but if
14667   // a user asks us to warn, we should warn if their code contains mismatched
14668   // declarations.
14669   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14670     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14671                                       Loc);
14672   };
14673   if (IsIgnoredLoc(NewTagLoc))
14674     return true;
14675 
14676   auto IsIgnored = [&](const TagDecl *Tag) {
14677     return IsIgnoredLoc(Tag->getLocation());
14678   };
14679   while (IsIgnored(Previous)) {
14680     Previous = Previous->getPreviousDecl();
14681     if (!Previous)
14682       return true;
14683     OldTag = Previous->getTagKind();
14684   }
14685 
14686   bool isTemplate = false;
14687   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14688     isTemplate = Record->getDescribedClassTemplate();
14689 
14690   if (inTemplateInstantiation()) {
14691     if (OldTag != NewTag) {
14692       // In a template instantiation, do not offer fix-its for tag mismatches
14693       // since they usually mess up the template instead of fixing the problem.
14694       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14695         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14696         << getRedeclDiagFromTagKind(OldTag);
14697       // FIXME: Note previous location?
14698     }
14699     return true;
14700   }
14701 
14702   if (isDefinition) {
14703     // On definitions, check all previous tags and issue a fix-it for each
14704     // one that doesn't match the current tag.
14705     if (Previous->getDefinition()) {
14706       // Don't suggest fix-its for redefinitions.
14707       return true;
14708     }
14709 
14710     bool previousMismatch = false;
14711     for (const TagDecl *I : Previous->redecls()) {
14712       if (I->getTagKind() != NewTag) {
14713         // Ignore previous declarations for which the warning was disabled.
14714         if (IsIgnored(I))
14715           continue;
14716 
14717         if (!previousMismatch) {
14718           previousMismatch = true;
14719           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14720             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14721             << getRedeclDiagFromTagKind(I->getTagKind());
14722         }
14723         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14724           << getRedeclDiagFromTagKind(NewTag)
14725           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14726                TypeWithKeyword::getTagTypeKindName(NewTag));
14727       }
14728     }
14729     return true;
14730   }
14731 
14732   // Identify the prevailing tag kind: this is the kind of the definition (if
14733   // there is a non-ignored definition), or otherwise the kind of the prior
14734   // (non-ignored) declaration.
14735   const TagDecl *PrevDef = Previous->getDefinition();
14736   if (PrevDef && IsIgnored(PrevDef))
14737     PrevDef = nullptr;
14738   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14739   if (Redecl->getTagKind() != NewTag) {
14740     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14741       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14742       << getRedeclDiagFromTagKind(OldTag);
14743     Diag(Redecl->getLocation(), diag::note_previous_use);
14744 
14745     // If there is a previous definition, suggest a fix-it.
14746     if (PrevDef) {
14747       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14748         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14749         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14750              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14751     }
14752   }
14753 
14754   return true;
14755 }
14756 
14757 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14758 /// from an outer enclosing namespace or file scope inside a friend declaration.
14759 /// This should provide the commented out code in the following snippet:
14760 ///   namespace N {
14761 ///     struct X;
14762 ///     namespace M {
14763 ///       struct Y { friend struct /*N::*/ X; };
14764 ///     }
14765 ///   }
14766 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14767                                          SourceLocation NameLoc) {
14768   // While the decl is in a namespace, do repeated lookup of that name and see
14769   // if we get the same namespace back.  If we do not, continue until
14770   // translation unit scope, at which point we have a fully qualified NNS.
14771   SmallVector<IdentifierInfo *, 4> Namespaces;
14772   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14773   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14774     // This tag should be declared in a namespace, which can only be enclosed by
14775     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14776     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14777     if (!Namespace || Namespace->isAnonymousNamespace())
14778       return FixItHint();
14779     IdentifierInfo *II = Namespace->getIdentifier();
14780     Namespaces.push_back(II);
14781     NamedDecl *Lookup = SemaRef.LookupSingleName(
14782         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14783     if (Lookup == Namespace)
14784       break;
14785   }
14786 
14787   // Once we have all the namespaces, reverse them to go outermost first, and
14788   // build an NNS.
14789   SmallString<64> Insertion;
14790   llvm::raw_svector_ostream OS(Insertion);
14791   if (DC->isTranslationUnit())
14792     OS << "::";
14793   std::reverse(Namespaces.begin(), Namespaces.end());
14794   for (auto *II : Namespaces)
14795     OS << II->getName() << "::";
14796   return FixItHint::CreateInsertion(NameLoc, Insertion);
14797 }
14798 
14799 /// Determine whether a tag originally declared in context \p OldDC can
14800 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14801 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14802 /// using-declaration).
14803 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14804                                          DeclContext *NewDC) {
14805   OldDC = OldDC->getRedeclContext();
14806   NewDC = NewDC->getRedeclContext();
14807 
14808   if (OldDC->Equals(NewDC))
14809     return true;
14810 
14811   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14812   // encloses the other).
14813   if (S.getLangOpts().MSVCCompat &&
14814       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14815     return true;
14816 
14817   return false;
14818 }
14819 
14820 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14821 /// former case, Name will be non-null.  In the later case, Name will be null.
14822 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14823 /// reference/declaration/definition of a tag.
14824 ///
14825 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14826 /// trailing-type-specifier) other than one in an alias-declaration.
14827 ///
14828 /// \param SkipBody If non-null, will be set to indicate if the caller should
14829 /// skip the definition of this tag and treat it as if it were a declaration.
14830 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14831                      SourceLocation KWLoc, CXXScopeSpec &SS,
14832                      IdentifierInfo *Name, SourceLocation NameLoc,
14833                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14834                      SourceLocation ModulePrivateLoc,
14835                      MultiTemplateParamsArg TemplateParameterLists,
14836                      bool &OwnedDecl, bool &IsDependent,
14837                      SourceLocation ScopedEnumKWLoc,
14838                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14839                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14840                      SkipBodyInfo *SkipBody) {
14841   // If this is not a definition, it must have a name.
14842   IdentifierInfo *OrigName = Name;
14843   assert((Name != nullptr || TUK == TUK_Definition) &&
14844          "Nameless record must be a definition!");
14845   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14846 
14847   OwnedDecl = false;
14848   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14849   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14850 
14851   // FIXME: Check member specializations more carefully.
14852   bool isMemberSpecialization = false;
14853   bool Invalid = false;
14854 
14855   // We only need to do this matching if we have template parameters
14856   // or a scope specifier, which also conveniently avoids this work
14857   // for non-C++ cases.
14858   if (TemplateParameterLists.size() > 0 ||
14859       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14860     if (TemplateParameterList *TemplateParams =
14861             MatchTemplateParametersToScopeSpecifier(
14862                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14863                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14864       if (Kind == TTK_Enum) {
14865         Diag(KWLoc, diag::err_enum_template);
14866         return nullptr;
14867       }
14868 
14869       if (TemplateParams->size() > 0) {
14870         // This is a declaration or definition of a class template (which may
14871         // be a member of another template).
14872 
14873         if (Invalid)
14874           return nullptr;
14875 
14876         OwnedDecl = false;
14877         DeclResult Result = CheckClassTemplate(
14878             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14879             AS, ModulePrivateLoc,
14880             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14881             TemplateParameterLists.data(), SkipBody);
14882         return Result.get();
14883       } else {
14884         // The "template<>" header is extraneous.
14885         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14886           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14887         isMemberSpecialization = true;
14888       }
14889     }
14890   }
14891 
14892   // Figure out the underlying type if this a enum declaration. We need to do
14893   // this early, because it's needed to detect if this is an incompatible
14894   // redeclaration.
14895   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14896   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14897 
14898   if (Kind == TTK_Enum) {
14899     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14900       // No underlying type explicitly specified, or we failed to parse the
14901       // type, default to int.
14902       EnumUnderlying = Context.IntTy.getTypePtr();
14903     } else if (UnderlyingType.get()) {
14904       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14905       // integral type; any cv-qualification is ignored.
14906       TypeSourceInfo *TI = nullptr;
14907       GetTypeFromParser(UnderlyingType.get(), &TI);
14908       EnumUnderlying = TI;
14909 
14910       if (CheckEnumUnderlyingType(TI))
14911         // Recover by falling back to int.
14912         EnumUnderlying = Context.IntTy.getTypePtr();
14913 
14914       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14915                                           UPPC_FixedUnderlyingType))
14916         EnumUnderlying = Context.IntTy.getTypePtr();
14917 
14918     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14919       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14920       // of 'int'. However, if this is an unfixed forward declaration, don't set
14921       // the underlying type unless the user enables -fms-compatibility. This
14922       // makes unfixed forward declared enums incomplete and is more conforming.
14923       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14924         EnumUnderlying = Context.IntTy.getTypePtr();
14925     }
14926   }
14927 
14928   DeclContext *SearchDC = CurContext;
14929   DeclContext *DC = CurContext;
14930   bool isStdBadAlloc = false;
14931   bool isStdAlignValT = false;
14932 
14933   RedeclarationKind Redecl = forRedeclarationInCurContext();
14934   if (TUK == TUK_Friend || TUK == TUK_Reference)
14935     Redecl = NotForRedeclaration;
14936 
14937   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14938   /// implemented asks for structural equivalence checking, the returned decl
14939   /// here is passed back to the parser, allowing the tag body to be parsed.
14940   auto createTagFromNewDecl = [&]() -> TagDecl * {
14941     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14942     // If there is an identifier, use the location of the identifier as the
14943     // location of the decl, otherwise use the location of the struct/union
14944     // keyword.
14945     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14946     TagDecl *New = nullptr;
14947 
14948     if (Kind == TTK_Enum) {
14949       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14950                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14951       // If this is an undefined enum, bail.
14952       if (TUK != TUK_Definition && !Invalid)
14953         return nullptr;
14954       if (EnumUnderlying) {
14955         EnumDecl *ED = cast<EnumDecl>(New);
14956         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14957           ED->setIntegerTypeSourceInfo(TI);
14958         else
14959           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14960         ED->setPromotionType(ED->getIntegerType());
14961       }
14962     } else { // struct/union
14963       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14964                                nullptr);
14965     }
14966 
14967     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14968       // Add alignment attributes if necessary; these attributes are checked
14969       // when the ASTContext lays out the structure.
14970       //
14971       // It is important for implementing the correct semantics that this
14972       // happen here (in ActOnTag). The #pragma pack stack is
14973       // maintained as a result of parser callbacks which can occur at
14974       // many points during the parsing of a struct declaration (because
14975       // the #pragma tokens are effectively skipped over during the
14976       // parsing of the struct).
14977       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14978         AddAlignmentAttributesForRecord(RD);
14979         AddMsStructLayoutForRecord(RD);
14980       }
14981     }
14982     New->setLexicalDeclContext(CurContext);
14983     return New;
14984   };
14985 
14986   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14987   if (Name && SS.isNotEmpty()) {
14988     // We have a nested-name tag ('struct foo::bar').
14989 
14990     // Check for invalid 'foo::'.
14991     if (SS.isInvalid()) {
14992       Name = nullptr;
14993       goto CreateNewDecl;
14994     }
14995 
14996     // If this is a friend or a reference to a class in a dependent
14997     // context, don't try to make a decl for it.
14998     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14999       DC = computeDeclContext(SS, false);
15000       if (!DC) {
15001         IsDependent = true;
15002         return nullptr;
15003       }
15004     } else {
15005       DC = computeDeclContext(SS, true);
15006       if (!DC) {
15007         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15008           << SS.getRange();
15009         return nullptr;
15010       }
15011     }
15012 
15013     if (RequireCompleteDeclContext(SS, DC))
15014       return nullptr;
15015 
15016     SearchDC = DC;
15017     // Look-up name inside 'foo::'.
15018     LookupQualifiedName(Previous, DC);
15019 
15020     if (Previous.isAmbiguous())
15021       return nullptr;
15022 
15023     if (Previous.empty()) {
15024       // Name lookup did not find anything. However, if the
15025       // nested-name-specifier refers to the current instantiation,
15026       // and that current instantiation has any dependent base
15027       // classes, we might find something at instantiation time: treat
15028       // this as a dependent elaborated-type-specifier.
15029       // But this only makes any sense for reference-like lookups.
15030       if (Previous.wasNotFoundInCurrentInstantiation() &&
15031           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15032         IsDependent = true;
15033         return nullptr;
15034       }
15035 
15036       // A tag 'foo::bar' must already exist.
15037       Diag(NameLoc, diag::err_not_tag_in_scope)
15038         << Kind << Name << DC << SS.getRange();
15039       Name = nullptr;
15040       Invalid = true;
15041       goto CreateNewDecl;
15042     }
15043   } else if (Name) {
15044     // C++14 [class.mem]p14:
15045     //   If T is the name of a class, then each of the following shall have a
15046     //   name different from T:
15047     //    -- every member of class T that is itself a type
15048     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15049         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15050       return nullptr;
15051 
15052     // If this is a named struct, check to see if there was a previous forward
15053     // declaration or definition.
15054     // FIXME: We're looking into outer scopes here, even when we
15055     // shouldn't be. Doing so can result in ambiguities that we
15056     // shouldn't be diagnosing.
15057     LookupName(Previous, S);
15058 
15059     // When declaring or defining a tag, ignore ambiguities introduced
15060     // by types using'ed into this scope.
15061     if (Previous.isAmbiguous() &&
15062         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15063       LookupResult::Filter F = Previous.makeFilter();
15064       while (F.hasNext()) {
15065         NamedDecl *ND = F.next();
15066         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15067                 SearchDC->getRedeclContext()))
15068           F.erase();
15069       }
15070       F.done();
15071     }
15072 
15073     // C++11 [namespace.memdef]p3:
15074     //   If the name in a friend declaration is neither qualified nor
15075     //   a template-id and the declaration is a function or an
15076     //   elaborated-type-specifier, the lookup to determine whether
15077     //   the entity has been previously declared shall not consider
15078     //   any scopes outside the innermost enclosing namespace.
15079     //
15080     // MSVC doesn't implement the above rule for types, so a friend tag
15081     // declaration may be a redeclaration of a type declared in an enclosing
15082     // scope.  They do implement this rule for friend functions.
15083     //
15084     // Does it matter that this should be by scope instead of by
15085     // semantic context?
15086     if (!Previous.empty() && TUK == TUK_Friend) {
15087       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15088       LookupResult::Filter F = Previous.makeFilter();
15089       bool FriendSawTagOutsideEnclosingNamespace = false;
15090       while (F.hasNext()) {
15091         NamedDecl *ND = F.next();
15092         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15093         if (DC->isFileContext() &&
15094             !EnclosingNS->Encloses(ND->getDeclContext())) {
15095           if (getLangOpts().MSVCCompat)
15096             FriendSawTagOutsideEnclosingNamespace = true;
15097           else
15098             F.erase();
15099         }
15100       }
15101       F.done();
15102 
15103       // Diagnose this MSVC extension in the easy case where lookup would have
15104       // unambiguously found something outside the enclosing namespace.
15105       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15106         NamedDecl *ND = Previous.getFoundDecl();
15107         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15108             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15109       }
15110     }
15111 
15112     // Note:  there used to be some attempt at recovery here.
15113     if (Previous.isAmbiguous())
15114       return nullptr;
15115 
15116     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15117       // FIXME: This makes sure that we ignore the contexts associated
15118       // with C structs, unions, and enums when looking for a matching
15119       // tag declaration or definition. See the similar lookup tweak
15120       // in Sema::LookupName; is there a better way to deal with this?
15121       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15122         SearchDC = SearchDC->getParent();
15123     }
15124   }
15125 
15126   if (Previous.isSingleResult() &&
15127       Previous.getFoundDecl()->isTemplateParameter()) {
15128     // Maybe we will complain about the shadowed template parameter.
15129     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15130     // Just pretend that we didn't see the previous declaration.
15131     Previous.clear();
15132   }
15133 
15134   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15135       DC->Equals(getStdNamespace())) {
15136     if (Name->isStr("bad_alloc")) {
15137       // This is a declaration of or a reference to "std::bad_alloc".
15138       isStdBadAlloc = true;
15139 
15140       // If std::bad_alloc has been implicitly declared (but made invisible to
15141       // name lookup), fill in this implicit declaration as the previous
15142       // declaration, so that the declarations get chained appropriately.
15143       if (Previous.empty() && StdBadAlloc)
15144         Previous.addDecl(getStdBadAlloc());
15145     } else if (Name->isStr("align_val_t")) {
15146       isStdAlignValT = true;
15147       if (Previous.empty() && StdAlignValT)
15148         Previous.addDecl(getStdAlignValT());
15149     }
15150   }
15151 
15152   // If we didn't find a previous declaration, and this is a reference
15153   // (or friend reference), move to the correct scope.  In C++, we
15154   // also need to do a redeclaration lookup there, just in case
15155   // there's a shadow friend decl.
15156   if (Name && Previous.empty() &&
15157       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15158     if (Invalid) goto CreateNewDecl;
15159     assert(SS.isEmpty());
15160 
15161     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15162       // C++ [basic.scope.pdecl]p5:
15163       //   -- for an elaborated-type-specifier of the form
15164       //
15165       //          class-key identifier
15166       //
15167       //      if the elaborated-type-specifier is used in the
15168       //      decl-specifier-seq or parameter-declaration-clause of a
15169       //      function defined in namespace scope, the identifier is
15170       //      declared as a class-name in the namespace that contains
15171       //      the declaration; otherwise, except as a friend
15172       //      declaration, the identifier is declared in the smallest
15173       //      non-class, non-function-prototype scope that contains the
15174       //      declaration.
15175       //
15176       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15177       // C structs and unions.
15178       //
15179       // It is an error in C++ to declare (rather than define) an enum
15180       // type, including via an elaborated type specifier.  We'll
15181       // diagnose that later; for now, declare the enum in the same
15182       // scope as we would have picked for any other tag type.
15183       //
15184       // GNU C also supports this behavior as part of its incomplete
15185       // enum types extension, while GNU C++ does not.
15186       //
15187       // Find the context where we'll be declaring the tag.
15188       // FIXME: We would like to maintain the current DeclContext as the
15189       // lexical context,
15190       SearchDC = getTagInjectionContext(SearchDC);
15191 
15192       // Find the scope where we'll be declaring the tag.
15193       S = getTagInjectionScope(S, getLangOpts());
15194     } else {
15195       assert(TUK == TUK_Friend);
15196       // C++ [namespace.memdef]p3:
15197       //   If a friend declaration in a non-local class first declares a
15198       //   class or function, the friend class or function is a member of
15199       //   the innermost enclosing namespace.
15200       SearchDC = SearchDC->getEnclosingNamespaceContext();
15201     }
15202 
15203     // In C++, we need to do a redeclaration lookup to properly
15204     // diagnose some problems.
15205     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15206     // hidden declaration so that we don't get ambiguity errors when using a
15207     // type declared by an elaborated-type-specifier.  In C that is not correct
15208     // and we should instead merge compatible types found by lookup.
15209     if (getLangOpts().CPlusPlus) {
15210       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15211       LookupQualifiedName(Previous, SearchDC);
15212     } else {
15213       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15214       LookupName(Previous, S);
15215     }
15216   }
15217 
15218   // If we have a known previous declaration to use, then use it.
15219   if (Previous.empty() && SkipBody && SkipBody->Previous)
15220     Previous.addDecl(SkipBody->Previous);
15221 
15222   if (!Previous.empty()) {
15223     NamedDecl *PrevDecl = Previous.getFoundDecl();
15224     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15225 
15226     // It's okay to have a tag decl in the same scope as a typedef
15227     // which hides a tag decl in the same scope.  Finding this
15228     // insanity with a redeclaration lookup can only actually happen
15229     // in C++.
15230     //
15231     // This is also okay for elaborated-type-specifiers, which is
15232     // technically forbidden by the current standard but which is
15233     // okay according to the likely resolution of an open issue;
15234     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15235     if (getLangOpts().CPlusPlus) {
15236       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15237         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15238           TagDecl *Tag = TT->getDecl();
15239           if (Tag->getDeclName() == Name &&
15240               Tag->getDeclContext()->getRedeclContext()
15241                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15242             PrevDecl = Tag;
15243             Previous.clear();
15244             Previous.addDecl(Tag);
15245             Previous.resolveKind();
15246           }
15247         }
15248       }
15249     }
15250 
15251     // If this is a redeclaration of a using shadow declaration, it must
15252     // declare a tag in the same context. In MSVC mode, we allow a
15253     // redefinition if either context is within the other.
15254     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15255       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15256       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15257           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15258           !(OldTag && isAcceptableTagRedeclContext(
15259                           *this, OldTag->getDeclContext(), SearchDC))) {
15260         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15261         Diag(Shadow->getTargetDecl()->getLocation(),
15262              diag::note_using_decl_target);
15263         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15264             << 0;
15265         // Recover by ignoring the old declaration.
15266         Previous.clear();
15267         goto CreateNewDecl;
15268       }
15269     }
15270 
15271     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15272       // If this is a use of a previous tag, or if the tag is already declared
15273       // in the same scope (so that the definition/declaration completes or
15274       // rementions the tag), reuse the decl.
15275       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15276           isDeclInScope(DirectPrevDecl, SearchDC, S,
15277                         SS.isNotEmpty() || isMemberSpecialization)) {
15278         // Make sure that this wasn't declared as an enum and now used as a
15279         // struct or something similar.
15280         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15281                                           TUK == TUK_Definition, KWLoc,
15282                                           Name)) {
15283           bool SafeToContinue
15284             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15285                Kind != TTK_Enum);
15286           if (SafeToContinue)
15287             Diag(KWLoc, diag::err_use_with_wrong_tag)
15288               << Name
15289               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15290                                               PrevTagDecl->getKindName());
15291           else
15292             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15293           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15294 
15295           if (SafeToContinue)
15296             Kind = PrevTagDecl->getTagKind();
15297           else {
15298             // Recover by making this an anonymous redefinition.
15299             Name = nullptr;
15300             Previous.clear();
15301             Invalid = true;
15302           }
15303         }
15304 
15305         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15306           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15307 
15308           // If this is an elaborated-type-specifier for a scoped enumeration,
15309           // the 'class' keyword is not necessary and not permitted.
15310           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15311             if (ScopedEnum)
15312               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15313                 << PrevEnum->isScoped()
15314                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15315             return PrevTagDecl;
15316           }
15317 
15318           QualType EnumUnderlyingTy;
15319           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15320             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15321           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15322             EnumUnderlyingTy = QualType(T, 0);
15323 
15324           // All conflicts with previous declarations are recovered by
15325           // returning the previous declaration, unless this is a definition,
15326           // in which case we want the caller to bail out.
15327           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15328                                      ScopedEnum, EnumUnderlyingTy,
15329                                      IsFixed, PrevEnum))
15330             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15331         }
15332 
15333         // C++11 [class.mem]p1:
15334         //   A member shall not be declared twice in the member-specification,
15335         //   except that a nested class or member class template can be declared
15336         //   and then later defined.
15337         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15338             S->isDeclScope(PrevDecl)) {
15339           Diag(NameLoc, diag::ext_member_redeclared);
15340           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15341         }
15342 
15343         if (!Invalid) {
15344           // If this is a use, just return the declaration we found, unless
15345           // we have attributes.
15346           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15347             if (!Attrs.empty()) {
15348               // FIXME: Diagnose these attributes. For now, we create a new
15349               // declaration to hold them.
15350             } else if (TUK == TUK_Reference &&
15351                        (PrevTagDecl->getFriendObjectKind() ==
15352                             Decl::FOK_Undeclared ||
15353                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15354                        SS.isEmpty()) {
15355               // This declaration is a reference to an existing entity, but
15356               // has different visibility from that entity: it either makes
15357               // a friend visible or it makes a type visible in a new module.
15358               // In either case, create a new declaration. We only do this if
15359               // the declaration would have meant the same thing if no prior
15360               // declaration were found, that is, if it was found in the same
15361               // scope where we would have injected a declaration.
15362               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15363                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15364                 return PrevTagDecl;
15365               // This is in the injected scope, create a new declaration in
15366               // that scope.
15367               S = getTagInjectionScope(S, getLangOpts());
15368             } else {
15369               return PrevTagDecl;
15370             }
15371           }
15372 
15373           // Diagnose attempts to redefine a tag.
15374           if (TUK == TUK_Definition) {
15375             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15376               // If we're defining a specialization and the previous definition
15377               // is from an implicit instantiation, don't emit an error
15378               // here; we'll catch this in the general case below.
15379               bool IsExplicitSpecializationAfterInstantiation = false;
15380               if (isMemberSpecialization) {
15381                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15382                   IsExplicitSpecializationAfterInstantiation =
15383                     RD->getTemplateSpecializationKind() !=
15384                     TSK_ExplicitSpecialization;
15385                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15386                   IsExplicitSpecializationAfterInstantiation =
15387                     ED->getTemplateSpecializationKind() !=
15388                     TSK_ExplicitSpecialization;
15389               }
15390 
15391               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15392               // not keep more that one definition around (merge them). However,
15393               // ensure the decl passes the structural compatibility check in
15394               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15395               NamedDecl *Hidden = nullptr;
15396               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15397                 // There is a definition of this tag, but it is not visible. We
15398                 // explicitly make use of C++'s one definition rule here, and
15399                 // assume that this definition is identical to the hidden one
15400                 // we already have. Make the existing definition visible and
15401                 // use it in place of this one.
15402                 if (!getLangOpts().CPlusPlus) {
15403                   // Postpone making the old definition visible until after we
15404                   // complete parsing the new one and do the structural
15405                   // comparison.
15406                   SkipBody->CheckSameAsPrevious = true;
15407                   SkipBody->New = createTagFromNewDecl();
15408                   SkipBody->Previous = Def;
15409                   return Def;
15410                 } else {
15411                   SkipBody->ShouldSkip = true;
15412                   SkipBody->Previous = Def;
15413                   makeMergedDefinitionVisible(Hidden);
15414                   // Carry on and handle it like a normal definition. We'll
15415                   // skip starting the definitiion later.
15416                 }
15417               } else if (!IsExplicitSpecializationAfterInstantiation) {
15418                 // A redeclaration in function prototype scope in C isn't
15419                 // visible elsewhere, so merely issue a warning.
15420                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15421                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15422                 else
15423                   Diag(NameLoc, diag::err_redefinition) << Name;
15424                 notePreviousDefinition(Def,
15425                                        NameLoc.isValid() ? NameLoc : KWLoc);
15426                 // If this is a redefinition, recover by making this
15427                 // struct be anonymous, which will make any later
15428                 // references get the previous definition.
15429                 Name = nullptr;
15430                 Previous.clear();
15431                 Invalid = true;
15432               }
15433             } else {
15434               // If the type is currently being defined, complain
15435               // about a nested redefinition.
15436               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15437               if (TD->isBeingDefined()) {
15438                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15439                 Diag(PrevTagDecl->getLocation(),
15440                      diag::note_previous_definition);
15441                 Name = nullptr;
15442                 Previous.clear();
15443                 Invalid = true;
15444               }
15445             }
15446 
15447             // Okay, this is definition of a previously declared or referenced
15448             // tag. We're going to create a new Decl for it.
15449           }
15450 
15451           // Okay, we're going to make a redeclaration.  If this is some kind
15452           // of reference, make sure we build the redeclaration in the same DC
15453           // as the original, and ignore the current access specifier.
15454           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15455             SearchDC = PrevTagDecl->getDeclContext();
15456             AS = AS_none;
15457           }
15458         }
15459         // If we get here we have (another) forward declaration or we
15460         // have a definition.  Just create a new decl.
15461 
15462       } else {
15463         // If we get here, this is a definition of a new tag type in a nested
15464         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15465         // new decl/type.  We set PrevDecl to NULL so that the entities
15466         // have distinct types.
15467         Previous.clear();
15468       }
15469       // If we get here, we're going to create a new Decl. If PrevDecl
15470       // is non-NULL, it's a definition of the tag declared by
15471       // PrevDecl. If it's NULL, we have a new definition.
15472 
15473     // Otherwise, PrevDecl is not a tag, but was found with tag
15474     // lookup.  This is only actually possible in C++, where a few
15475     // things like templates still live in the tag namespace.
15476     } else {
15477       // Use a better diagnostic if an elaborated-type-specifier
15478       // found the wrong kind of type on the first
15479       // (non-redeclaration) lookup.
15480       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15481           !Previous.isForRedeclaration()) {
15482         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15483         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15484                                                        << Kind;
15485         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15486         Invalid = true;
15487 
15488       // Otherwise, only diagnose if the declaration is in scope.
15489       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15490                                 SS.isNotEmpty() || isMemberSpecialization)) {
15491         // do nothing
15492 
15493       // Diagnose implicit declarations introduced by elaborated types.
15494       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15495         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15496         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15497         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15498         Invalid = true;
15499 
15500       // Otherwise it's a declaration.  Call out a particularly common
15501       // case here.
15502       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15503         unsigned Kind = 0;
15504         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15505         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15506           << Name << Kind << TND->getUnderlyingType();
15507         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15508         Invalid = true;
15509 
15510       // Otherwise, diagnose.
15511       } else {
15512         // The tag name clashes with something else in the target scope,
15513         // issue an error and recover by making this tag be anonymous.
15514         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15515         notePreviousDefinition(PrevDecl, NameLoc);
15516         Name = nullptr;
15517         Invalid = true;
15518       }
15519 
15520       // The existing declaration isn't relevant to us; we're in a
15521       // new scope, so clear out the previous declaration.
15522       Previous.clear();
15523     }
15524   }
15525 
15526 CreateNewDecl:
15527 
15528   TagDecl *PrevDecl = nullptr;
15529   if (Previous.isSingleResult())
15530     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15531 
15532   // If there is an identifier, use the location of the identifier as the
15533   // location of the decl, otherwise use the location of the struct/union
15534   // keyword.
15535   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15536 
15537   // Otherwise, create a new declaration. If there is a previous
15538   // declaration of the same entity, the two will be linked via
15539   // PrevDecl.
15540   TagDecl *New;
15541 
15542   if (Kind == TTK_Enum) {
15543     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15544     // enum X { A, B, C } D;    D should chain to X.
15545     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15546                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15547                            ScopedEnumUsesClassTag, IsFixed);
15548 
15549     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15550       StdAlignValT = cast<EnumDecl>(New);
15551 
15552     // If this is an undefined enum, warn.
15553     if (TUK != TUK_Definition && !Invalid) {
15554       TagDecl *Def;
15555       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15556         // C++0x: 7.2p2: opaque-enum-declaration.
15557         // Conflicts are diagnosed above. Do nothing.
15558       }
15559       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15560         Diag(Loc, diag::ext_forward_ref_enum_def)
15561           << New;
15562         Diag(Def->getLocation(), diag::note_previous_definition);
15563       } else {
15564         unsigned DiagID = diag::ext_forward_ref_enum;
15565         if (getLangOpts().MSVCCompat)
15566           DiagID = diag::ext_ms_forward_ref_enum;
15567         else if (getLangOpts().CPlusPlus)
15568           DiagID = diag::err_forward_ref_enum;
15569         Diag(Loc, DiagID);
15570       }
15571     }
15572 
15573     if (EnumUnderlying) {
15574       EnumDecl *ED = cast<EnumDecl>(New);
15575       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15576         ED->setIntegerTypeSourceInfo(TI);
15577       else
15578         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15579       ED->setPromotionType(ED->getIntegerType());
15580       assert(ED->isComplete() && "enum with type should be complete");
15581     }
15582   } else {
15583     // struct/union/class
15584 
15585     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15586     // struct X { int A; } D;    D should chain to X.
15587     if (getLangOpts().CPlusPlus) {
15588       // FIXME: Look for a way to use RecordDecl for simple structs.
15589       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15590                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15591 
15592       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15593         StdBadAlloc = cast<CXXRecordDecl>(New);
15594     } else
15595       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15596                                cast_or_null<RecordDecl>(PrevDecl));
15597   }
15598 
15599   // C++11 [dcl.type]p3:
15600   //   A type-specifier-seq shall not define a class or enumeration [...].
15601   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15602       TUK == TUK_Definition) {
15603     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15604       << Context.getTagDeclType(New);
15605     Invalid = true;
15606   }
15607 
15608   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15609       DC->getDeclKind() == Decl::Enum) {
15610     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15611       << Context.getTagDeclType(New);
15612     Invalid = true;
15613   }
15614 
15615   // Maybe add qualifier info.
15616   if (SS.isNotEmpty()) {
15617     if (SS.isSet()) {
15618       // If this is either a declaration or a definition, check the
15619       // nested-name-specifier against the current context.
15620       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15621           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15622                                        isMemberSpecialization))
15623         Invalid = true;
15624 
15625       New->setQualifierInfo(SS.getWithLocInContext(Context));
15626       if (TemplateParameterLists.size() > 0) {
15627         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15628       }
15629     }
15630     else
15631       Invalid = true;
15632   }
15633 
15634   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15635     // Add alignment attributes if necessary; these attributes are checked when
15636     // the ASTContext lays out the structure.
15637     //
15638     // It is important for implementing the correct semantics that this
15639     // happen here (in ActOnTag). The #pragma pack stack is
15640     // maintained as a result of parser callbacks which can occur at
15641     // many points during the parsing of a struct declaration (because
15642     // the #pragma tokens are effectively skipped over during the
15643     // parsing of the struct).
15644     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15645       AddAlignmentAttributesForRecord(RD);
15646       AddMsStructLayoutForRecord(RD);
15647     }
15648   }
15649 
15650   if (ModulePrivateLoc.isValid()) {
15651     if (isMemberSpecialization)
15652       Diag(New->getLocation(), diag::err_module_private_specialization)
15653         << 2
15654         << FixItHint::CreateRemoval(ModulePrivateLoc);
15655     // __module_private__ does not apply to local classes. However, we only
15656     // diagnose this as an error when the declaration specifiers are
15657     // freestanding. Here, we just ignore the __module_private__.
15658     else if (!SearchDC->isFunctionOrMethod())
15659       New->setModulePrivate();
15660   }
15661 
15662   // If this is a specialization of a member class (of a class template),
15663   // check the specialization.
15664   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15665     Invalid = true;
15666 
15667   // If we're declaring or defining a tag in function prototype scope in C,
15668   // note that this type can only be used within the function and add it to
15669   // the list of decls to inject into the function definition scope.
15670   if ((Name || Kind == TTK_Enum) &&
15671       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15672     if (getLangOpts().CPlusPlus) {
15673       // C++ [dcl.fct]p6:
15674       //   Types shall not be defined in return or parameter types.
15675       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15676         Diag(Loc, diag::err_type_defined_in_param_type)
15677             << Name;
15678         Invalid = true;
15679       }
15680     } else if (!PrevDecl) {
15681       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15682     }
15683   }
15684 
15685   if (Invalid)
15686     New->setInvalidDecl();
15687 
15688   // Set the lexical context. If the tag has a C++ scope specifier, the
15689   // lexical context will be different from the semantic context.
15690   New->setLexicalDeclContext(CurContext);
15691 
15692   // Mark this as a friend decl if applicable.
15693   // In Microsoft mode, a friend declaration also acts as a forward
15694   // declaration so we always pass true to setObjectOfFriendDecl to make
15695   // the tag name visible.
15696   if (TUK == TUK_Friend)
15697     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15698 
15699   // Set the access specifier.
15700   if (!Invalid && SearchDC->isRecord())
15701     SetMemberAccessSpecifier(New, PrevDecl, AS);
15702 
15703   if (PrevDecl)
15704     CheckRedeclarationModuleOwnership(New, PrevDecl);
15705 
15706   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15707     New->startDefinition();
15708 
15709   ProcessDeclAttributeList(S, New, Attrs);
15710   AddPragmaAttributes(S, New);
15711 
15712   // If this has an identifier, add it to the scope stack.
15713   if (TUK == TUK_Friend) {
15714     // We might be replacing an existing declaration in the lookup tables;
15715     // if so, borrow its access specifier.
15716     if (PrevDecl)
15717       New->setAccess(PrevDecl->getAccess());
15718 
15719     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15720     DC->makeDeclVisibleInContext(New);
15721     if (Name) // can be null along some error paths
15722       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15723         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15724   } else if (Name) {
15725     S = getNonFieldDeclScope(S);
15726     PushOnScopeChains(New, S, true);
15727   } else {
15728     CurContext->addDecl(New);
15729   }
15730 
15731   // If this is the C FILE type, notify the AST context.
15732   if (IdentifierInfo *II = New->getIdentifier())
15733     if (!New->isInvalidDecl() &&
15734         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15735         II->isStr("FILE"))
15736       Context.setFILEDecl(New);
15737 
15738   if (PrevDecl)
15739     mergeDeclAttributes(New, PrevDecl);
15740 
15741   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15742     inferGslOwnerPointerAttribute(CXXRD);
15743 
15744   // If there's a #pragma GCC visibility in scope, set the visibility of this
15745   // record.
15746   AddPushedVisibilityAttribute(New);
15747 
15748   if (isMemberSpecialization && !New->isInvalidDecl())
15749     CompleteMemberSpecialization(New, Previous);
15750 
15751   OwnedDecl = true;
15752   // In C++, don't return an invalid declaration. We can't recover well from
15753   // the cases where we make the type anonymous.
15754   if (Invalid && getLangOpts().CPlusPlus) {
15755     if (New->isBeingDefined())
15756       if (auto RD = dyn_cast<RecordDecl>(New))
15757         RD->completeDefinition();
15758     return nullptr;
15759   } else if (SkipBody && SkipBody->ShouldSkip) {
15760     return SkipBody->Previous;
15761   } else {
15762     return New;
15763   }
15764 }
15765 
15766 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15767   AdjustDeclIfTemplate(TagD);
15768   TagDecl *Tag = cast<TagDecl>(TagD);
15769 
15770   // Enter the tag context.
15771   PushDeclContext(S, Tag);
15772 
15773   ActOnDocumentableDecl(TagD);
15774 
15775   // If there's a #pragma GCC visibility in scope, set the visibility of this
15776   // record.
15777   AddPushedVisibilityAttribute(Tag);
15778 }
15779 
15780 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15781                                     SkipBodyInfo &SkipBody) {
15782   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15783     return false;
15784 
15785   // Make the previous decl visible.
15786   makeMergedDefinitionVisible(SkipBody.Previous);
15787   return true;
15788 }
15789 
15790 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15791   assert(isa<ObjCContainerDecl>(IDecl) &&
15792          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15793   DeclContext *OCD = cast<DeclContext>(IDecl);
15794   assert(getContainingDC(OCD) == CurContext &&
15795       "The next DeclContext should be lexically contained in the current one.");
15796   CurContext = OCD;
15797   return IDecl;
15798 }
15799 
15800 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15801                                            SourceLocation FinalLoc,
15802                                            bool IsFinalSpelledSealed,
15803                                            SourceLocation LBraceLoc) {
15804   AdjustDeclIfTemplate(TagD);
15805   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15806 
15807   FieldCollector->StartClass();
15808 
15809   if (!Record->getIdentifier())
15810     return;
15811 
15812   if (FinalLoc.isValid())
15813     Record->addAttr(FinalAttr::Create(
15814         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15815         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15816 
15817   // C++ [class]p2:
15818   //   [...] The class-name is also inserted into the scope of the
15819   //   class itself; this is known as the injected-class-name. For
15820   //   purposes of access checking, the injected-class-name is treated
15821   //   as if it were a public member name.
15822   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15823       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15824       Record->getLocation(), Record->getIdentifier(),
15825       /*PrevDecl=*/nullptr,
15826       /*DelayTypeCreation=*/true);
15827   Context.getTypeDeclType(InjectedClassName, Record);
15828   InjectedClassName->setImplicit();
15829   InjectedClassName->setAccess(AS_public);
15830   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15831       InjectedClassName->setDescribedClassTemplate(Template);
15832   PushOnScopeChains(InjectedClassName, S);
15833   assert(InjectedClassName->isInjectedClassName() &&
15834          "Broken injected-class-name");
15835 }
15836 
15837 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15838                                     SourceRange BraceRange) {
15839   AdjustDeclIfTemplate(TagD);
15840   TagDecl *Tag = cast<TagDecl>(TagD);
15841   Tag->setBraceRange(BraceRange);
15842 
15843   // Make sure we "complete" the definition even it is invalid.
15844   if (Tag->isBeingDefined()) {
15845     assert(Tag->isInvalidDecl() && "We should already have completed it");
15846     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15847       RD->completeDefinition();
15848   }
15849 
15850   if (isa<CXXRecordDecl>(Tag)) {
15851     FieldCollector->FinishClass();
15852   }
15853 
15854   // Exit this scope of this tag's definition.
15855   PopDeclContext();
15856 
15857   if (getCurLexicalContext()->isObjCContainer() &&
15858       Tag->getDeclContext()->isFileContext())
15859     Tag->setTopLevelDeclInObjCContainer();
15860 
15861   // Notify the consumer that we've defined a tag.
15862   if (!Tag->isInvalidDecl())
15863     Consumer.HandleTagDeclDefinition(Tag);
15864 }
15865 
15866 void Sema::ActOnObjCContainerFinishDefinition() {
15867   // Exit this scope of this interface definition.
15868   PopDeclContext();
15869 }
15870 
15871 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15872   assert(DC == CurContext && "Mismatch of container contexts");
15873   OriginalLexicalContext = DC;
15874   ActOnObjCContainerFinishDefinition();
15875 }
15876 
15877 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15878   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15879   OriginalLexicalContext = nullptr;
15880 }
15881 
15882 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15883   AdjustDeclIfTemplate(TagD);
15884   TagDecl *Tag = cast<TagDecl>(TagD);
15885   Tag->setInvalidDecl();
15886 
15887   // Make sure we "complete" the definition even it is invalid.
15888   if (Tag->isBeingDefined()) {
15889     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15890       RD->completeDefinition();
15891   }
15892 
15893   // We're undoing ActOnTagStartDefinition here, not
15894   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15895   // the FieldCollector.
15896 
15897   PopDeclContext();
15898 }
15899 
15900 // Note that FieldName may be null for anonymous bitfields.
15901 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15902                                 IdentifierInfo *FieldName,
15903                                 QualType FieldTy, bool IsMsStruct,
15904                                 Expr *BitWidth, bool *ZeroWidth) {
15905   // Default to true; that shouldn't confuse checks for emptiness
15906   if (ZeroWidth)
15907     *ZeroWidth = true;
15908 
15909   // C99 6.7.2.1p4 - verify the field type.
15910   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15911   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15912     // Handle incomplete types with specific error.
15913     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15914       return ExprError();
15915     if (FieldName)
15916       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15917         << FieldName << FieldTy << BitWidth->getSourceRange();
15918     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15919       << FieldTy << BitWidth->getSourceRange();
15920   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15921                                              UPPC_BitFieldWidth))
15922     return ExprError();
15923 
15924   // If the bit-width is type- or value-dependent, don't try to check
15925   // it now.
15926   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15927     return BitWidth;
15928 
15929   llvm::APSInt Value;
15930   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15931   if (ICE.isInvalid())
15932     return ICE;
15933   BitWidth = ICE.get();
15934 
15935   if (Value != 0 && ZeroWidth)
15936     *ZeroWidth = false;
15937 
15938   // Zero-width bitfield is ok for anonymous field.
15939   if (Value == 0 && FieldName)
15940     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15941 
15942   if (Value.isSigned() && Value.isNegative()) {
15943     if (FieldName)
15944       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15945                << FieldName << Value.toString(10);
15946     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15947       << Value.toString(10);
15948   }
15949 
15950   if (!FieldTy->isDependentType()) {
15951     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15952     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15953     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15954 
15955     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15956     // ABI.
15957     bool CStdConstraintViolation =
15958         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15959     bool MSBitfieldViolation =
15960         Value.ugt(TypeStorageSize) &&
15961         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15962     if (CStdConstraintViolation || MSBitfieldViolation) {
15963       unsigned DiagWidth =
15964           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15965       if (FieldName)
15966         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15967                << FieldName << (unsigned)Value.getZExtValue()
15968                << !CStdConstraintViolation << DiagWidth;
15969 
15970       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15971              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15972              << DiagWidth;
15973     }
15974 
15975     // Warn on types where the user might conceivably expect to get all
15976     // specified bits as value bits: that's all integral types other than
15977     // 'bool'.
15978     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15979       if (FieldName)
15980         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15981             << FieldName << (unsigned)Value.getZExtValue()
15982             << (unsigned)TypeWidth;
15983       else
15984         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15985             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15986     }
15987   }
15988 
15989   return BitWidth;
15990 }
15991 
15992 /// ActOnField - Each field of a C struct/union is passed into this in order
15993 /// to create a FieldDecl object for it.
15994 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15995                        Declarator &D, Expr *BitfieldWidth) {
15996   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15997                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15998                                /*InitStyle=*/ICIS_NoInit, AS_public);
15999   return Res;
16000 }
16001 
16002 /// HandleField - Analyze a field of a C struct or a C++ data member.
16003 ///
16004 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16005                              SourceLocation DeclStart,
16006                              Declarator &D, Expr *BitWidth,
16007                              InClassInitStyle InitStyle,
16008                              AccessSpecifier AS) {
16009   if (D.isDecompositionDeclarator()) {
16010     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16011     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16012       << Decomp.getSourceRange();
16013     return nullptr;
16014   }
16015 
16016   IdentifierInfo *II = D.getIdentifier();
16017   SourceLocation Loc = DeclStart;
16018   if (II) Loc = D.getIdentifierLoc();
16019 
16020   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16021   QualType T = TInfo->getType();
16022   if (getLangOpts().CPlusPlus) {
16023     CheckExtraCXXDefaultArguments(D);
16024 
16025     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16026                                         UPPC_DataMemberType)) {
16027       D.setInvalidType();
16028       T = Context.IntTy;
16029       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16030     }
16031   }
16032 
16033   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16034 
16035   if (D.getDeclSpec().isInlineSpecified())
16036     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16037         << getLangOpts().CPlusPlus17;
16038   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16039     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16040          diag::err_invalid_thread)
16041       << DeclSpec::getSpecifierName(TSCS);
16042 
16043   // Check to see if this name was declared as a member previously
16044   NamedDecl *PrevDecl = nullptr;
16045   LookupResult Previous(*this, II, Loc, LookupMemberName,
16046                         ForVisibleRedeclaration);
16047   LookupName(Previous, S);
16048   switch (Previous.getResultKind()) {
16049     case LookupResult::Found:
16050     case LookupResult::FoundUnresolvedValue:
16051       PrevDecl = Previous.getAsSingle<NamedDecl>();
16052       break;
16053 
16054     case LookupResult::FoundOverloaded:
16055       PrevDecl = Previous.getRepresentativeDecl();
16056       break;
16057 
16058     case LookupResult::NotFound:
16059     case LookupResult::NotFoundInCurrentInstantiation:
16060     case LookupResult::Ambiguous:
16061       break;
16062   }
16063   Previous.suppressDiagnostics();
16064 
16065   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16066     // Maybe we will complain about the shadowed template parameter.
16067     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16068     // Just pretend that we didn't see the previous declaration.
16069     PrevDecl = nullptr;
16070   }
16071 
16072   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16073     PrevDecl = nullptr;
16074 
16075   bool Mutable
16076     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16077   SourceLocation TSSL = D.getBeginLoc();
16078   FieldDecl *NewFD
16079     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16080                      TSSL, AS, PrevDecl, &D);
16081 
16082   if (NewFD->isInvalidDecl())
16083     Record->setInvalidDecl();
16084 
16085   if (D.getDeclSpec().isModulePrivateSpecified())
16086     NewFD->setModulePrivate();
16087 
16088   if (NewFD->isInvalidDecl() && PrevDecl) {
16089     // Don't introduce NewFD into scope; there's already something
16090     // with the same name in the same scope.
16091   } else if (II) {
16092     PushOnScopeChains(NewFD, S);
16093   } else
16094     Record->addDecl(NewFD);
16095 
16096   return NewFD;
16097 }
16098 
16099 /// Build a new FieldDecl and check its well-formedness.
16100 ///
16101 /// This routine builds a new FieldDecl given the fields name, type,
16102 /// record, etc. \p PrevDecl should refer to any previous declaration
16103 /// with the same name and in the same scope as the field to be
16104 /// created.
16105 ///
16106 /// \returns a new FieldDecl.
16107 ///
16108 /// \todo The Declarator argument is a hack. It will be removed once
16109 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16110                                 TypeSourceInfo *TInfo,
16111                                 RecordDecl *Record, SourceLocation Loc,
16112                                 bool Mutable, Expr *BitWidth,
16113                                 InClassInitStyle InitStyle,
16114                                 SourceLocation TSSL,
16115                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16116                                 Declarator *D) {
16117   IdentifierInfo *II = Name.getAsIdentifierInfo();
16118   bool InvalidDecl = false;
16119   if (D) InvalidDecl = D->isInvalidType();
16120 
16121   // If we receive a broken type, recover by assuming 'int' and
16122   // marking this declaration as invalid.
16123   if (T.isNull()) {
16124     InvalidDecl = true;
16125     T = Context.IntTy;
16126   }
16127 
16128   QualType EltTy = Context.getBaseElementType(T);
16129   if (!EltTy->isDependentType()) {
16130     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16131       // Fields of incomplete type force their record to be invalid.
16132       Record->setInvalidDecl();
16133       InvalidDecl = true;
16134     } else {
16135       NamedDecl *Def;
16136       EltTy->isIncompleteType(&Def);
16137       if (Def && Def->isInvalidDecl()) {
16138         Record->setInvalidDecl();
16139         InvalidDecl = true;
16140       }
16141     }
16142   }
16143 
16144   // TR 18037 does not allow fields to be declared with address space
16145   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16146       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16147     Diag(Loc, diag::err_field_with_address_space);
16148     Record->setInvalidDecl();
16149     InvalidDecl = true;
16150   }
16151 
16152   if (LangOpts.OpenCL) {
16153     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16154     // used as structure or union field: image, sampler, event or block types.
16155     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16156         T->isBlockPointerType()) {
16157       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16158       Record->setInvalidDecl();
16159       InvalidDecl = true;
16160     }
16161     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16162     if (BitWidth) {
16163       Diag(Loc, diag::err_opencl_bitfields);
16164       InvalidDecl = true;
16165     }
16166   }
16167 
16168   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16169   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16170       T.hasQualifiers()) {
16171     InvalidDecl = true;
16172     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16173   }
16174 
16175   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16176   // than a variably modified type.
16177   if (!InvalidDecl && T->isVariablyModifiedType()) {
16178     bool SizeIsNegative;
16179     llvm::APSInt Oversized;
16180 
16181     TypeSourceInfo *FixedTInfo =
16182       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16183                                                     SizeIsNegative,
16184                                                     Oversized);
16185     if (FixedTInfo) {
16186       Diag(Loc, diag::warn_illegal_constant_array_size);
16187       TInfo = FixedTInfo;
16188       T = FixedTInfo->getType();
16189     } else {
16190       if (SizeIsNegative)
16191         Diag(Loc, diag::err_typecheck_negative_array_size);
16192       else if (Oversized.getBoolValue())
16193         Diag(Loc, diag::err_array_too_large)
16194           << Oversized.toString(10);
16195       else
16196         Diag(Loc, diag::err_typecheck_field_variable_size);
16197       InvalidDecl = true;
16198     }
16199   }
16200 
16201   // Fields can not have abstract class types
16202   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16203                                              diag::err_abstract_type_in_decl,
16204                                              AbstractFieldType))
16205     InvalidDecl = true;
16206 
16207   bool ZeroWidth = false;
16208   if (InvalidDecl)
16209     BitWidth = nullptr;
16210   // If this is declared as a bit-field, check the bit-field.
16211   if (BitWidth) {
16212     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16213                               &ZeroWidth).get();
16214     if (!BitWidth) {
16215       InvalidDecl = true;
16216       BitWidth = nullptr;
16217       ZeroWidth = false;
16218     }
16219   }
16220 
16221   // Check that 'mutable' is consistent with the type of the declaration.
16222   if (!InvalidDecl && Mutable) {
16223     unsigned DiagID = 0;
16224     if (T->isReferenceType())
16225       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16226                                         : diag::err_mutable_reference;
16227     else if (T.isConstQualified())
16228       DiagID = diag::err_mutable_const;
16229 
16230     if (DiagID) {
16231       SourceLocation ErrLoc = Loc;
16232       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16233         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16234       Diag(ErrLoc, DiagID);
16235       if (DiagID != diag::ext_mutable_reference) {
16236         Mutable = false;
16237         InvalidDecl = true;
16238       }
16239     }
16240   }
16241 
16242   // C++11 [class.union]p8 (DR1460):
16243   //   At most one variant member of a union may have a
16244   //   brace-or-equal-initializer.
16245   if (InitStyle != ICIS_NoInit)
16246     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16247 
16248   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16249                                        BitWidth, Mutable, InitStyle);
16250   if (InvalidDecl)
16251     NewFD->setInvalidDecl();
16252 
16253   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16254     Diag(Loc, diag::err_duplicate_member) << II;
16255     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16256     NewFD->setInvalidDecl();
16257   }
16258 
16259   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16260     if (Record->isUnion()) {
16261       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16262         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16263         if (RDecl->getDefinition()) {
16264           // C++ [class.union]p1: An object of a class with a non-trivial
16265           // constructor, a non-trivial copy constructor, a non-trivial
16266           // destructor, or a non-trivial copy assignment operator
16267           // cannot be a member of a union, nor can an array of such
16268           // objects.
16269           if (CheckNontrivialField(NewFD))
16270             NewFD->setInvalidDecl();
16271         }
16272       }
16273 
16274       // C++ [class.union]p1: If a union contains a member of reference type,
16275       // the program is ill-formed, except when compiling with MSVC extensions
16276       // enabled.
16277       if (EltTy->isReferenceType()) {
16278         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16279                                     diag::ext_union_member_of_reference_type :
16280                                     diag::err_union_member_of_reference_type)
16281           << NewFD->getDeclName() << EltTy;
16282         if (!getLangOpts().MicrosoftExt)
16283           NewFD->setInvalidDecl();
16284       }
16285     }
16286   }
16287 
16288   // FIXME: We need to pass in the attributes given an AST
16289   // representation, not a parser representation.
16290   if (D) {
16291     // FIXME: The current scope is almost... but not entirely... correct here.
16292     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16293 
16294     if (NewFD->hasAttrs())
16295       CheckAlignasUnderalignment(NewFD);
16296   }
16297 
16298   // In auto-retain/release, infer strong retension for fields of
16299   // retainable type.
16300   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16301     NewFD->setInvalidDecl();
16302 
16303   if (T.isObjCGCWeak())
16304     Diag(Loc, diag::warn_attribute_weak_on_field);
16305 
16306   NewFD->setAccess(AS);
16307   return NewFD;
16308 }
16309 
16310 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16311   assert(FD);
16312   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16313 
16314   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16315     return false;
16316 
16317   QualType EltTy = Context.getBaseElementType(FD->getType());
16318   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16319     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16320     if (RDecl->getDefinition()) {
16321       // We check for copy constructors before constructors
16322       // because otherwise we'll never get complaints about
16323       // copy constructors.
16324 
16325       CXXSpecialMember member = CXXInvalid;
16326       // We're required to check for any non-trivial constructors. Since the
16327       // implicit default constructor is suppressed if there are any
16328       // user-declared constructors, we just need to check that there is a
16329       // trivial default constructor and a trivial copy constructor. (We don't
16330       // worry about move constructors here, since this is a C++98 check.)
16331       if (RDecl->hasNonTrivialCopyConstructor())
16332         member = CXXCopyConstructor;
16333       else if (!RDecl->hasTrivialDefaultConstructor())
16334         member = CXXDefaultConstructor;
16335       else if (RDecl->hasNonTrivialCopyAssignment())
16336         member = CXXCopyAssignment;
16337       else if (RDecl->hasNonTrivialDestructor())
16338         member = CXXDestructor;
16339 
16340       if (member != CXXInvalid) {
16341         if (!getLangOpts().CPlusPlus11 &&
16342             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16343           // Objective-C++ ARC: it is an error to have a non-trivial field of
16344           // a union. However, system headers in Objective-C programs
16345           // occasionally have Objective-C lifetime objects within unions,
16346           // and rather than cause the program to fail, we make those
16347           // members unavailable.
16348           SourceLocation Loc = FD->getLocation();
16349           if (getSourceManager().isInSystemHeader(Loc)) {
16350             if (!FD->hasAttr<UnavailableAttr>())
16351               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16352                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16353             return false;
16354           }
16355         }
16356 
16357         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16358                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16359                diag::err_illegal_union_or_anon_struct_member)
16360           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16361         DiagnoseNontrivial(RDecl, member);
16362         return !getLangOpts().CPlusPlus11;
16363       }
16364     }
16365   }
16366 
16367   return false;
16368 }
16369 
16370 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16371 ///  AST enum value.
16372 static ObjCIvarDecl::AccessControl
16373 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16374   switch (ivarVisibility) {
16375   default: llvm_unreachable("Unknown visitibility kind");
16376   case tok::objc_private: return ObjCIvarDecl::Private;
16377   case tok::objc_public: return ObjCIvarDecl::Public;
16378   case tok::objc_protected: return ObjCIvarDecl::Protected;
16379   case tok::objc_package: return ObjCIvarDecl::Package;
16380   }
16381 }
16382 
16383 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16384 /// in order to create an IvarDecl object for it.
16385 Decl *Sema::ActOnIvar(Scope *S,
16386                                 SourceLocation DeclStart,
16387                                 Declarator &D, Expr *BitfieldWidth,
16388                                 tok::ObjCKeywordKind Visibility) {
16389 
16390   IdentifierInfo *II = D.getIdentifier();
16391   Expr *BitWidth = (Expr*)BitfieldWidth;
16392   SourceLocation Loc = DeclStart;
16393   if (II) Loc = D.getIdentifierLoc();
16394 
16395   // FIXME: Unnamed fields can be handled in various different ways, for
16396   // example, unnamed unions inject all members into the struct namespace!
16397 
16398   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16399   QualType T = TInfo->getType();
16400 
16401   if (BitWidth) {
16402     // 6.7.2.1p3, 6.7.2.1p4
16403     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16404     if (!BitWidth)
16405       D.setInvalidType();
16406   } else {
16407     // Not a bitfield.
16408 
16409     // validate II.
16410 
16411   }
16412   if (T->isReferenceType()) {
16413     Diag(Loc, diag::err_ivar_reference_type);
16414     D.setInvalidType();
16415   }
16416   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16417   // than a variably modified type.
16418   else if (T->isVariablyModifiedType()) {
16419     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16420     D.setInvalidType();
16421   }
16422 
16423   // Get the visibility (access control) for this ivar.
16424   ObjCIvarDecl::AccessControl ac =
16425     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16426                                         : ObjCIvarDecl::None;
16427   // Must set ivar's DeclContext to its enclosing interface.
16428   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16429   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16430     return nullptr;
16431   ObjCContainerDecl *EnclosingContext;
16432   if (ObjCImplementationDecl *IMPDecl =
16433       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16434     if (LangOpts.ObjCRuntime.isFragile()) {
16435     // Case of ivar declared in an implementation. Context is that of its class.
16436       EnclosingContext = IMPDecl->getClassInterface();
16437       assert(EnclosingContext && "Implementation has no class interface!");
16438     }
16439     else
16440       EnclosingContext = EnclosingDecl;
16441   } else {
16442     if (ObjCCategoryDecl *CDecl =
16443         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16444       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16445         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16446         return nullptr;
16447       }
16448     }
16449     EnclosingContext = EnclosingDecl;
16450   }
16451 
16452   // Construct the decl.
16453   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16454                                              DeclStart, Loc, II, T,
16455                                              TInfo, ac, (Expr *)BitfieldWidth);
16456 
16457   if (II) {
16458     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16459                                            ForVisibleRedeclaration);
16460     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16461         && !isa<TagDecl>(PrevDecl)) {
16462       Diag(Loc, diag::err_duplicate_member) << II;
16463       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16464       NewID->setInvalidDecl();
16465     }
16466   }
16467 
16468   // Process attributes attached to the ivar.
16469   ProcessDeclAttributes(S, NewID, D);
16470 
16471   if (D.isInvalidType())
16472     NewID->setInvalidDecl();
16473 
16474   // In ARC, infer 'retaining' for ivars of retainable type.
16475   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16476     NewID->setInvalidDecl();
16477 
16478   if (D.getDeclSpec().isModulePrivateSpecified())
16479     NewID->setModulePrivate();
16480 
16481   if (II) {
16482     // FIXME: When interfaces are DeclContexts, we'll need to add
16483     // these to the interface.
16484     S->AddDecl(NewID);
16485     IdResolver.AddDecl(NewID);
16486   }
16487 
16488   if (LangOpts.ObjCRuntime.isNonFragile() &&
16489       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16490     Diag(Loc, diag::warn_ivars_in_interface);
16491 
16492   return NewID;
16493 }
16494 
16495 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16496 /// class and class extensions. For every class \@interface and class
16497 /// extension \@interface, if the last ivar is a bitfield of any type,
16498 /// then add an implicit `char :0` ivar to the end of that interface.
16499 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16500                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16501   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16502     return;
16503 
16504   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16505   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16506 
16507   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16508     return;
16509   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16510   if (!ID) {
16511     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16512       if (!CD->IsClassExtension())
16513         return;
16514     }
16515     // No need to add this to end of @implementation.
16516     else
16517       return;
16518   }
16519   // All conditions are met. Add a new bitfield to the tail end of ivars.
16520   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16521   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16522 
16523   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16524                               DeclLoc, DeclLoc, nullptr,
16525                               Context.CharTy,
16526                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16527                                                                DeclLoc),
16528                               ObjCIvarDecl::Private, BW,
16529                               true);
16530   AllIvarDecls.push_back(Ivar);
16531 }
16532 
16533 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16534                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16535                        SourceLocation RBrac,
16536                        const ParsedAttributesView &Attrs) {
16537   assert(EnclosingDecl && "missing record or interface decl");
16538 
16539   // If this is an Objective-C @implementation or category and we have
16540   // new fields here we should reset the layout of the interface since
16541   // it will now change.
16542   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16543     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16544     switch (DC->getKind()) {
16545     default: break;
16546     case Decl::ObjCCategory:
16547       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16548       break;
16549     case Decl::ObjCImplementation:
16550       Context.
16551         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16552       break;
16553     }
16554   }
16555 
16556   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16557   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16558 
16559   // Start counting up the number of named members; make sure to include
16560   // members of anonymous structs and unions in the total.
16561   unsigned NumNamedMembers = 0;
16562   if (Record) {
16563     for (const auto *I : Record->decls()) {
16564       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16565         if (IFD->getDeclName())
16566           ++NumNamedMembers;
16567     }
16568   }
16569 
16570   // Verify that all the fields are okay.
16571   SmallVector<FieldDecl*, 32> RecFields;
16572 
16573   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16574        i != end; ++i) {
16575     FieldDecl *FD = cast<FieldDecl>(*i);
16576 
16577     // Get the type for the field.
16578     const Type *FDTy = FD->getType().getTypePtr();
16579 
16580     if (!FD->isAnonymousStructOrUnion()) {
16581       // Remember all fields written by the user.
16582       RecFields.push_back(FD);
16583     }
16584 
16585     // If the field is already invalid for some reason, don't emit more
16586     // diagnostics about it.
16587     if (FD->isInvalidDecl()) {
16588       EnclosingDecl->setInvalidDecl();
16589       continue;
16590     }
16591 
16592     // C99 6.7.2.1p2:
16593     //   A structure or union shall not contain a member with
16594     //   incomplete or function type (hence, a structure shall not
16595     //   contain an instance of itself, but may contain a pointer to
16596     //   an instance of itself), except that the last member of a
16597     //   structure with more than one named member may have incomplete
16598     //   array type; such a structure (and any union containing,
16599     //   possibly recursively, a member that is such a structure)
16600     //   shall not be a member of a structure or an element of an
16601     //   array.
16602     bool IsLastField = (i + 1 == Fields.end());
16603     if (FDTy->isFunctionType()) {
16604       // Field declared as a function.
16605       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16606         << FD->getDeclName();
16607       FD->setInvalidDecl();
16608       EnclosingDecl->setInvalidDecl();
16609       continue;
16610     } else if (FDTy->isIncompleteArrayType() &&
16611                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16612       if (Record) {
16613         // Flexible array member.
16614         // Microsoft and g++ is more permissive regarding flexible array.
16615         // It will accept flexible array in union and also
16616         // as the sole element of a struct/class.
16617         unsigned DiagID = 0;
16618         if (!Record->isUnion() && !IsLastField) {
16619           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16620             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16621           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16622           FD->setInvalidDecl();
16623           EnclosingDecl->setInvalidDecl();
16624           continue;
16625         } else if (Record->isUnion())
16626           DiagID = getLangOpts().MicrosoftExt
16627                        ? diag::ext_flexible_array_union_ms
16628                        : getLangOpts().CPlusPlus
16629                              ? diag::ext_flexible_array_union_gnu
16630                              : diag::err_flexible_array_union;
16631         else if (NumNamedMembers < 1)
16632           DiagID = getLangOpts().MicrosoftExt
16633                        ? diag::ext_flexible_array_empty_aggregate_ms
16634                        : getLangOpts().CPlusPlus
16635                              ? diag::ext_flexible_array_empty_aggregate_gnu
16636                              : diag::err_flexible_array_empty_aggregate;
16637 
16638         if (DiagID)
16639           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16640                                           << Record->getTagKind();
16641         // While the layout of types that contain virtual bases is not specified
16642         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16643         // virtual bases after the derived members.  This would make a flexible
16644         // array member declared at the end of an object not adjacent to the end
16645         // of the type.
16646         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16647           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16648               << FD->getDeclName() << Record->getTagKind();
16649         if (!getLangOpts().C99)
16650           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16651             << FD->getDeclName() << Record->getTagKind();
16652 
16653         // If the element type has a non-trivial destructor, we would not
16654         // implicitly destroy the elements, so disallow it for now.
16655         //
16656         // FIXME: GCC allows this. We should probably either implicitly delete
16657         // the destructor of the containing class, or just allow this.
16658         QualType BaseElem = Context.getBaseElementType(FD->getType());
16659         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16660           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16661             << FD->getDeclName() << FD->getType();
16662           FD->setInvalidDecl();
16663           EnclosingDecl->setInvalidDecl();
16664           continue;
16665         }
16666         // Okay, we have a legal flexible array member at the end of the struct.
16667         Record->setHasFlexibleArrayMember(true);
16668       } else {
16669         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16670         // unless they are followed by another ivar. That check is done
16671         // elsewhere, after synthesized ivars are known.
16672       }
16673     } else if (!FDTy->isDependentType() &&
16674                RequireCompleteType(FD->getLocation(), FD->getType(),
16675                                    diag::err_field_incomplete)) {
16676       // Incomplete type
16677       FD->setInvalidDecl();
16678       EnclosingDecl->setInvalidDecl();
16679       continue;
16680     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16681       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16682         // A type which contains a flexible array member is considered to be a
16683         // flexible array member.
16684         Record->setHasFlexibleArrayMember(true);
16685         if (!Record->isUnion()) {
16686           // If this is a struct/class and this is not the last element, reject
16687           // it.  Note that GCC supports variable sized arrays in the middle of
16688           // structures.
16689           if (!IsLastField)
16690             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16691               << FD->getDeclName() << FD->getType();
16692           else {
16693             // We support flexible arrays at the end of structs in
16694             // other structs as an extension.
16695             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16696               << FD->getDeclName();
16697           }
16698         }
16699       }
16700       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16701           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16702                                  diag::err_abstract_type_in_decl,
16703                                  AbstractIvarType)) {
16704         // Ivars can not have abstract class types
16705         FD->setInvalidDecl();
16706       }
16707       if (Record && FDTTy->getDecl()->hasObjectMember())
16708         Record->setHasObjectMember(true);
16709       if (Record && FDTTy->getDecl()->hasVolatileMember())
16710         Record->setHasVolatileMember(true);
16711     } else if (FDTy->isObjCObjectType()) {
16712       /// A field cannot be an Objective-c object
16713       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16714         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16715       QualType T = Context.getObjCObjectPointerType(FD->getType());
16716       FD->setType(T);
16717     } else if (Record && Record->isUnion() &&
16718                FD->getType().hasNonTrivialObjCLifetime() &&
16719                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16720                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16721                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16722                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16723       // For backward compatibility, fields of C unions declared in system
16724       // headers that have non-trivial ObjC ownership qualifications are marked
16725       // as unavailable unless the qualifier is explicit and __strong. This can
16726       // break ABI compatibility between programs compiled with ARC and MRR, but
16727       // is a better option than rejecting programs using those unions under
16728       // ARC.
16729       FD->addAttr(UnavailableAttr::CreateImplicit(
16730           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16731           FD->getLocation()));
16732     } else if (getLangOpts().ObjC &&
16733                getLangOpts().getGC() != LangOptions::NonGC &&
16734                Record && !Record->hasObjectMember()) {
16735       if (FD->getType()->isObjCObjectPointerType() ||
16736           FD->getType().isObjCGCStrong())
16737         Record->setHasObjectMember(true);
16738       else if (Context.getAsArrayType(FD->getType())) {
16739         QualType BaseType = Context.getBaseElementType(FD->getType());
16740         if (BaseType->isRecordType() &&
16741             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16742           Record->setHasObjectMember(true);
16743         else if (BaseType->isObjCObjectPointerType() ||
16744                  BaseType.isObjCGCStrong())
16745                Record->setHasObjectMember(true);
16746       }
16747     }
16748 
16749     if (Record && !getLangOpts().CPlusPlus &&
16750         !shouldIgnoreForRecordTriviality(FD)) {
16751       QualType FT = FD->getType();
16752       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16753         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16754         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16755             Record->isUnion())
16756           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16757       }
16758       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16759       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16760         Record->setNonTrivialToPrimitiveCopy(true);
16761         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16762           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16763       }
16764       if (FT.isDestructedType()) {
16765         Record->setNonTrivialToPrimitiveDestroy(true);
16766         Record->setParamDestroyedInCallee(true);
16767         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16768           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16769       }
16770 
16771       if (const auto *RT = FT->getAs<RecordType>()) {
16772         if (RT->getDecl()->getArgPassingRestrictions() ==
16773             RecordDecl::APK_CanNeverPassInRegs)
16774           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16775       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16776         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16777     }
16778 
16779     if (Record && FD->getType().isVolatileQualified())
16780       Record->setHasVolatileMember(true);
16781     // Keep track of the number of named members.
16782     if (FD->getIdentifier())
16783       ++NumNamedMembers;
16784   }
16785 
16786   // Okay, we successfully defined 'Record'.
16787   if (Record) {
16788     bool Completed = false;
16789     if (CXXRecord) {
16790       if (!CXXRecord->isInvalidDecl()) {
16791         // Set access bits correctly on the directly-declared conversions.
16792         for (CXXRecordDecl::conversion_iterator
16793                I = CXXRecord->conversion_begin(),
16794                E = CXXRecord->conversion_end(); I != E; ++I)
16795           I.setAccess((*I)->getAccess());
16796       }
16797 
16798       if (!CXXRecord->isDependentType()) {
16799         // Add any implicitly-declared members to this class.
16800         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16801 
16802         if (!CXXRecord->isInvalidDecl()) {
16803           // If we have virtual base classes, we may end up finding multiple
16804           // final overriders for a given virtual function. Check for this
16805           // problem now.
16806           if (CXXRecord->getNumVBases()) {
16807             CXXFinalOverriderMap FinalOverriders;
16808             CXXRecord->getFinalOverriders(FinalOverriders);
16809 
16810             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16811                                              MEnd = FinalOverriders.end();
16812                  M != MEnd; ++M) {
16813               for (OverridingMethods::iterator SO = M->second.begin(),
16814                                             SOEnd = M->second.end();
16815                    SO != SOEnd; ++SO) {
16816                 assert(SO->second.size() > 0 &&
16817                        "Virtual function without overriding functions?");
16818                 if (SO->second.size() == 1)
16819                   continue;
16820 
16821                 // C++ [class.virtual]p2:
16822                 //   In a derived class, if a virtual member function of a base
16823                 //   class subobject has more than one final overrider the
16824                 //   program is ill-formed.
16825                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16826                   << (const NamedDecl *)M->first << Record;
16827                 Diag(M->first->getLocation(),
16828                      diag::note_overridden_virtual_function);
16829                 for (OverridingMethods::overriding_iterator
16830                           OM = SO->second.begin(),
16831                        OMEnd = SO->second.end();
16832                      OM != OMEnd; ++OM)
16833                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16834                     << (const NamedDecl *)M->first << OM->Method->getParent();
16835 
16836                 Record->setInvalidDecl();
16837               }
16838             }
16839             CXXRecord->completeDefinition(&FinalOverriders);
16840             Completed = true;
16841           }
16842         }
16843       }
16844     }
16845 
16846     if (!Completed)
16847       Record->completeDefinition();
16848 
16849     // Handle attributes before checking the layout.
16850     ProcessDeclAttributeList(S, Record, Attrs);
16851 
16852     // We may have deferred checking for a deleted destructor. Check now.
16853     if (CXXRecord) {
16854       auto *Dtor = CXXRecord->getDestructor();
16855       if (Dtor && Dtor->isImplicit() &&
16856           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16857         CXXRecord->setImplicitDestructorIsDeleted();
16858         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16859       }
16860     }
16861 
16862     if (Record->hasAttrs()) {
16863       CheckAlignasUnderalignment(Record);
16864 
16865       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16866         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16867                                            IA->getRange(), IA->getBestCase(),
16868                                            IA->getInheritanceModel());
16869     }
16870 
16871     // Check if the structure/union declaration is a type that can have zero
16872     // size in C. For C this is a language extension, for C++ it may cause
16873     // compatibility problems.
16874     bool CheckForZeroSize;
16875     if (!getLangOpts().CPlusPlus) {
16876       CheckForZeroSize = true;
16877     } else {
16878       // For C++ filter out types that cannot be referenced in C code.
16879       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16880       CheckForZeroSize =
16881           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16882           !CXXRecord->isDependentType() &&
16883           CXXRecord->isCLike();
16884     }
16885     if (CheckForZeroSize) {
16886       bool ZeroSize = true;
16887       bool IsEmpty = true;
16888       unsigned NonBitFields = 0;
16889       for (RecordDecl::field_iterator I = Record->field_begin(),
16890                                       E = Record->field_end();
16891            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16892         IsEmpty = false;
16893         if (I->isUnnamedBitfield()) {
16894           if (!I->isZeroLengthBitField(Context))
16895             ZeroSize = false;
16896         } else {
16897           ++NonBitFields;
16898           QualType FieldType = I->getType();
16899           if (FieldType->isIncompleteType() ||
16900               !Context.getTypeSizeInChars(FieldType).isZero())
16901             ZeroSize = false;
16902         }
16903       }
16904 
16905       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16906       // allowed in C++, but warn if its declaration is inside
16907       // extern "C" block.
16908       if (ZeroSize) {
16909         Diag(RecLoc, getLangOpts().CPlusPlus ?
16910                          diag::warn_zero_size_struct_union_in_extern_c :
16911                          diag::warn_zero_size_struct_union_compat)
16912           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16913       }
16914 
16915       // Structs without named members are extension in C (C99 6.7.2.1p7),
16916       // but are accepted by GCC.
16917       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16918         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16919                                diag::ext_no_named_members_in_struct_union)
16920           << Record->isUnion();
16921       }
16922     }
16923   } else {
16924     ObjCIvarDecl **ClsFields =
16925       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16926     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16927       ID->setEndOfDefinitionLoc(RBrac);
16928       // Add ivar's to class's DeclContext.
16929       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16930         ClsFields[i]->setLexicalDeclContext(ID);
16931         ID->addDecl(ClsFields[i]);
16932       }
16933       // Must enforce the rule that ivars in the base classes may not be
16934       // duplicates.
16935       if (ID->getSuperClass())
16936         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16937     } else if (ObjCImplementationDecl *IMPDecl =
16938                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16939       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16940       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16941         // Ivar declared in @implementation never belongs to the implementation.
16942         // Only it is in implementation's lexical context.
16943         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16944       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16945       IMPDecl->setIvarLBraceLoc(LBrac);
16946       IMPDecl->setIvarRBraceLoc(RBrac);
16947     } else if (ObjCCategoryDecl *CDecl =
16948                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16949       // case of ivars in class extension; all other cases have been
16950       // reported as errors elsewhere.
16951       // FIXME. Class extension does not have a LocEnd field.
16952       // CDecl->setLocEnd(RBrac);
16953       // Add ivar's to class extension's DeclContext.
16954       // Diagnose redeclaration of private ivars.
16955       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16956       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16957         if (IDecl) {
16958           if (const ObjCIvarDecl *ClsIvar =
16959               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16960             Diag(ClsFields[i]->getLocation(),
16961                  diag::err_duplicate_ivar_declaration);
16962             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16963             continue;
16964           }
16965           for (const auto *Ext : IDecl->known_extensions()) {
16966             if (const ObjCIvarDecl *ClsExtIvar
16967                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16968               Diag(ClsFields[i]->getLocation(),
16969                    diag::err_duplicate_ivar_declaration);
16970               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16971               continue;
16972             }
16973           }
16974         }
16975         ClsFields[i]->setLexicalDeclContext(CDecl);
16976         CDecl->addDecl(ClsFields[i]);
16977       }
16978       CDecl->setIvarLBraceLoc(LBrac);
16979       CDecl->setIvarRBraceLoc(RBrac);
16980     }
16981   }
16982 }
16983 
16984 /// Determine whether the given integral value is representable within
16985 /// the given type T.
16986 static bool isRepresentableIntegerValue(ASTContext &Context,
16987                                         llvm::APSInt &Value,
16988                                         QualType T) {
16989   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16990          "Integral type required!");
16991   unsigned BitWidth = Context.getIntWidth(T);
16992 
16993   if (Value.isUnsigned() || Value.isNonNegative()) {
16994     if (T->isSignedIntegerOrEnumerationType())
16995       --BitWidth;
16996     return Value.getActiveBits() <= BitWidth;
16997   }
16998   return Value.getMinSignedBits() <= BitWidth;
16999 }
17000 
17001 // Given an integral type, return the next larger integral type
17002 // (or a NULL type of no such type exists).
17003 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17004   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17005   // enum checking below.
17006   assert((T->isIntegralType(Context) ||
17007          T->isEnumeralType()) && "Integral type required!");
17008   const unsigned NumTypes = 4;
17009   QualType SignedIntegralTypes[NumTypes] = {
17010     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17011   };
17012   QualType UnsignedIntegralTypes[NumTypes] = {
17013     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17014     Context.UnsignedLongLongTy
17015   };
17016 
17017   unsigned BitWidth = Context.getTypeSize(T);
17018   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17019                                                         : UnsignedIntegralTypes;
17020   for (unsigned I = 0; I != NumTypes; ++I)
17021     if (Context.getTypeSize(Types[I]) > BitWidth)
17022       return Types[I];
17023 
17024   return QualType();
17025 }
17026 
17027 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17028                                           EnumConstantDecl *LastEnumConst,
17029                                           SourceLocation IdLoc,
17030                                           IdentifierInfo *Id,
17031                                           Expr *Val) {
17032   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17033   llvm::APSInt EnumVal(IntWidth);
17034   QualType EltTy;
17035 
17036   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17037     Val = nullptr;
17038 
17039   if (Val)
17040     Val = DefaultLvalueConversion(Val).get();
17041 
17042   if (Val) {
17043     if (Enum->isDependentType() || Val->isTypeDependent())
17044       EltTy = Context.DependentTy;
17045     else {
17046       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17047         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17048         // constant-expression in the enumerator-definition shall be a converted
17049         // constant expression of the underlying type.
17050         EltTy = Enum->getIntegerType();
17051         ExprResult Converted =
17052           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17053                                            CCEK_Enumerator);
17054         if (Converted.isInvalid())
17055           Val = nullptr;
17056         else
17057           Val = Converted.get();
17058       } else if (!Val->isValueDependent() &&
17059                  !(Val = VerifyIntegerConstantExpression(Val,
17060                                                          &EnumVal).get())) {
17061         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17062       } else {
17063         if (Enum->isComplete()) {
17064           EltTy = Enum->getIntegerType();
17065 
17066           // In Obj-C and Microsoft mode, require the enumeration value to be
17067           // representable in the underlying type of the enumeration. In C++11,
17068           // we perform a non-narrowing conversion as part of converted constant
17069           // expression checking.
17070           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17071             if (Context.getTargetInfo()
17072                     .getTriple()
17073                     .isWindowsMSVCEnvironment()) {
17074               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17075             } else {
17076               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17077             }
17078           }
17079 
17080           // Cast to the underlying type.
17081           Val = ImpCastExprToType(Val, EltTy,
17082                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17083                                                          : CK_IntegralCast)
17084                     .get();
17085         } else if (getLangOpts().CPlusPlus) {
17086           // C++11 [dcl.enum]p5:
17087           //   If the underlying type is not fixed, the type of each enumerator
17088           //   is the type of its initializing value:
17089           //     - If an initializer is specified for an enumerator, the
17090           //       initializing value has the same type as the expression.
17091           EltTy = Val->getType();
17092         } else {
17093           // C99 6.7.2.2p2:
17094           //   The expression that defines the value of an enumeration constant
17095           //   shall be an integer constant expression that has a value
17096           //   representable as an int.
17097 
17098           // Complain if the value is not representable in an int.
17099           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17100             Diag(IdLoc, diag::ext_enum_value_not_int)
17101               << EnumVal.toString(10) << Val->getSourceRange()
17102               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17103           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17104             // Force the type of the expression to 'int'.
17105             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17106           }
17107           EltTy = Val->getType();
17108         }
17109       }
17110     }
17111   }
17112 
17113   if (!Val) {
17114     if (Enum->isDependentType())
17115       EltTy = Context.DependentTy;
17116     else if (!LastEnumConst) {
17117       // C++0x [dcl.enum]p5:
17118       //   If the underlying type is not fixed, the type of each enumerator
17119       //   is the type of its initializing value:
17120       //     - If no initializer is specified for the first enumerator, the
17121       //       initializing value has an unspecified integral type.
17122       //
17123       // GCC uses 'int' for its unspecified integral type, as does
17124       // C99 6.7.2.2p3.
17125       if (Enum->isFixed()) {
17126         EltTy = Enum->getIntegerType();
17127       }
17128       else {
17129         EltTy = Context.IntTy;
17130       }
17131     } else {
17132       // Assign the last value + 1.
17133       EnumVal = LastEnumConst->getInitVal();
17134       ++EnumVal;
17135       EltTy = LastEnumConst->getType();
17136 
17137       // Check for overflow on increment.
17138       if (EnumVal < LastEnumConst->getInitVal()) {
17139         // C++0x [dcl.enum]p5:
17140         //   If the underlying type is not fixed, the type of each enumerator
17141         //   is the type of its initializing value:
17142         //
17143         //     - Otherwise the type of the initializing value is the same as
17144         //       the type of the initializing value of the preceding enumerator
17145         //       unless the incremented value is not representable in that type,
17146         //       in which case the type is an unspecified integral type
17147         //       sufficient to contain the incremented value. If no such type
17148         //       exists, the program is ill-formed.
17149         QualType T = getNextLargerIntegralType(Context, EltTy);
17150         if (T.isNull() || Enum->isFixed()) {
17151           // There is no integral type larger enough to represent this
17152           // value. Complain, then allow the value to wrap around.
17153           EnumVal = LastEnumConst->getInitVal();
17154           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17155           ++EnumVal;
17156           if (Enum->isFixed())
17157             // When the underlying type is fixed, this is ill-formed.
17158             Diag(IdLoc, diag::err_enumerator_wrapped)
17159               << EnumVal.toString(10)
17160               << EltTy;
17161           else
17162             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17163               << EnumVal.toString(10);
17164         } else {
17165           EltTy = T;
17166         }
17167 
17168         // Retrieve the last enumerator's value, extent that type to the
17169         // type that is supposed to be large enough to represent the incremented
17170         // value, then increment.
17171         EnumVal = LastEnumConst->getInitVal();
17172         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17173         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17174         ++EnumVal;
17175 
17176         // If we're not in C++, diagnose the overflow of enumerator values,
17177         // which in C99 means that the enumerator value is not representable in
17178         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17179         // permits enumerator values that are representable in some larger
17180         // integral type.
17181         if (!getLangOpts().CPlusPlus && !T.isNull())
17182           Diag(IdLoc, diag::warn_enum_value_overflow);
17183       } else if (!getLangOpts().CPlusPlus &&
17184                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17185         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17186         Diag(IdLoc, diag::ext_enum_value_not_int)
17187           << EnumVal.toString(10) << 1;
17188       }
17189     }
17190   }
17191 
17192   if (!EltTy->isDependentType()) {
17193     // Make the enumerator value match the signedness and size of the
17194     // enumerator's type.
17195     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17196     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17197   }
17198 
17199   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17200                                   Val, EnumVal);
17201 }
17202 
17203 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17204                                                 SourceLocation IILoc) {
17205   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17206       !getLangOpts().CPlusPlus)
17207     return SkipBodyInfo();
17208 
17209   // We have an anonymous enum definition. Look up the first enumerator to
17210   // determine if we should merge the definition with an existing one and
17211   // skip the body.
17212   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17213                                          forRedeclarationInCurContext());
17214   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17215   if (!PrevECD)
17216     return SkipBodyInfo();
17217 
17218   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17219   NamedDecl *Hidden;
17220   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17221     SkipBodyInfo Skip;
17222     Skip.Previous = Hidden;
17223     return Skip;
17224   }
17225 
17226   return SkipBodyInfo();
17227 }
17228 
17229 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17230                               SourceLocation IdLoc, IdentifierInfo *Id,
17231                               const ParsedAttributesView &Attrs,
17232                               SourceLocation EqualLoc, Expr *Val) {
17233   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17234   EnumConstantDecl *LastEnumConst =
17235     cast_or_null<EnumConstantDecl>(lastEnumConst);
17236 
17237   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17238   // we find one that is.
17239   S = getNonFieldDeclScope(S);
17240 
17241   // Verify that there isn't already something declared with this name in this
17242   // scope.
17243   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17244   LookupName(R, S);
17245   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17246 
17247   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17248     // Maybe we will complain about the shadowed template parameter.
17249     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17250     // Just pretend that we didn't see the previous declaration.
17251     PrevDecl = nullptr;
17252   }
17253 
17254   // C++ [class.mem]p15:
17255   // If T is the name of a class, then each of the following shall have a name
17256   // different from T:
17257   // - every enumerator of every member of class T that is an unscoped
17258   // enumerated type
17259   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17260     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17261                             DeclarationNameInfo(Id, IdLoc));
17262 
17263   EnumConstantDecl *New =
17264     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17265   if (!New)
17266     return nullptr;
17267 
17268   if (PrevDecl) {
17269     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17270       // Check for other kinds of shadowing not already handled.
17271       CheckShadow(New, PrevDecl, R);
17272     }
17273 
17274     // When in C++, we may get a TagDecl with the same name; in this case the
17275     // enum constant will 'hide' the tag.
17276     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17277            "Received TagDecl when not in C++!");
17278     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17279       if (isa<EnumConstantDecl>(PrevDecl))
17280         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17281       else
17282         Diag(IdLoc, diag::err_redefinition) << Id;
17283       notePreviousDefinition(PrevDecl, IdLoc);
17284       return nullptr;
17285     }
17286   }
17287 
17288   // Process attributes.
17289   ProcessDeclAttributeList(S, New, Attrs);
17290   AddPragmaAttributes(S, New);
17291 
17292   // Register this decl in the current scope stack.
17293   New->setAccess(TheEnumDecl->getAccess());
17294   PushOnScopeChains(New, S);
17295 
17296   ActOnDocumentableDecl(New);
17297 
17298   return New;
17299 }
17300 
17301 // Returns true when the enum initial expression does not trigger the
17302 // duplicate enum warning.  A few common cases are exempted as follows:
17303 // Element2 = Element1
17304 // Element2 = Element1 + 1
17305 // Element2 = Element1 - 1
17306 // Where Element2 and Element1 are from the same enum.
17307 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17308   Expr *InitExpr = ECD->getInitExpr();
17309   if (!InitExpr)
17310     return true;
17311   InitExpr = InitExpr->IgnoreImpCasts();
17312 
17313   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17314     if (!BO->isAdditiveOp())
17315       return true;
17316     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17317     if (!IL)
17318       return true;
17319     if (IL->getValue() != 1)
17320       return true;
17321 
17322     InitExpr = BO->getLHS();
17323   }
17324 
17325   // This checks if the elements are from the same enum.
17326   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17327   if (!DRE)
17328     return true;
17329 
17330   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17331   if (!EnumConstant)
17332     return true;
17333 
17334   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17335       Enum)
17336     return true;
17337 
17338   return false;
17339 }
17340 
17341 // Emits a warning when an element is implicitly set a value that
17342 // a previous element has already been set to.
17343 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17344                                         EnumDecl *Enum, QualType EnumType) {
17345   // Avoid anonymous enums
17346   if (!Enum->getIdentifier())
17347     return;
17348 
17349   // Only check for small enums.
17350   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17351     return;
17352 
17353   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17354     return;
17355 
17356   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17357   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17358 
17359   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17360   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17361 
17362   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17363   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17364     llvm::APSInt Val = D->getInitVal();
17365     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17366   };
17367 
17368   DuplicatesVector DupVector;
17369   ValueToVectorMap EnumMap;
17370 
17371   // Populate the EnumMap with all values represented by enum constants without
17372   // an initializer.
17373   for (auto *Element : Elements) {
17374     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17375 
17376     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17377     // this constant.  Skip this enum since it may be ill-formed.
17378     if (!ECD) {
17379       return;
17380     }
17381 
17382     // Constants with initalizers are handled in the next loop.
17383     if (ECD->getInitExpr())
17384       continue;
17385 
17386     // Duplicate values are handled in the next loop.
17387     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17388   }
17389 
17390   if (EnumMap.size() == 0)
17391     return;
17392 
17393   // Create vectors for any values that has duplicates.
17394   for (auto *Element : Elements) {
17395     // The last loop returned if any constant was null.
17396     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17397     if (!ValidDuplicateEnum(ECD, Enum))
17398       continue;
17399 
17400     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17401     if (Iter == EnumMap.end())
17402       continue;
17403 
17404     DeclOrVector& Entry = Iter->second;
17405     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17406       // Ensure constants are different.
17407       if (D == ECD)
17408         continue;
17409 
17410       // Create new vector and push values onto it.
17411       auto Vec = std::make_unique<ECDVector>();
17412       Vec->push_back(D);
17413       Vec->push_back(ECD);
17414 
17415       // Update entry to point to the duplicates vector.
17416       Entry = Vec.get();
17417 
17418       // Store the vector somewhere we can consult later for quick emission of
17419       // diagnostics.
17420       DupVector.emplace_back(std::move(Vec));
17421       continue;
17422     }
17423 
17424     ECDVector *Vec = Entry.get<ECDVector*>();
17425     // Make sure constants are not added more than once.
17426     if (*Vec->begin() == ECD)
17427       continue;
17428 
17429     Vec->push_back(ECD);
17430   }
17431 
17432   // Emit diagnostics.
17433   for (const auto &Vec : DupVector) {
17434     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17435 
17436     // Emit warning for one enum constant.
17437     auto *FirstECD = Vec->front();
17438     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17439       << FirstECD << FirstECD->getInitVal().toString(10)
17440       << FirstECD->getSourceRange();
17441 
17442     // Emit one note for each of the remaining enum constants with
17443     // the same value.
17444     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17445       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17446         << ECD << ECD->getInitVal().toString(10)
17447         << ECD->getSourceRange();
17448   }
17449 }
17450 
17451 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17452                              bool AllowMask) const {
17453   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17454   assert(ED->isCompleteDefinition() && "expected enum definition");
17455 
17456   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17457   llvm::APInt &FlagBits = R.first->second;
17458 
17459   if (R.second) {
17460     for (auto *E : ED->enumerators()) {
17461       const auto &EVal = E->getInitVal();
17462       // Only single-bit enumerators introduce new flag values.
17463       if (EVal.isPowerOf2())
17464         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17465     }
17466   }
17467 
17468   // A value is in a flag enum if either its bits are a subset of the enum's
17469   // flag bits (the first condition) or we are allowing masks and the same is
17470   // true of its complement (the second condition). When masks are allowed, we
17471   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17472   //
17473   // While it's true that any value could be used as a mask, the assumption is
17474   // that a mask will have all of the insignificant bits set. Anything else is
17475   // likely a logic error.
17476   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17477   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17478 }
17479 
17480 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17481                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17482                          const ParsedAttributesView &Attrs) {
17483   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17484   QualType EnumType = Context.getTypeDeclType(Enum);
17485 
17486   ProcessDeclAttributeList(S, Enum, Attrs);
17487 
17488   if (Enum->isDependentType()) {
17489     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17490       EnumConstantDecl *ECD =
17491         cast_or_null<EnumConstantDecl>(Elements[i]);
17492       if (!ECD) continue;
17493 
17494       ECD->setType(EnumType);
17495     }
17496 
17497     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17498     return;
17499   }
17500 
17501   // TODO: If the result value doesn't fit in an int, it must be a long or long
17502   // long value.  ISO C does not support this, but GCC does as an extension,
17503   // emit a warning.
17504   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17505   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17506   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17507 
17508   // Verify that all the values are okay, compute the size of the values, and
17509   // reverse the list.
17510   unsigned NumNegativeBits = 0;
17511   unsigned NumPositiveBits = 0;
17512 
17513   // Keep track of whether all elements have type int.
17514   bool AllElementsInt = true;
17515 
17516   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17517     EnumConstantDecl *ECD =
17518       cast_or_null<EnumConstantDecl>(Elements[i]);
17519     if (!ECD) continue;  // Already issued a diagnostic.
17520 
17521     const llvm::APSInt &InitVal = ECD->getInitVal();
17522 
17523     // Keep track of the size of positive and negative values.
17524     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17525       NumPositiveBits = std::max(NumPositiveBits,
17526                                  (unsigned)InitVal.getActiveBits());
17527     else
17528       NumNegativeBits = std::max(NumNegativeBits,
17529                                  (unsigned)InitVal.getMinSignedBits());
17530 
17531     // Keep track of whether every enum element has type int (very common).
17532     if (AllElementsInt)
17533       AllElementsInt = ECD->getType() == Context.IntTy;
17534   }
17535 
17536   // Figure out the type that should be used for this enum.
17537   QualType BestType;
17538   unsigned BestWidth;
17539 
17540   // C++0x N3000 [conv.prom]p3:
17541   //   An rvalue of an unscoped enumeration type whose underlying
17542   //   type is not fixed can be converted to an rvalue of the first
17543   //   of the following types that can represent all the values of
17544   //   the enumeration: int, unsigned int, long int, unsigned long
17545   //   int, long long int, or unsigned long long int.
17546   // C99 6.4.4.3p2:
17547   //   An identifier declared as an enumeration constant has type int.
17548   // The C99 rule is modified by a gcc extension
17549   QualType BestPromotionType;
17550 
17551   bool Packed = Enum->hasAttr<PackedAttr>();
17552   // -fshort-enums is the equivalent to specifying the packed attribute on all
17553   // enum definitions.
17554   if (LangOpts.ShortEnums)
17555     Packed = true;
17556 
17557   // If the enum already has a type because it is fixed or dictated by the
17558   // target, promote that type instead of analyzing the enumerators.
17559   if (Enum->isComplete()) {
17560     BestType = Enum->getIntegerType();
17561     if (BestType->isPromotableIntegerType())
17562       BestPromotionType = Context.getPromotedIntegerType(BestType);
17563     else
17564       BestPromotionType = BestType;
17565 
17566     BestWidth = Context.getIntWidth(BestType);
17567   }
17568   else if (NumNegativeBits) {
17569     // If there is a negative value, figure out the smallest integer type (of
17570     // int/long/longlong) that fits.
17571     // If it's packed, check also if it fits a char or a short.
17572     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17573       BestType = Context.SignedCharTy;
17574       BestWidth = CharWidth;
17575     } else if (Packed && NumNegativeBits <= ShortWidth &&
17576                NumPositiveBits < ShortWidth) {
17577       BestType = Context.ShortTy;
17578       BestWidth = ShortWidth;
17579     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17580       BestType = Context.IntTy;
17581       BestWidth = IntWidth;
17582     } else {
17583       BestWidth = Context.getTargetInfo().getLongWidth();
17584 
17585       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17586         BestType = Context.LongTy;
17587       } else {
17588         BestWidth = Context.getTargetInfo().getLongLongWidth();
17589 
17590         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17591           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17592         BestType = Context.LongLongTy;
17593       }
17594     }
17595     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17596   } else {
17597     // If there is no negative value, figure out the smallest type that fits
17598     // all of the enumerator values.
17599     // If it's packed, check also if it fits a char or a short.
17600     if (Packed && NumPositiveBits <= CharWidth) {
17601       BestType = Context.UnsignedCharTy;
17602       BestPromotionType = Context.IntTy;
17603       BestWidth = CharWidth;
17604     } else if (Packed && NumPositiveBits <= ShortWidth) {
17605       BestType = Context.UnsignedShortTy;
17606       BestPromotionType = Context.IntTy;
17607       BestWidth = ShortWidth;
17608     } else if (NumPositiveBits <= IntWidth) {
17609       BestType = Context.UnsignedIntTy;
17610       BestWidth = IntWidth;
17611       BestPromotionType
17612         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17613                            ? Context.UnsignedIntTy : Context.IntTy;
17614     } else if (NumPositiveBits <=
17615                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17616       BestType = Context.UnsignedLongTy;
17617       BestPromotionType
17618         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17619                            ? Context.UnsignedLongTy : Context.LongTy;
17620     } else {
17621       BestWidth = Context.getTargetInfo().getLongLongWidth();
17622       assert(NumPositiveBits <= BestWidth &&
17623              "How could an initializer get larger than ULL?");
17624       BestType = Context.UnsignedLongLongTy;
17625       BestPromotionType
17626         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17627                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17628     }
17629   }
17630 
17631   // Loop over all of the enumerator constants, changing their types to match
17632   // the type of the enum if needed.
17633   for (auto *D : Elements) {
17634     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17635     if (!ECD) continue;  // Already issued a diagnostic.
17636 
17637     // Standard C says the enumerators have int type, but we allow, as an
17638     // extension, the enumerators to be larger than int size.  If each
17639     // enumerator value fits in an int, type it as an int, otherwise type it the
17640     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17641     // that X has type 'int', not 'unsigned'.
17642 
17643     // Determine whether the value fits into an int.
17644     llvm::APSInt InitVal = ECD->getInitVal();
17645 
17646     // If it fits into an integer type, force it.  Otherwise force it to match
17647     // the enum decl type.
17648     QualType NewTy;
17649     unsigned NewWidth;
17650     bool NewSign;
17651     if (!getLangOpts().CPlusPlus &&
17652         !Enum->isFixed() &&
17653         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17654       NewTy = Context.IntTy;
17655       NewWidth = IntWidth;
17656       NewSign = true;
17657     } else if (ECD->getType() == BestType) {
17658       // Already the right type!
17659       if (getLangOpts().CPlusPlus)
17660         // C++ [dcl.enum]p4: Following the closing brace of an
17661         // enum-specifier, each enumerator has the type of its
17662         // enumeration.
17663         ECD->setType(EnumType);
17664       continue;
17665     } else {
17666       NewTy = BestType;
17667       NewWidth = BestWidth;
17668       NewSign = BestType->isSignedIntegerOrEnumerationType();
17669     }
17670 
17671     // Adjust the APSInt value.
17672     InitVal = InitVal.extOrTrunc(NewWidth);
17673     InitVal.setIsSigned(NewSign);
17674     ECD->setInitVal(InitVal);
17675 
17676     // Adjust the Expr initializer and type.
17677     if (ECD->getInitExpr() &&
17678         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17679       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17680                                                 CK_IntegralCast,
17681                                                 ECD->getInitExpr(),
17682                                                 /*base paths*/ nullptr,
17683                                                 VK_RValue));
17684     if (getLangOpts().CPlusPlus)
17685       // C++ [dcl.enum]p4: Following the closing brace of an
17686       // enum-specifier, each enumerator has the type of its
17687       // enumeration.
17688       ECD->setType(EnumType);
17689     else
17690       ECD->setType(NewTy);
17691   }
17692 
17693   Enum->completeDefinition(BestType, BestPromotionType,
17694                            NumPositiveBits, NumNegativeBits);
17695 
17696   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17697 
17698   if (Enum->isClosedFlag()) {
17699     for (Decl *D : Elements) {
17700       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17701       if (!ECD) continue;  // Already issued a diagnostic.
17702 
17703       llvm::APSInt InitVal = ECD->getInitVal();
17704       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17705           !IsValueInFlagEnum(Enum, InitVal, true))
17706         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17707           << ECD << Enum;
17708     }
17709   }
17710 
17711   // Now that the enum type is defined, ensure it's not been underaligned.
17712   if (Enum->hasAttrs())
17713     CheckAlignasUnderalignment(Enum);
17714 }
17715 
17716 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17717                                   SourceLocation StartLoc,
17718                                   SourceLocation EndLoc) {
17719   StringLiteral *AsmString = cast<StringLiteral>(expr);
17720 
17721   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17722                                                    AsmString, StartLoc,
17723                                                    EndLoc);
17724   CurContext->addDecl(New);
17725   return New;
17726 }
17727 
17728 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17729                                       IdentifierInfo* AliasName,
17730                                       SourceLocation PragmaLoc,
17731                                       SourceLocation NameLoc,
17732                                       SourceLocation AliasNameLoc) {
17733   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17734                                          LookupOrdinaryName);
17735   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17736                            AttributeCommonInfo::AS_Pragma);
17737   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17738       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17739 
17740   // If a declaration that:
17741   // 1) declares a function or a variable
17742   // 2) has external linkage
17743   // already exists, add a label attribute to it.
17744   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17745     if (isDeclExternC(PrevDecl))
17746       PrevDecl->addAttr(Attr);
17747     else
17748       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17749           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17750   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17751   } else
17752     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17753 }
17754 
17755 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17756                              SourceLocation PragmaLoc,
17757                              SourceLocation NameLoc) {
17758   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17759 
17760   if (PrevDecl) {
17761     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17762   } else {
17763     (void)WeakUndeclaredIdentifiers.insert(
17764       std::pair<IdentifierInfo*,WeakInfo>
17765         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17766   }
17767 }
17768 
17769 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17770                                 IdentifierInfo* AliasName,
17771                                 SourceLocation PragmaLoc,
17772                                 SourceLocation NameLoc,
17773                                 SourceLocation AliasNameLoc) {
17774   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17775                                     LookupOrdinaryName);
17776   WeakInfo W = WeakInfo(Name, NameLoc);
17777 
17778   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17779     if (!PrevDecl->hasAttr<AliasAttr>())
17780       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17781         DeclApplyPragmaWeak(TUScope, ND, W);
17782   } else {
17783     (void)WeakUndeclaredIdentifiers.insert(
17784       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17785   }
17786 }
17787 
17788 Decl *Sema::getObjCDeclContext() const {
17789   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17790 }
17791 
17792 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17793   // Templates are emitted when they're instantiated.
17794   if (FD->isDependentContext())
17795     return FunctionEmissionStatus::TemplateDiscarded;
17796 
17797   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17798   if (LangOpts.OpenMPIsDevice) {
17799     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17800         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17801     if (DevTy.hasValue()) {
17802       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17803         OMPES = FunctionEmissionStatus::OMPDiscarded;
17804       else if (DeviceKnownEmittedFns.count(FD) > 0)
17805         OMPES = FunctionEmissionStatus::Emitted;
17806     }
17807   } else if (LangOpts.OpenMP) {
17808     // In OpenMP 4.5 all the functions are host functions.
17809     if (LangOpts.OpenMP <= 45) {
17810       OMPES = FunctionEmissionStatus::Emitted;
17811     } else {
17812       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17813           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17814       // In OpenMP 5.0 or above, DevTy may be changed later by
17815       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17816       // having no value does not imply host. The emission status will be
17817       // checked again at the end of compilation unit.
17818       if (DevTy.hasValue()) {
17819         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17820           OMPES = FunctionEmissionStatus::OMPDiscarded;
17821         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17822           OMPES = FunctionEmissionStatus::Emitted;
17823         }
17824       }
17825     }
17826   }
17827   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17828       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17829     return OMPES;
17830 
17831   if (LangOpts.CUDA) {
17832     // When compiling for device, host functions are never emitted.  Similarly,
17833     // when compiling for host, device and global functions are never emitted.
17834     // (Technically, we do emit a host-side stub for global functions, but this
17835     // doesn't count for our purposes here.)
17836     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17837     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17838       return FunctionEmissionStatus::CUDADiscarded;
17839     if (!LangOpts.CUDAIsDevice &&
17840         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17841       return FunctionEmissionStatus::CUDADiscarded;
17842 
17843     // Check whether this function is externally visible -- if so, it's
17844     // known-emitted.
17845     //
17846     // We have to check the GVA linkage of the function's *definition* -- if we
17847     // only have a declaration, we don't know whether or not the function will
17848     // be emitted, because (say) the definition could include "inline".
17849     FunctionDecl *Def = FD->getDefinition();
17850 
17851     if (Def &&
17852         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17853         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17854       return FunctionEmissionStatus::Emitted;
17855   }
17856 
17857   // Otherwise, the function is known-emitted if it's in our set of
17858   // known-emitted functions.
17859   return (DeviceKnownEmittedFns.count(FD) > 0)
17860              ? FunctionEmissionStatus::Emitted
17861              : FunctionEmissionStatus::Unknown;
17862 }
17863 
17864 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17865   // Host-side references to a __global__ function refer to the stub, so the
17866   // function itself is never emitted and therefore should not be marked.
17867   // If we have host fn calls kernel fn calls host+device, the HD function
17868   // does not get instantiated on the host. We model this by omitting at the
17869   // call to the kernel from the callgraph. This ensures that, when compiling
17870   // for host, only HD functions actually called from the host get marked as
17871   // known-emitted.
17872   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17873          IdentifyCUDATarget(Callee) == CFT_Global;
17874 }
17875