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   llvm_unreachable("Unexpected context");
6472 }
6473 
6474 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6475   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6476   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6477       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6478     return true;
6479   if (DC->isRecord())
6480     return false;
6481   llvm_unreachable("Unexpected context");
6482 }
6483 
6484 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6485                           ParsedAttr::Kind Kind) {
6486   // Check decl attributes on the DeclSpec.
6487   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6488     return true;
6489 
6490   // Walk the declarator structure, checking decl attributes that were in a type
6491   // position to the decl itself.
6492   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6493     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6494       return true;
6495   }
6496 
6497   // Finally, check attributes on the decl itself.
6498   return PD.getAttributes().hasAttribute(Kind);
6499 }
6500 
6501 /// Adjust the \c DeclContext for a function or variable that might be a
6502 /// function-local external declaration.
6503 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6504   if (!DC->isFunctionOrMethod())
6505     return false;
6506 
6507   // If this is a local extern function or variable declared within a function
6508   // template, don't add it into the enclosing namespace scope until it is
6509   // instantiated; it might have a dependent type right now.
6510   if (DC->isDependentContext())
6511     return true;
6512 
6513   // C++11 [basic.link]p7:
6514   //   When a block scope declaration of an entity with linkage is not found to
6515   //   refer to some other declaration, then that entity is a member of the
6516   //   innermost enclosing namespace.
6517   //
6518   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6519   // semantically-enclosing namespace, not a lexically-enclosing one.
6520   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6521     DC = DC->getParent();
6522   return true;
6523 }
6524 
6525 /// Returns true if given declaration has external C language linkage.
6526 static bool isDeclExternC(const Decl *D) {
6527   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6528     return FD->isExternC();
6529   if (const auto *VD = dyn_cast<VarDecl>(D))
6530     return VD->isExternC();
6531 
6532   llvm_unreachable("Unknown type of decl!");
6533 }
6534 /// Returns true if there hasn't been any invalid type diagnosed.
6535 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6536                                 DeclContext *DC, QualType R) {
6537   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6538   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6539   // argument.
6540   if (R->isImageType() || R->isPipeType()) {
6541     Se.Diag(D.getIdentifierLoc(),
6542             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6543         << R;
6544     D.setInvalidType();
6545     return false;
6546   }
6547 
6548   // OpenCL v1.2 s6.9.r:
6549   // The event type cannot be used to declare a program scope variable.
6550   // OpenCL v2.0 s6.9.q:
6551   // The clk_event_t and reserve_id_t types cannot be declared in program
6552   // scope.
6553   if (NULL == S->getParent()) {
6554     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6555       Se.Diag(D.getIdentifierLoc(),
6556               diag::err_invalid_type_for_program_scope_var)
6557           << R;
6558       D.setInvalidType();
6559       return false;
6560     }
6561   }
6562 
6563   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6564   QualType NR = R;
6565   while (NR->isPointerType()) {
6566     if (NR->isFunctionPointerType()) {
6567       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6568       D.setInvalidType();
6569       return false;
6570     }
6571     NR = NR->getPointeeType();
6572   }
6573 
6574   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6575     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6576     // half array type (unless the cl_khr_fp16 extension is enabled).
6577     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6578       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6579       D.setInvalidType();
6580       return false;
6581     }
6582   }
6583 
6584   // OpenCL v1.2 s6.9.r:
6585   // The event type cannot be used with the __local, __constant and __global
6586   // address space qualifiers.
6587   if (R->isEventT()) {
6588     if (R.getAddressSpace() != LangAS::opencl_private) {
6589       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6590       D.setInvalidType();
6591       return false;
6592     }
6593   }
6594 
6595   // C++ for OpenCL does not allow the thread_local storage qualifier.
6596   // OpenCL C does not support thread_local either, and
6597   // also reject all other thread storage class specifiers.
6598   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6599   if (TSC != TSCS_unspecified) {
6600     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6601     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6602             diag::err_opencl_unknown_type_specifier)
6603         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6604         << DeclSpec::getSpecifierName(TSC) << 1;
6605     D.setInvalidType();
6606     return false;
6607   }
6608 
6609   if (R->isSamplerT()) {
6610     // OpenCL v1.2 s6.9.b p4:
6611     // The sampler type cannot be used with the __local and __global address
6612     // space qualifiers.
6613     if (R.getAddressSpace() == LangAS::opencl_local ||
6614         R.getAddressSpace() == LangAS::opencl_global) {
6615       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6616       D.setInvalidType();
6617     }
6618 
6619     // OpenCL v1.2 s6.12.14.1:
6620     // A global sampler must be declared with either the constant address
6621     // space qualifier or with the const qualifier.
6622     if (DC->isTranslationUnit() &&
6623         !(R.getAddressSpace() == LangAS::opencl_constant ||
6624           R.isConstQualified())) {
6625       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6626       D.setInvalidType();
6627     }
6628     if (D.isInvalidType())
6629       return false;
6630   }
6631   return true;
6632 }
6633 
6634 NamedDecl *Sema::ActOnVariableDeclarator(
6635     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6636     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6637     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6638   QualType R = TInfo->getType();
6639   DeclarationName Name = GetNameForDeclarator(D).getName();
6640 
6641   IdentifierInfo *II = Name.getAsIdentifierInfo();
6642 
6643   if (D.isDecompositionDeclarator()) {
6644     // Take the name of the first declarator as our name for diagnostic
6645     // purposes.
6646     auto &Decomp = D.getDecompositionDeclarator();
6647     if (!Decomp.bindings().empty()) {
6648       II = Decomp.bindings()[0].Name;
6649       Name = II;
6650     }
6651   } else if (!II) {
6652     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6653     return nullptr;
6654   }
6655 
6656 
6657   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6658   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6659 
6660   // dllimport globals without explicit storage class are treated as extern. We
6661   // have to change the storage class this early to get the right DeclContext.
6662   if (SC == SC_None && !DC->isRecord() &&
6663       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6664       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6665     SC = SC_Extern;
6666 
6667   DeclContext *OriginalDC = DC;
6668   bool IsLocalExternDecl = SC == SC_Extern &&
6669                            adjustContextForLocalExternDecl(DC);
6670 
6671   if (SCSpec == DeclSpec::SCS_mutable) {
6672     // mutable can only appear on non-static class members, so it's always
6673     // an error here
6674     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6675     D.setInvalidType();
6676     SC = SC_None;
6677   }
6678 
6679   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6680       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6681                               D.getDeclSpec().getStorageClassSpecLoc())) {
6682     // In C++11, the 'register' storage class specifier is deprecated.
6683     // Suppress the warning in system macros, it's used in macros in some
6684     // popular C system headers, such as in glibc's htonl() macro.
6685     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6686          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6687                                    : diag::warn_deprecated_register)
6688       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6689   }
6690 
6691   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6692 
6693   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6694     // C99 6.9p2: The storage-class specifiers auto and register shall not
6695     // appear in the declaration specifiers in an external declaration.
6696     // Global Register+Asm is a GNU extension we support.
6697     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6698       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6699       D.setInvalidType();
6700     }
6701   }
6702 
6703   bool IsMemberSpecialization = false;
6704   bool IsVariableTemplateSpecialization = false;
6705   bool IsPartialSpecialization = false;
6706   bool IsVariableTemplate = false;
6707   VarDecl *NewVD = nullptr;
6708   VarTemplateDecl *NewTemplate = nullptr;
6709   TemplateParameterList *TemplateParams = nullptr;
6710   if (!getLangOpts().CPlusPlus) {
6711     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6712                             II, R, TInfo, SC);
6713 
6714     if (R->getContainedDeducedType())
6715       ParsingInitForAutoVars.insert(NewVD);
6716 
6717     if (D.isInvalidType())
6718       NewVD->setInvalidDecl();
6719 
6720     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6721         NewVD->hasLocalStorage())
6722       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6723                             NTCUC_AutoVar, NTCUK_Destruct);
6724   } else {
6725     bool Invalid = false;
6726 
6727     if (DC->isRecord() && !CurContext->isRecord()) {
6728       // This is an out-of-line definition of a static data member.
6729       switch (SC) {
6730       case SC_None:
6731         break;
6732       case SC_Static:
6733         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6734              diag::err_static_out_of_line)
6735           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6736         break;
6737       case SC_Auto:
6738       case SC_Register:
6739       case SC_Extern:
6740         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6741         // to names of variables declared in a block or to function parameters.
6742         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6743         // of class members
6744 
6745         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6746              diag::err_storage_class_for_static_member)
6747           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6748         break;
6749       case SC_PrivateExtern:
6750         llvm_unreachable("C storage class in c++!");
6751       }
6752     }
6753 
6754     if (SC == SC_Static && CurContext->isRecord()) {
6755       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6756         if (RD->isLocalClass())
6757           Diag(D.getIdentifierLoc(),
6758                diag::err_static_data_member_not_allowed_in_local_class)
6759             << Name << RD->getDeclName();
6760 
6761         // C++98 [class.union]p1: If a union contains a static data member,
6762         // the program is ill-formed. C++11 drops this restriction.
6763         if (RD->isUnion())
6764           Diag(D.getIdentifierLoc(),
6765                getLangOpts().CPlusPlus11
6766                  ? diag::warn_cxx98_compat_static_data_member_in_union
6767                  : diag::ext_static_data_member_in_union) << Name;
6768         // We conservatively disallow static data members in anonymous structs.
6769         else if (!RD->getDeclName())
6770           Diag(D.getIdentifierLoc(),
6771                diag::err_static_data_member_not_allowed_in_anon_struct)
6772             << Name << RD->isUnion();
6773       }
6774     }
6775 
6776     // Match up the template parameter lists with the scope specifier, then
6777     // determine whether we have a template or a template specialization.
6778     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6779         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6780         D.getCXXScopeSpec(),
6781         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6782             ? D.getName().TemplateId
6783             : nullptr,
6784         TemplateParamLists,
6785         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6786 
6787     if (TemplateParams) {
6788       if (!TemplateParams->size() &&
6789           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6790         // There is an extraneous 'template<>' for this variable. Complain
6791         // about it, but allow the declaration of the variable.
6792         Diag(TemplateParams->getTemplateLoc(),
6793              diag::err_template_variable_noparams)
6794           << II
6795           << SourceRange(TemplateParams->getTemplateLoc(),
6796                          TemplateParams->getRAngleLoc());
6797         TemplateParams = nullptr;
6798       } else {
6799         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6800           // This is an explicit specialization or a partial specialization.
6801           // FIXME: Check that we can declare a specialization here.
6802           IsVariableTemplateSpecialization = true;
6803           IsPartialSpecialization = TemplateParams->size() > 0;
6804         } else { // if (TemplateParams->size() > 0)
6805           // This is a template declaration.
6806           IsVariableTemplate = true;
6807 
6808           // Check that we can declare a template here.
6809           if (CheckTemplateDeclScope(S, TemplateParams))
6810             return nullptr;
6811 
6812           // Only C++1y supports variable templates (N3651).
6813           Diag(D.getIdentifierLoc(),
6814                getLangOpts().CPlusPlus14
6815                    ? diag::warn_cxx11_compat_variable_template
6816                    : diag::ext_variable_template);
6817         }
6818       }
6819     } else {
6820       assert((Invalid ||
6821               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6822              "should have a 'template<>' for this decl");
6823     }
6824 
6825     if (IsVariableTemplateSpecialization) {
6826       SourceLocation TemplateKWLoc =
6827           TemplateParamLists.size() > 0
6828               ? TemplateParamLists[0]->getTemplateLoc()
6829               : SourceLocation();
6830       DeclResult Res = ActOnVarTemplateSpecialization(
6831           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6832           IsPartialSpecialization);
6833       if (Res.isInvalid())
6834         return nullptr;
6835       NewVD = cast<VarDecl>(Res.get());
6836       AddToScope = false;
6837     } else if (D.isDecompositionDeclarator()) {
6838       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6839                                         D.getIdentifierLoc(), R, TInfo, SC,
6840                                         Bindings);
6841     } else
6842       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6843                               D.getIdentifierLoc(), II, R, TInfo, SC);
6844 
6845     // If this is supposed to be a variable template, create it as such.
6846     if (IsVariableTemplate) {
6847       NewTemplate =
6848           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6849                                   TemplateParams, NewVD);
6850       NewVD->setDescribedVarTemplate(NewTemplate);
6851     }
6852 
6853     // If this decl has an auto type in need of deduction, make a note of the
6854     // Decl so we can diagnose uses of it in its own initializer.
6855     if (R->getContainedDeducedType())
6856       ParsingInitForAutoVars.insert(NewVD);
6857 
6858     if (D.isInvalidType() || Invalid) {
6859       NewVD->setInvalidDecl();
6860       if (NewTemplate)
6861         NewTemplate->setInvalidDecl();
6862     }
6863 
6864     SetNestedNameSpecifier(*this, NewVD, D);
6865 
6866     // If we have any template parameter lists that don't directly belong to
6867     // the variable (matching the scope specifier), store them.
6868     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6869     if (TemplateParamLists.size() > VDTemplateParamLists)
6870       NewVD->setTemplateParameterListsInfo(
6871           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6872   }
6873 
6874   if (D.getDeclSpec().isInlineSpecified()) {
6875     if (!getLangOpts().CPlusPlus) {
6876       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6877           << 0;
6878     } else if (CurContext->isFunctionOrMethod()) {
6879       // 'inline' is not allowed on block scope variable declaration.
6880       Diag(D.getDeclSpec().getInlineSpecLoc(),
6881            diag::err_inline_declaration_block_scope) << Name
6882         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6883     } else {
6884       Diag(D.getDeclSpec().getInlineSpecLoc(),
6885            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6886                                      : diag::ext_inline_variable);
6887       NewVD->setInlineSpecified();
6888     }
6889   }
6890 
6891   // Set the lexical context. If the declarator has a C++ scope specifier, the
6892   // lexical context will be different from the semantic context.
6893   NewVD->setLexicalDeclContext(CurContext);
6894   if (NewTemplate)
6895     NewTemplate->setLexicalDeclContext(CurContext);
6896 
6897   if (IsLocalExternDecl) {
6898     if (D.isDecompositionDeclarator())
6899       for (auto *B : Bindings)
6900         B->setLocalExternDecl();
6901     else
6902       NewVD->setLocalExternDecl();
6903   }
6904 
6905   bool EmitTLSUnsupportedError = false;
6906   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6907     // C++11 [dcl.stc]p4:
6908     //   When thread_local is applied to a variable of block scope the
6909     //   storage-class-specifier static is implied if it does not appear
6910     //   explicitly.
6911     // Core issue: 'static' is not implied if the variable is declared
6912     //   'extern'.
6913     if (NewVD->hasLocalStorage() &&
6914         (SCSpec != DeclSpec::SCS_unspecified ||
6915          TSCS != DeclSpec::TSCS_thread_local ||
6916          !DC->isFunctionOrMethod()))
6917       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6918            diag::err_thread_non_global)
6919         << DeclSpec::getSpecifierName(TSCS);
6920     else if (!Context.getTargetInfo().isTLSSupported()) {
6921       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6922         // Postpone error emission until we've collected attributes required to
6923         // figure out whether it's a host or device variable and whether the
6924         // error should be ignored.
6925         EmitTLSUnsupportedError = true;
6926         // We still need to mark the variable as TLS so it shows up in AST with
6927         // proper storage class for other tools to use even if we're not going
6928         // to emit any code for it.
6929         NewVD->setTSCSpec(TSCS);
6930       } else
6931         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6932              diag::err_thread_unsupported);
6933     } else
6934       NewVD->setTSCSpec(TSCS);
6935   }
6936 
6937   switch (D.getDeclSpec().getConstexprSpecifier()) {
6938   case CSK_unspecified:
6939     break;
6940 
6941   case CSK_consteval:
6942     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6943         diag::err_constexpr_wrong_decl_kind)
6944       << D.getDeclSpec().getConstexprSpecifier();
6945     LLVM_FALLTHROUGH;
6946 
6947   case CSK_constexpr:
6948     NewVD->setConstexpr(true);
6949     // C++1z [dcl.spec.constexpr]p1:
6950     //   A static data member declared with the constexpr specifier is
6951     //   implicitly an inline variable.
6952     if (NewVD->isStaticDataMember() &&
6953         (getLangOpts().CPlusPlus17 ||
6954          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6955       NewVD->setImplicitlyInline();
6956     break;
6957 
6958   case CSK_constinit:
6959     if (!NewVD->hasGlobalStorage())
6960       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6961            diag::err_constinit_local_variable);
6962     else
6963       NewVD->addAttr(ConstInitAttr::Create(
6964           Context, D.getDeclSpec().getConstexprSpecLoc(),
6965           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6966     break;
6967   }
6968 
6969   // C99 6.7.4p3
6970   //   An inline definition of a function with external linkage shall
6971   //   not contain a definition of a modifiable object with static or
6972   //   thread storage duration...
6973   // We only apply this when the function is required to be defined
6974   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6975   // that a local variable with thread storage duration still has to
6976   // be marked 'static'.  Also note that it's possible to get these
6977   // semantics in C++ using __attribute__((gnu_inline)).
6978   if (SC == SC_Static && S->getFnParent() != nullptr &&
6979       !NewVD->getType().isConstQualified()) {
6980     FunctionDecl *CurFD = getCurFunctionDecl();
6981     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6982       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6983            diag::warn_static_local_in_extern_inline);
6984       MaybeSuggestAddingStaticToDecl(CurFD);
6985     }
6986   }
6987 
6988   if (D.getDeclSpec().isModulePrivateSpecified()) {
6989     if (IsVariableTemplateSpecialization)
6990       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6991           << (IsPartialSpecialization ? 1 : 0)
6992           << FixItHint::CreateRemoval(
6993                  D.getDeclSpec().getModulePrivateSpecLoc());
6994     else if (IsMemberSpecialization)
6995       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6996         << 2
6997         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6998     else if (NewVD->hasLocalStorage())
6999       Diag(NewVD->getLocation(), diag::err_module_private_local)
7000         << 0 << NewVD->getDeclName()
7001         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7002         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7003     else {
7004       NewVD->setModulePrivate();
7005       if (NewTemplate)
7006         NewTemplate->setModulePrivate();
7007       for (auto *B : Bindings)
7008         B->setModulePrivate();
7009     }
7010   }
7011 
7012   if (getLangOpts().OpenCL) {
7013 
7014     deduceOpenCLAddressSpace(NewVD);
7015 
7016     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7017   }
7018 
7019   // Handle attributes prior to checking for duplicates in MergeVarDecl
7020   ProcessDeclAttributes(S, NewVD, D);
7021 
7022   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7023     if (EmitTLSUnsupportedError &&
7024         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7025          (getLangOpts().OpenMPIsDevice &&
7026           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7027       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7028            diag::err_thread_unsupported);
7029     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7030     // storage [duration]."
7031     if (SC == SC_None && S->getFnParent() != nullptr &&
7032         (NewVD->hasAttr<CUDASharedAttr>() ||
7033          NewVD->hasAttr<CUDAConstantAttr>())) {
7034       NewVD->setStorageClass(SC_Static);
7035     }
7036   }
7037 
7038   // Ensure that dllimport globals without explicit storage class are treated as
7039   // extern. The storage class is set above using parsed attributes. Now we can
7040   // check the VarDecl itself.
7041   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7042          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7043          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7044 
7045   // In auto-retain/release, infer strong retension for variables of
7046   // retainable type.
7047   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7048     NewVD->setInvalidDecl();
7049 
7050   // Handle GNU asm-label extension (encoded as an attribute).
7051   if (Expr *E = (Expr*)D.getAsmLabel()) {
7052     // The parser guarantees this is a string.
7053     StringLiteral *SE = cast<StringLiteral>(E);
7054     StringRef Label = SE->getString();
7055     if (S->getFnParent() != nullptr) {
7056       switch (SC) {
7057       case SC_None:
7058       case SC_Auto:
7059         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7060         break;
7061       case SC_Register:
7062         // Local Named register
7063         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7064             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7065           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7066         break;
7067       case SC_Static:
7068       case SC_Extern:
7069       case SC_PrivateExtern:
7070         break;
7071       }
7072     } else if (SC == SC_Register) {
7073       // Global Named register
7074       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7075         const auto &TI = Context.getTargetInfo();
7076         bool HasSizeMismatch;
7077 
7078         if (!TI.isValidGCCRegisterName(Label))
7079           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7080         else if (!TI.validateGlobalRegisterVariable(Label,
7081                                                     Context.getTypeSize(R),
7082                                                     HasSizeMismatch))
7083           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7084         else if (HasSizeMismatch)
7085           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7086       }
7087 
7088       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7089         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7090         NewVD->setInvalidDecl(true);
7091       }
7092     }
7093 
7094     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7095                                         /*IsLiteralLabel=*/true,
7096                                         SE->getStrTokenLoc(0)));
7097   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7098     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7099       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7100     if (I != ExtnameUndeclaredIdentifiers.end()) {
7101       if (isDeclExternC(NewVD)) {
7102         NewVD->addAttr(I->second);
7103         ExtnameUndeclaredIdentifiers.erase(I);
7104       } else
7105         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7106             << /*Variable*/1 << NewVD;
7107     }
7108   }
7109 
7110   // Find the shadowed declaration before filtering for scope.
7111   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7112                                 ? getShadowedDeclaration(NewVD, Previous)
7113                                 : nullptr;
7114 
7115   // Don't consider existing declarations that are in a different
7116   // scope and are out-of-semantic-context declarations (if the new
7117   // declaration has linkage).
7118   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7119                        D.getCXXScopeSpec().isNotEmpty() ||
7120                        IsMemberSpecialization ||
7121                        IsVariableTemplateSpecialization);
7122 
7123   // Check whether the previous declaration is in the same block scope. This
7124   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7125   if (getLangOpts().CPlusPlus &&
7126       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7127     NewVD->setPreviousDeclInSameBlockScope(
7128         Previous.isSingleResult() && !Previous.isShadowed() &&
7129         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7130 
7131   if (!getLangOpts().CPlusPlus) {
7132     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7133   } else {
7134     // If this is an explicit specialization of a static data member, check it.
7135     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7136         CheckMemberSpecialization(NewVD, Previous))
7137       NewVD->setInvalidDecl();
7138 
7139     // Merge the decl with the existing one if appropriate.
7140     if (!Previous.empty()) {
7141       if (Previous.isSingleResult() &&
7142           isa<FieldDecl>(Previous.getFoundDecl()) &&
7143           D.getCXXScopeSpec().isSet()) {
7144         // The user tried to define a non-static data member
7145         // out-of-line (C++ [dcl.meaning]p1).
7146         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7147           << D.getCXXScopeSpec().getRange();
7148         Previous.clear();
7149         NewVD->setInvalidDecl();
7150       }
7151     } else if (D.getCXXScopeSpec().isSet()) {
7152       // No previous declaration in the qualifying scope.
7153       Diag(D.getIdentifierLoc(), diag::err_no_member)
7154         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7155         << D.getCXXScopeSpec().getRange();
7156       NewVD->setInvalidDecl();
7157     }
7158 
7159     if (!IsVariableTemplateSpecialization)
7160       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7161 
7162     if (NewTemplate) {
7163       VarTemplateDecl *PrevVarTemplate =
7164           NewVD->getPreviousDecl()
7165               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7166               : nullptr;
7167 
7168       // Check the template parameter list of this declaration, possibly
7169       // merging in the template parameter list from the previous variable
7170       // template declaration.
7171       if (CheckTemplateParameterList(
7172               TemplateParams,
7173               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7174                               : nullptr,
7175               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7176                DC->isDependentContext())
7177                   ? TPC_ClassTemplateMember
7178                   : TPC_VarTemplate))
7179         NewVD->setInvalidDecl();
7180 
7181       // If we are providing an explicit specialization of a static variable
7182       // template, make a note of that.
7183       if (PrevVarTemplate &&
7184           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7185         PrevVarTemplate->setMemberSpecialization();
7186     }
7187   }
7188 
7189   // Diagnose shadowed variables iff this isn't a redeclaration.
7190   if (ShadowedDecl && !D.isRedeclaration())
7191     CheckShadow(NewVD, ShadowedDecl, Previous);
7192 
7193   ProcessPragmaWeak(S, NewVD);
7194 
7195   // If this is the first declaration of an extern C variable, update
7196   // the map of such variables.
7197   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7198       isIncompleteDeclExternC(*this, NewVD))
7199     RegisterLocallyScopedExternCDecl(NewVD, S);
7200 
7201   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7202     MangleNumberingContext *MCtx;
7203     Decl *ManglingContextDecl;
7204     std::tie(MCtx, ManglingContextDecl) =
7205         getCurrentMangleNumberContext(NewVD->getDeclContext());
7206     if (MCtx) {
7207       Context.setManglingNumber(
7208           NewVD, MCtx->getManglingNumber(
7209                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7210       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7211     }
7212   }
7213 
7214   // Special handling of variable named 'main'.
7215   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7216       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7217       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7218 
7219     // C++ [basic.start.main]p3
7220     // A program that declares a variable main at global scope is ill-formed.
7221     if (getLangOpts().CPlusPlus)
7222       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7223 
7224     // In C, and external-linkage variable named main results in undefined
7225     // behavior.
7226     else if (NewVD->hasExternalFormalLinkage())
7227       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7228   }
7229 
7230   if (D.isRedeclaration() && !Previous.empty()) {
7231     NamedDecl *Prev = Previous.getRepresentativeDecl();
7232     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7233                                    D.isFunctionDefinition());
7234   }
7235 
7236   if (NewTemplate) {
7237     if (NewVD->isInvalidDecl())
7238       NewTemplate->setInvalidDecl();
7239     ActOnDocumentableDecl(NewTemplate);
7240     return NewTemplate;
7241   }
7242 
7243   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7244     CompleteMemberSpecialization(NewVD, Previous);
7245 
7246   return NewVD;
7247 }
7248 
7249 /// Enum describing the %select options in diag::warn_decl_shadow.
7250 enum ShadowedDeclKind {
7251   SDK_Local,
7252   SDK_Global,
7253   SDK_StaticMember,
7254   SDK_Field,
7255   SDK_Typedef,
7256   SDK_Using
7257 };
7258 
7259 /// Determine what kind of declaration we're shadowing.
7260 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7261                                                 const DeclContext *OldDC) {
7262   if (isa<TypeAliasDecl>(ShadowedDecl))
7263     return SDK_Using;
7264   else if (isa<TypedefDecl>(ShadowedDecl))
7265     return SDK_Typedef;
7266   else if (isa<RecordDecl>(OldDC))
7267     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7268 
7269   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7270 }
7271 
7272 /// Return the location of the capture if the given lambda captures the given
7273 /// variable \p VD, or an invalid source location otherwise.
7274 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7275                                          const VarDecl *VD) {
7276   for (const Capture &Capture : LSI->Captures) {
7277     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7278       return Capture.getLocation();
7279   }
7280   return SourceLocation();
7281 }
7282 
7283 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7284                                      const LookupResult &R) {
7285   // Only diagnose if we're shadowing an unambiguous field or variable.
7286   if (R.getResultKind() != LookupResult::Found)
7287     return false;
7288 
7289   // Return false if warning is ignored.
7290   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7291 }
7292 
7293 /// Return the declaration shadowed by the given variable \p D, or null
7294 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7295 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7296                                         const LookupResult &R) {
7297   if (!shouldWarnIfShadowedDecl(Diags, R))
7298     return nullptr;
7299 
7300   // Don't diagnose declarations at file scope.
7301   if (D->hasGlobalStorage())
7302     return nullptr;
7303 
7304   NamedDecl *ShadowedDecl = R.getFoundDecl();
7305   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7306              ? ShadowedDecl
7307              : nullptr;
7308 }
7309 
7310 /// Return the declaration shadowed by the given typedef \p D, or null
7311 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7312 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7313                                         const LookupResult &R) {
7314   // Don't warn if typedef declaration is part of a class
7315   if (D->getDeclContext()->isRecord())
7316     return nullptr;
7317 
7318   if (!shouldWarnIfShadowedDecl(Diags, R))
7319     return nullptr;
7320 
7321   NamedDecl *ShadowedDecl = R.getFoundDecl();
7322   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7323 }
7324 
7325 /// Diagnose variable or built-in function shadowing.  Implements
7326 /// -Wshadow.
7327 ///
7328 /// This method is called whenever a VarDecl is added to a "useful"
7329 /// scope.
7330 ///
7331 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7332 /// \param R the lookup of the name
7333 ///
7334 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7335                        const LookupResult &R) {
7336   DeclContext *NewDC = D->getDeclContext();
7337 
7338   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7339     // Fields are not shadowed by variables in C++ static methods.
7340     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7341       if (MD->isStatic())
7342         return;
7343 
7344     // Fields shadowed by constructor parameters are a special case. Usually
7345     // the constructor initializes the field with the parameter.
7346     if (isa<CXXConstructorDecl>(NewDC))
7347       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7348         // Remember that this was shadowed so we can either warn about its
7349         // modification or its existence depending on warning settings.
7350         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7351         return;
7352       }
7353   }
7354 
7355   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7356     if (shadowedVar->isExternC()) {
7357       // For shadowing external vars, make sure that we point to the global
7358       // declaration, not a locally scoped extern declaration.
7359       for (auto I : shadowedVar->redecls())
7360         if (I->isFileVarDecl()) {
7361           ShadowedDecl = I;
7362           break;
7363         }
7364     }
7365 
7366   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7367 
7368   unsigned WarningDiag = diag::warn_decl_shadow;
7369   SourceLocation CaptureLoc;
7370   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7371       isa<CXXMethodDecl>(NewDC)) {
7372     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7373       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7374         if (RD->getLambdaCaptureDefault() == LCD_None) {
7375           // Try to avoid warnings for lambdas with an explicit capture list.
7376           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7377           // Warn only when the lambda captures the shadowed decl explicitly.
7378           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7379           if (CaptureLoc.isInvalid())
7380             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7381         } else {
7382           // Remember that this was shadowed so we can avoid the warning if the
7383           // shadowed decl isn't captured and the warning settings allow it.
7384           cast<LambdaScopeInfo>(getCurFunction())
7385               ->ShadowingDecls.push_back(
7386                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7387           return;
7388         }
7389       }
7390 
7391       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7392         // A variable can't shadow a local variable in an enclosing scope, if
7393         // they are separated by a non-capturing declaration context.
7394         for (DeclContext *ParentDC = NewDC;
7395              ParentDC && !ParentDC->Equals(OldDC);
7396              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7397           // Only block literals, captured statements, and lambda expressions
7398           // can capture; other scopes don't.
7399           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7400               !isLambdaCallOperator(ParentDC)) {
7401             return;
7402           }
7403         }
7404       }
7405     }
7406   }
7407 
7408   // Only warn about certain kinds of shadowing for class members.
7409   if (NewDC && NewDC->isRecord()) {
7410     // In particular, don't warn about shadowing non-class members.
7411     if (!OldDC->isRecord())
7412       return;
7413 
7414     // TODO: should we warn about static data members shadowing
7415     // static data members from base classes?
7416 
7417     // TODO: don't diagnose for inaccessible shadowed members.
7418     // This is hard to do perfectly because we might friend the
7419     // shadowing context, but that's just a false negative.
7420   }
7421 
7422 
7423   DeclarationName Name = R.getLookupName();
7424 
7425   // Emit warning and note.
7426   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7427     return;
7428   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7429   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7430   if (!CaptureLoc.isInvalid())
7431     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7432         << Name << /*explicitly*/ 1;
7433   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7434 }
7435 
7436 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7437 /// when these variables are captured by the lambda.
7438 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7439   for (const auto &Shadow : LSI->ShadowingDecls) {
7440     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7441     // Try to avoid the warning when the shadowed decl isn't captured.
7442     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7443     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7444     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7445                                        ? diag::warn_decl_shadow_uncaptured_local
7446                                        : diag::warn_decl_shadow)
7447         << Shadow.VD->getDeclName()
7448         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7449     if (!CaptureLoc.isInvalid())
7450       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7451           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7452     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7453   }
7454 }
7455 
7456 /// Check -Wshadow without the advantage of a previous lookup.
7457 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7458   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7459     return;
7460 
7461   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7462                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7463   LookupName(R, S);
7464   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7465     CheckShadow(D, ShadowedDecl, R);
7466 }
7467 
7468 /// Check if 'E', which is an expression that is about to be modified, refers
7469 /// to a constructor parameter that shadows a field.
7470 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7471   // Quickly ignore expressions that can't be shadowing ctor parameters.
7472   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7473     return;
7474   E = E->IgnoreParenImpCasts();
7475   auto *DRE = dyn_cast<DeclRefExpr>(E);
7476   if (!DRE)
7477     return;
7478   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7479   auto I = ShadowingDecls.find(D);
7480   if (I == ShadowingDecls.end())
7481     return;
7482   const NamedDecl *ShadowedDecl = I->second;
7483   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7484   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7485   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7486   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7487 
7488   // Avoid issuing multiple warnings about the same decl.
7489   ShadowingDecls.erase(I);
7490 }
7491 
7492 /// Check for conflict between this global or extern "C" declaration and
7493 /// previous global or extern "C" declarations. This is only used in C++.
7494 template<typename T>
7495 static bool checkGlobalOrExternCConflict(
7496     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7497   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7498   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7499 
7500   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7501     // The common case: this global doesn't conflict with any extern "C"
7502     // declaration.
7503     return false;
7504   }
7505 
7506   if (Prev) {
7507     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7508       // Both the old and new declarations have C language linkage. This is a
7509       // redeclaration.
7510       Previous.clear();
7511       Previous.addDecl(Prev);
7512       return true;
7513     }
7514 
7515     // This is a global, non-extern "C" declaration, and there is a previous
7516     // non-global extern "C" declaration. Diagnose if this is a variable
7517     // declaration.
7518     if (!isa<VarDecl>(ND))
7519       return false;
7520   } else {
7521     // The declaration is extern "C". Check for any declaration in the
7522     // translation unit which might conflict.
7523     if (IsGlobal) {
7524       // We have already performed the lookup into the translation unit.
7525       IsGlobal = false;
7526       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7527            I != E; ++I) {
7528         if (isa<VarDecl>(*I)) {
7529           Prev = *I;
7530           break;
7531         }
7532       }
7533     } else {
7534       DeclContext::lookup_result R =
7535           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7536       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7537            I != E; ++I) {
7538         if (isa<VarDecl>(*I)) {
7539           Prev = *I;
7540           break;
7541         }
7542         // FIXME: If we have any other entity with this name in global scope,
7543         // the declaration is ill-formed, but that is a defect: it breaks the
7544         // 'stat' hack, for instance. Only variables can have mangled name
7545         // clashes with extern "C" declarations, so only they deserve a
7546         // diagnostic.
7547       }
7548     }
7549 
7550     if (!Prev)
7551       return false;
7552   }
7553 
7554   // Use the first declaration's location to ensure we point at something which
7555   // is lexically inside an extern "C" linkage-spec.
7556   assert(Prev && "should have found a previous declaration to diagnose");
7557   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7558     Prev = FD->getFirstDecl();
7559   else
7560     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7561 
7562   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7563     << IsGlobal << ND;
7564   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7565     << IsGlobal;
7566   return false;
7567 }
7568 
7569 /// Apply special rules for handling extern "C" declarations. Returns \c true
7570 /// if we have found that this is a redeclaration of some prior entity.
7571 ///
7572 /// Per C++ [dcl.link]p6:
7573 ///   Two declarations [for a function or variable] with C language linkage
7574 ///   with the same name that appear in different scopes refer to the same
7575 ///   [entity]. An entity with C language linkage shall not be declared with
7576 ///   the same name as an entity in global scope.
7577 template<typename T>
7578 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7579                                                   LookupResult &Previous) {
7580   if (!S.getLangOpts().CPlusPlus) {
7581     // In C, when declaring a global variable, look for a corresponding 'extern'
7582     // variable declared in function scope. We don't need this in C++, because
7583     // we find local extern decls in the surrounding file-scope DeclContext.
7584     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7585       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7586         Previous.clear();
7587         Previous.addDecl(Prev);
7588         return true;
7589       }
7590     }
7591     return false;
7592   }
7593 
7594   // A declaration in the translation unit can conflict with an extern "C"
7595   // declaration.
7596   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7597     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7598 
7599   // An extern "C" declaration can conflict with a declaration in the
7600   // translation unit or can be a redeclaration of an extern "C" declaration
7601   // in another scope.
7602   if (isIncompleteDeclExternC(S,ND))
7603     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7604 
7605   // Neither global nor extern "C": nothing to do.
7606   return false;
7607 }
7608 
7609 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7610   // If the decl is already known invalid, don't check it.
7611   if (NewVD->isInvalidDecl())
7612     return;
7613 
7614   QualType T = NewVD->getType();
7615 
7616   // Defer checking an 'auto' type until its initializer is attached.
7617   if (T->isUndeducedType())
7618     return;
7619 
7620   if (NewVD->hasAttrs())
7621     CheckAlignasUnderalignment(NewVD);
7622 
7623   if (T->isObjCObjectType()) {
7624     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7625       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7626     T = Context.getObjCObjectPointerType(T);
7627     NewVD->setType(T);
7628   }
7629 
7630   // Emit an error if an address space was applied to decl with local storage.
7631   // This includes arrays of objects with address space qualifiers, but not
7632   // automatic variables that point to other address spaces.
7633   // ISO/IEC TR 18037 S5.1.2
7634   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7635       T.getAddressSpace() != LangAS::Default) {
7636     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7637     NewVD->setInvalidDecl();
7638     return;
7639   }
7640 
7641   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7642   // scope.
7643   if (getLangOpts().OpenCLVersion == 120 &&
7644       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7645       NewVD->isStaticLocal()) {
7646     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7647     NewVD->setInvalidDecl();
7648     return;
7649   }
7650 
7651   if (getLangOpts().OpenCL) {
7652     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7653     if (NewVD->hasAttr<BlocksAttr>()) {
7654       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7655       return;
7656     }
7657 
7658     if (T->isBlockPointerType()) {
7659       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7660       // can't use 'extern' storage class.
7661       if (!T.isConstQualified()) {
7662         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7663             << 0 /*const*/;
7664         NewVD->setInvalidDecl();
7665         return;
7666       }
7667       if (NewVD->hasExternalStorage()) {
7668         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7669         NewVD->setInvalidDecl();
7670         return;
7671       }
7672     }
7673     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7674     // __constant address space.
7675     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7676     // variables inside a function can also be declared in the global
7677     // address space.
7678     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7679     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7680     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7681         NewVD->hasExternalStorage()) {
7682       if (!T->isSamplerT() &&
7683           !(T.getAddressSpace() == LangAS::opencl_constant ||
7684             (T.getAddressSpace() == LangAS::opencl_global &&
7685              (getLangOpts().OpenCLVersion == 200 ||
7686               getLangOpts().OpenCLCPlusPlus)))) {
7687         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7688         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7689           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7690               << Scope << "global or constant";
7691         else
7692           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7693               << Scope << "constant";
7694         NewVD->setInvalidDecl();
7695         return;
7696       }
7697     } else {
7698       if (T.getAddressSpace() == LangAS::opencl_global) {
7699         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7700             << 1 /*is any function*/ << "global";
7701         NewVD->setInvalidDecl();
7702         return;
7703       }
7704       if (T.getAddressSpace() == LangAS::opencl_constant ||
7705           T.getAddressSpace() == LangAS::opencl_local) {
7706         FunctionDecl *FD = getCurFunctionDecl();
7707         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7708         // in functions.
7709         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7710           if (T.getAddressSpace() == LangAS::opencl_constant)
7711             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7712                 << 0 /*non-kernel only*/ << "constant";
7713           else
7714             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7715                 << 0 /*non-kernel only*/ << "local";
7716           NewVD->setInvalidDecl();
7717           return;
7718         }
7719         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7720         // in the outermost scope of a kernel function.
7721         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7722           if (!getCurScope()->isFunctionScope()) {
7723             if (T.getAddressSpace() == LangAS::opencl_constant)
7724               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7725                   << "constant";
7726             else
7727               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7728                   << "local";
7729             NewVD->setInvalidDecl();
7730             return;
7731           }
7732         }
7733       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7734                  // If we are parsing a template we didn't deduce an addr
7735                  // space yet.
7736                  T.getAddressSpace() != LangAS::Default) {
7737         // Do not allow other address spaces on automatic variable.
7738         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7739         NewVD->setInvalidDecl();
7740         return;
7741       }
7742     }
7743   }
7744 
7745   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7746       && !NewVD->hasAttr<BlocksAttr>()) {
7747     if (getLangOpts().getGC() != LangOptions::NonGC)
7748       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7749     else {
7750       assert(!getLangOpts().ObjCAutoRefCount);
7751       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7752     }
7753   }
7754 
7755   bool isVM = T->isVariablyModifiedType();
7756   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7757       NewVD->hasAttr<BlocksAttr>())
7758     setFunctionHasBranchProtectedScope();
7759 
7760   if ((isVM && NewVD->hasLinkage()) ||
7761       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7762     bool SizeIsNegative;
7763     llvm::APSInt Oversized;
7764     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7765         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7766     QualType FixedT;
7767     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7768       FixedT = FixedTInfo->getType();
7769     else if (FixedTInfo) {
7770       // Type and type-as-written are canonically different. We need to fix up
7771       // both types separately.
7772       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7773                                                    Oversized);
7774     }
7775     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7776       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7777       // FIXME: This won't give the correct result for
7778       // int a[10][n];
7779       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7780 
7781       if (NewVD->isFileVarDecl())
7782         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7783         << SizeRange;
7784       else if (NewVD->isStaticLocal())
7785         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7786         << SizeRange;
7787       else
7788         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7789         << SizeRange;
7790       NewVD->setInvalidDecl();
7791       return;
7792     }
7793 
7794     if (!FixedTInfo) {
7795       if (NewVD->isFileVarDecl())
7796         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7797       else
7798         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7799       NewVD->setInvalidDecl();
7800       return;
7801     }
7802 
7803     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7804     NewVD->setType(FixedT);
7805     NewVD->setTypeSourceInfo(FixedTInfo);
7806   }
7807 
7808   if (T->isVoidType()) {
7809     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7810     //                    of objects and functions.
7811     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7812       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7813         << T;
7814       NewVD->setInvalidDecl();
7815       return;
7816     }
7817   }
7818 
7819   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7820     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7821     NewVD->setInvalidDecl();
7822     return;
7823   }
7824 
7825   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7826     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7827     NewVD->setInvalidDecl();
7828     return;
7829   }
7830 
7831   if (NewVD->isConstexpr() && !T->isDependentType() &&
7832       RequireLiteralType(NewVD->getLocation(), T,
7833                          diag::err_constexpr_var_non_literal)) {
7834     NewVD->setInvalidDecl();
7835     return;
7836   }
7837 }
7838 
7839 /// Perform semantic checking on a newly-created variable
7840 /// declaration.
7841 ///
7842 /// This routine performs all of the type-checking required for a
7843 /// variable declaration once it has been built. It is used both to
7844 /// check variables after they have been parsed and their declarators
7845 /// have been translated into a declaration, and to check variables
7846 /// that have been instantiated from a template.
7847 ///
7848 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7849 ///
7850 /// Returns true if the variable declaration is a redeclaration.
7851 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7852   CheckVariableDeclarationType(NewVD);
7853 
7854   // If the decl is already known invalid, don't check it.
7855   if (NewVD->isInvalidDecl())
7856     return false;
7857 
7858   // If we did not find anything by this name, look for a non-visible
7859   // extern "C" declaration with the same name.
7860   if (Previous.empty() &&
7861       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7862     Previous.setShadowed();
7863 
7864   if (!Previous.empty()) {
7865     MergeVarDecl(NewVD, Previous);
7866     return true;
7867   }
7868   return false;
7869 }
7870 
7871 namespace {
7872 struct FindOverriddenMethod {
7873   Sema *S;
7874   CXXMethodDecl *Method;
7875 
7876   /// Member lookup function that determines whether a given C++
7877   /// method overrides a method in a base class, to be used with
7878   /// CXXRecordDecl::lookupInBases().
7879   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7880     RecordDecl *BaseRecord =
7881         Specifier->getType()->castAs<RecordType>()->getDecl();
7882 
7883     DeclarationName Name = Method->getDeclName();
7884 
7885     // FIXME: Do we care about other names here too?
7886     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7887       // We really want to find the base class destructor here.
7888       QualType T = S->Context.getTypeDeclType(BaseRecord);
7889       CanQualType CT = S->Context.getCanonicalType(T);
7890 
7891       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7892     }
7893 
7894     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7895          Path.Decls = Path.Decls.slice(1)) {
7896       NamedDecl *D = Path.Decls.front();
7897       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7898         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7899           return true;
7900       }
7901     }
7902 
7903     return false;
7904   }
7905 };
7906 
7907 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7908 } // end anonymous namespace
7909 
7910 /// Report an error regarding overriding, along with any relevant
7911 /// overridden methods.
7912 ///
7913 /// \param DiagID the primary error to report.
7914 /// \param MD the overriding method.
7915 /// \param OEK which overrides to include as notes.
7916 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7917                             OverrideErrorKind OEK = OEK_All) {
7918   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7919   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7920     // This check (& the OEK parameter) could be replaced by a predicate, but
7921     // without lambdas that would be overkill. This is still nicer than writing
7922     // out the diag loop 3 times.
7923     if ((OEK == OEK_All) ||
7924         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7925         (OEK == OEK_Deleted && O->isDeleted()))
7926       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7927   }
7928 }
7929 
7930 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7931 /// and if so, check that it's a valid override and remember it.
7932 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7933   // Look for methods in base classes that this method might override.
7934   CXXBasePaths Paths;
7935   FindOverriddenMethod FOM;
7936   FOM.Method = MD;
7937   FOM.S = this;
7938   bool hasDeletedOverridenMethods = false;
7939   bool hasNonDeletedOverridenMethods = false;
7940   bool AddedAny = false;
7941   if (DC->lookupInBases(FOM, Paths)) {
7942     for (auto *I : Paths.found_decls()) {
7943       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7944         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7945         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7946             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7947             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7948             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7949           hasDeletedOverridenMethods |= OldMD->isDeleted();
7950           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7951           AddedAny = true;
7952         }
7953       }
7954     }
7955   }
7956 
7957   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7958     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7959   }
7960   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7961     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7962   }
7963 
7964   return AddedAny;
7965 }
7966 
7967 namespace {
7968   // Struct for holding all of the extra arguments needed by
7969   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7970   struct ActOnFDArgs {
7971     Scope *S;
7972     Declarator &D;
7973     MultiTemplateParamsArg TemplateParamLists;
7974     bool AddToScope;
7975   };
7976 } // end anonymous namespace
7977 
7978 namespace {
7979 
7980 // Callback to only accept typo corrections that have a non-zero edit distance.
7981 // Also only accept corrections that have the same parent decl.
7982 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7983  public:
7984   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7985                             CXXRecordDecl *Parent)
7986       : Context(Context), OriginalFD(TypoFD),
7987         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7988 
7989   bool ValidateCandidate(const TypoCorrection &candidate) override {
7990     if (candidate.getEditDistance() == 0)
7991       return false;
7992 
7993     SmallVector<unsigned, 1> MismatchedParams;
7994     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7995                                           CDeclEnd = candidate.end();
7996          CDecl != CDeclEnd; ++CDecl) {
7997       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7998 
7999       if (FD && !FD->hasBody() &&
8000           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8001         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8002           CXXRecordDecl *Parent = MD->getParent();
8003           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8004             return true;
8005         } else if (!ExpectedParent) {
8006           return true;
8007         }
8008       }
8009     }
8010 
8011     return false;
8012   }
8013 
8014   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8015     return std::make_unique<DifferentNameValidatorCCC>(*this);
8016   }
8017 
8018  private:
8019   ASTContext &Context;
8020   FunctionDecl *OriginalFD;
8021   CXXRecordDecl *ExpectedParent;
8022 };
8023 
8024 } // end anonymous namespace
8025 
8026 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8027   TypoCorrectedFunctionDefinitions.insert(F);
8028 }
8029 
8030 /// Generate diagnostics for an invalid function redeclaration.
8031 ///
8032 /// This routine handles generating the diagnostic messages for an invalid
8033 /// function redeclaration, including finding possible similar declarations
8034 /// or performing typo correction if there are no previous declarations with
8035 /// the same name.
8036 ///
8037 /// Returns a NamedDecl iff typo correction was performed and substituting in
8038 /// the new declaration name does not cause new errors.
8039 static NamedDecl *DiagnoseInvalidRedeclaration(
8040     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8041     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8042   DeclarationName Name = NewFD->getDeclName();
8043   DeclContext *NewDC = NewFD->getDeclContext();
8044   SmallVector<unsigned, 1> MismatchedParams;
8045   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8046   TypoCorrection Correction;
8047   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8048   unsigned DiagMsg =
8049     IsLocalFriend ? diag::err_no_matching_local_friend :
8050     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8051     diag::err_member_decl_does_not_match;
8052   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8053                     IsLocalFriend ? Sema::LookupLocalFriendName
8054                                   : Sema::LookupOrdinaryName,
8055                     Sema::ForVisibleRedeclaration);
8056 
8057   NewFD->setInvalidDecl();
8058   if (IsLocalFriend)
8059     SemaRef.LookupName(Prev, S);
8060   else
8061     SemaRef.LookupQualifiedName(Prev, NewDC);
8062   assert(!Prev.isAmbiguous() &&
8063          "Cannot have an ambiguity in previous-declaration lookup");
8064   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8065   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8066                                 MD ? MD->getParent() : nullptr);
8067   if (!Prev.empty()) {
8068     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8069          Func != FuncEnd; ++Func) {
8070       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8071       if (FD &&
8072           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8073         // Add 1 to the index so that 0 can mean the mismatch didn't
8074         // involve a parameter
8075         unsigned ParamNum =
8076             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8077         NearMatches.push_back(std::make_pair(FD, ParamNum));
8078       }
8079     }
8080   // If the qualified name lookup yielded nothing, try typo correction
8081   } else if ((Correction = SemaRef.CorrectTypo(
8082                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8083                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8084                   IsLocalFriend ? nullptr : NewDC))) {
8085     // Set up everything for the call to ActOnFunctionDeclarator
8086     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8087                               ExtraArgs.D.getIdentifierLoc());
8088     Previous.clear();
8089     Previous.setLookupName(Correction.getCorrection());
8090     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8091                                     CDeclEnd = Correction.end();
8092          CDecl != CDeclEnd; ++CDecl) {
8093       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8094       if (FD && !FD->hasBody() &&
8095           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8096         Previous.addDecl(FD);
8097       }
8098     }
8099     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8100 
8101     NamedDecl *Result;
8102     // Retry building the function declaration with the new previous
8103     // declarations, and with errors suppressed.
8104     {
8105       // Trap errors.
8106       Sema::SFINAETrap Trap(SemaRef);
8107 
8108       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8109       // pieces need to verify the typo-corrected C++ declaration and hopefully
8110       // eliminate the need for the parameter pack ExtraArgs.
8111       Result = SemaRef.ActOnFunctionDeclarator(
8112           ExtraArgs.S, ExtraArgs.D,
8113           Correction.getCorrectionDecl()->getDeclContext(),
8114           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8115           ExtraArgs.AddToScope);
8116 
8117       if (Trap.hasErrorOccurred())
8118         Result = nullptr;
8119     }
8120 
8121     if (Result) {
8122       // Determine which correction we picked.
8123       Decl *Canonical = Result->getCanonicalDecl();
8124       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8125            I != E; ++I)
8126         if ((*I)->getCanonicalDecl() == Canonical)
8127           Correction.setCorrectionDecl(*I);
8128 
8129       // Let Sema know about the correction.
8130       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8131       SemaRef.diagnoseTypo(
8132           Correction,
8133           SemaRef.PDiag(IsLocalFriend
8134                           ? diag::err_no_matching_local_friend_suggest
8135                           : diag::err_member_decl_does_not_match_suggest)
8136             << Name << NewDC << IsDefinition);
8137       return Result;
8138     }
8139 
8140     // Pretend the typo correction never occurred
8141     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8142                               ExtraArgs.D.getIdentifierLoc());
8143     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8144     Previous.clear();
8145     Previous.setLookupName(Name);
8146   }
8147 
8148   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8149       << Name << NewDC << IsDefinition << NewFD->getLocation();
8150 
8151   bool NewFDisConst = false;
8152   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8153     NewFDisConst = NewMD->isConst();
8154 
8155   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8156        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8157        NearMatch != NearMatchEnd; ++NearMatch) {
8158     FunctionDecl *FD = NearMatch->first;
8159     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8160     bool FDisConst = MD && MD->isConst();
8161     bool IsMember = MD || !IsLocalFriend;
8162 
8163     // FIXME: These notes are poorly worded for the local friend case.
8164     if (unsigned Idx = NearMatch->second) {
8165       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8166       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8167       if (Loc.isInvalid()) Loc = FD->getLocation();
8168       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8169                                  : diag::note_local_decl_close_param_match)
8170         << Idx << FDParam->getType()
8171         << NewFD->getParamDecl(Idx - 1)->getType();
8172     } else if (FDisConst != NewFDisConst) {
8173       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8174           << NewFDisConst << FD->getSourceRange().getEnd();
8175     } else
8176       SemaRef.Diag(FD->getLocation(),
8177                    IsMember ? diag::note_member_def_close_match
8178                             : diag::note_local_decl_close_match);
8179   }
8180   return nullptr;
8181 }
8182 
8183 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8184   switch (D.getDeclSpec().getStorageClassSpec()) {
8185   default: llvm_unreachable("Unknown storage class!");
8186   case DeclSpec::SCS_auto:
8187   case DeclSpec::SCS_register:
8188   case DeclSpec::SCS_mutable:
8189     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8190                  diag::err_typecheck_sclass_func);
8191     D.getMutableDeclSpec().ClearStorageClassSpecs();
8192     D.setInvalidType();
8193     break;
8194   case DeclSpec::SCS_unspecified: break;
8195   case DeclSpec::SCS_extern:
8196     if (D.getDeclSpec().isExternInLinkageSpec())
8197       return SC_None;
8198     return SC_Extern;
8199   case DeclSpec::SCS_static: {
8200     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8201       // C99 6.7.1p5:
8202       //   The declaration of an identifier for a function that has
8203       //   block scope shall have no explicit storage-class specifier
8204       //   other than extern
8205       // See also (C++ [dcl.stc]p4).
8206       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8207                    diag::err_static_block_func);
8208       break;
8209     } else
8210       return SC_Static;
8211   }
8212   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8213   }
8214 
8215   // No explicit storage class has already been returned
8216   return SC_None;
8217 }
8218 
8219 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8220                                            DeclContext *DC, QualType &R,
8221                                            TypeSourceInfo *TInfo,
8222                                            StorageClass SC,
8223                                            bool &IsVirtualOkay) {
8224   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8225   DeclarationName Name = NameInfo.getName();
8226 
8227   FunctionDecl *NewFD = nullptr;
8228   bool isInline = D.getDeclSpec().isInlineSpecified();
8229 
8230   if (!SemaRef.getLangOpts().CPlusPlus) {
8231     // Determine whether the function was written with a
8232     // prototype. This true when:
8233     //   - there is a prototype in the declarator, or
8234     //   - the type R of the function is some kind of typedef or other non-
8235     //     attributed reference to a type name (which eventually refers to a
8236     //     function type).
8237     bool HasPrototype =
8238       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8239       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8240 
8241     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8242                                  R, TInfo, SC, isInline, HasPrototype,
8243                                  CSK_unspecified);
8244     if (D.isInvalidType())
8245       NewFD->setInvalidDecl();
8246 
8247     return NewFD;
8248   }
8249 
8250   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8251 
8252   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8253   if (ConstexprKind == CSK_constinit) {
8254     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8255                  diag::err_constexpr_wrong_decl_kind)
8256         << ConstexprKind;
8257     ConstexprKind = CSK_unspecified;
8258     D.getMutableDeclSpec().ClearConstexprSpec();
8259   }
8260 
8261   // Check that the return type is not an abstract class type.
8262   // For record types, this is done by the AbstractClassUsageDiagnoser once
8263   // the class has been completely parsed.
8264   if (!DC->isRecord() &&
8265       SemaRef.RequireNonAbstractType(
8266           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8267           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8268     D.setInvalidType();
8269 
8270   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8271     // This is a C++ constructor declaration.
8272     assert(DC->isRecord() &&
8273            "Constructors can only be declared in a member context");
8274 
8275     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8276     return CXXConstructorDecl::Create(
8277         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8278         TInfo, ExplicitSpecifier, isInline,
8279         /*isImplicitlyDeclared=*/false, ConstexprKind);
8280 
8281   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8282     // This is a C++ destructor declaration.
8283     if (DC->isRecord()) {
8284       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8285       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8286       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8287           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8288           isInline,
8289           /*isImplicitlyDeclared=*/false, ConstexprKind);
8290 
8291       // If the destructor needs an implicit exception specification, set it
8292       // now. FIXME: It'd be nice to be able to create the right type to start
8293       // with, but the type needs to reference the destructor declaration.
8294       if (SemaRef.getLangOpts().CPlusPlus11)
8295         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8296 
8297       IsVirtualOkay = true;
8298       return NewDD;
8299 
8300     } else {
8301       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8302       D.setInvalidType();
8303 
8304       // Create a FunctionDecl to satisfy the function definition parsing
8305       // code path.
8306       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8307                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8308                                   isInline,
8309                                   /*hasPrototype=*/true, ConstexprKind);
8310     }
8311 
8312   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8313     if (!DC->isRecord()) {
8314       SemaRef.Diag(D.getIdentifierLoc(),
8315            diag::err_conv_function_not_member);
8316       return nullptr;
8317     }
8318 
8319     SemaRef.CheckConversionDeclarator(D, R, SC);
8320     if (D.isInvalidType())
8321       return nullptr;
8322 
8323     IsVirtualOkay = true;
8324     return CXXConversionDecl::Create(
8325         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8326         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8327 
8328   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8329     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8330 
8331     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8332                                          ExplicitSpecifier, NameInfo, R, TInfo,
8333                                          D.getEndLoc());
8334   } else if (DC->isRecord()) {
8335     // If the name of the function is the same as the name of the record,
8336     // then this must be an invalid constructor that has a return type.
8337     // (The parser checks for a return type and makes the declarator a
8338     // constructor if it has no return type).
8339     if (Name.getAsIdentifierInfo() &&
8340         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8341       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8342         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8343         << SourceRange(D.getIdentifierLoc());
8344       return nullptr;
8345     }
8346 
8347     // This is a C++ method declaration.
8348     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8349         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8350         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8351     IsVirtualOkay = !Ret->isStatic();
8352     return Ret;
8353   } else {
8354     bool isFriend =
8355         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8356     if (!isFriend && SemaRef.CurContext->isRecord())
8357       return nullptr;
8358 
8359     // Determine whether the function was written with a
8360     // prototype. This true when:
8361     //   - we're in C++ (where every function has a prototype),
8362     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8363                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8364                                 ConstexprKind);
8365   }
8366 }
8367 
8368 enum OpenCLParamType {
8369   ValidKernelParam,
8370   PtrPtrKernelParam,
8371   PtrKernelParam,
8372   InvalidAddrSpacePtrKernelParam,
8373   InvalidKernelParam,
8374   RecordKernelParam
8375 };
8376 
8377 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8378   // Size dependent types are just typedefs to normal integer types
8379   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8380   // integers other than by their names.
8381   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8382 
8383   // Remove typedefs one by one until we reach a typedef
8384   // for a size dependent type.
8385   QualType DesugaredTy = Ty;
8386   do {
8387     ArrayRef<StringRef> Names(SizeTypeNames);
8388     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8389     if (Names.end() != Match)
8390       return true;
8391 
8392     Ty = DesugaredTy;
8393     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8394   } while (DesugaredTy != Ty);
8395 
8396   return false;
8397 }
8398 
8399 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8400   if (PT->isPointerType()) {
8401     QualType PointeeType = PT->getPointeeType();
8402     if (PointeeType->isPointerType())
8403       return PtrPtrKernelParam;
8404     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8405         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8406         PointeeType.getAddressSpace() == LangAS::Default)
8407       return InvalidAddrSpacePtrKernelParam;
8408     return PtrKernelParam;
8409   }
8410 
8411   // OpenCL v1.2 s6.9.k:
8412   // Arguments to kernel functions in a program cannot be declared with the
8413   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8414   // uintptr_t or a struct and/or union that contain fields declared to be one
8415   // of these built-in scalar types.
8416   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8417     return InvalidKernelParam;
8418 
8419   if (PT->isImageType())
8420     return PtrKernelParam;
8421 
8422   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8423     return InvalidKernelParam;
8424 
8425   // OpenCL extension spec v1.2 s9.5:
8426   // This extension adds support for half scalar and vector types as built-in
8427   // types that can be used for arithmetic operations, conversions etc.
8428   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8429     return InvalidKernelParam;
8430 
8431   if (PT->isRecordType())
8432     return RecordKernelParam;
8433 
8434   // Look into an array argument to check if it has a forbidden type.
8435   if (PT->isArrayType()) {
8436     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8437     // Call ourself to check an underlying type of an array. Since the
8438     // getPointeeOrArrayElementType returns an innermost type which is not an
8439     // array, this recursive call only happens once.
8440     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8441   }
8442 
8443   return ValidKernelParam;
8444 }
8445 
8446 static void checkIsValidOpenCLKernelParameter(
8447   Sema &S,
8448   Declarator &D,
8449   ParmVarDecl *Param,
8450   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8451   QualType PT = Param->getType();
8452 
8453   // Cache the valid types we encounter to avoid rechecking structs that are
8454   // used again
8455   if (ValidTypes.count(PT.getTypePtr()))
8456     return;
8457 
8458   switch (getOpenCLKernelParameterType(S, PT)) {
8459   case PtrPtrKernelParam:
8460     // OpenCL v1.2 s6.9.a:
8461     // A kernel function argument cannot be declared as a
8462     // pointer to a pointer type.
8463     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8464     D.setInvalidType();
8465     return;
8466 
8467   case InvalidAddrSpacePtrKernelParam:
8468     // OpenCL v1.0 s6.5:
8469     // __kernel function arguments declared to be a pointer of a type can point
8470     // to one of the following address spaces only : __global, __local or
8471     // __constant.
8472     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8473     D.setInvalidType();
8474     return;
8475 
8476     // OpenCL v1.2 s6.9.k:
8477     // Arguments to kernel functions in a program cannot be declared with the
8478     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8479     // uintptr_t or a struct and/or union that contain fields declared to be
8480     // one of these built-in scalar types.
8481 
8482   case InvalidKernelParam:
8483     // OpenCL v1.2 s6.8 n:
8484     // A kernel function argument cannot be declared
8485     // of event_t type.
8486     // Do not diagnose half type since it is diagnosed as invalid argument
8487     // type for any function elsewhere.
8488     if (!PT->isHalfType()) {
8489       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8490 
8491       // Explain what typedefs are involved.
8492       const TypedefType *Typedef = nullptr;
8493       while ((Typedef = PT->getAs<TypedefType>())) {
8494         SourceLocation Loc = Typedef->getDecl()->getLocation();
8495         // SourceLocation may be invalid for a built-in type.
8496         if (Loc.isValid())
8497           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8498         PT = Typedef->desugar();
8499       }
8500     }
8501 
8502     D.setInvalidType();
8503     return;
8504 
8505   case PtrKernelParam:
8506   case ValidKernelParam:
8507     ValidTypes.insert(PT.getTypePtr());
8508     return;
8509 
8510   case RecordKernelParam:
8511     break;
8512   }
8513 
8514   // Track nested structs we will inspect
8515   SmallVector<const Decl *, 4> VisitStack;
8516 
8517   // Track where we are in the nested structs. Items will migrate from
8518   // VisitStack to HistoryStack as we do the DFS for bad field.
8519   SmallVector<const FieldDecl *, 4> HistoryStack;
8520   HistoryStack.push_back(nullptr);
8521 
8522   // At this point we already handled everything except of a RecordType or
8523   // an ArrayType of a RecordType.
8524   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8525   const RecordType *RecTy =
8526       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8527   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8528 
8529   VisitStack.push_back(RecTy->getDecl());
8530   assert(VisitStack.back() && "First decl null?");
8531 
8532   do {
8533     const Decl *Next = VisitStack.pop_back_val();
8534     if (!Next) {
8535       assert(!HistoryStack.empty());
8536       // Found a marker, we have gone up a level
8537       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8538         ValidTypes.insert(Hist->getType().getTypePtr());
8539 
8540       continue;
8541     }
8542 
8543     // Adds everything except the original parameter declaration (which is not a
8544     // field itself) to the history stack.
8545     const RecordDecl *RD;
8546     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8547       HistoryStack.push_back(Field);
8548 
8549       QualType FieldTy = Field->getType();
8550       // Other field types (known to be valid or invalid) are handled while we
8551       // walk around RecordDecl::fields().
8552       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8553              "Unexpected type.");
8554       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8555 
8556       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8557     } else {
8558       RD = cast<RecordDecl>(Next);
8559     }
8560 
8561     // Add a null marker so we know when we've gone back up a level
8562     VisitStack.push_back(nullptr);
8563 
8564     for (const auto *FD : RD->fields()) {
8565       QualType QT = FD->getType();
8566 
8567       if (ValidTypes.count(QT.getTypePtr()))
8568         continue;
8569 
8570       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8571       if (ParamType == ValidKernelParam)
8572         continue;
8573 
8574       if (ParamType == RecordKernelParam) {
8575         VisitStack.push_back(FD);
8576         continue;
8577       }
8578 
8579       // OpenCL v1.2 s6.9.p:
8580       // Arguments to kernel functions that are declared to be a struct or union
8581       // do not allow OpenCL objects to be passed as elements of the struct or
8582       // union.
8583       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8584           ParamType == InvalidAddrSpacePtrKernelParam) {
8585         S.Diag(Param->getLocation(),
8586                diag::err_record_with_pointers_kernel_param)
8587           << PT->isUnionType()
8588           << PT;
8589       } else {
8590         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8591       }
8592 
8593       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8594           << OrigRecDecl->getDeclName();
8595 
8596       // We have an error, now let's go back up through history and show where
8597       // the offending field came from
8598       for (ArrayRef<const FieldDecl *>::const_iterator
8599                I = HistoryStack.begin() + 1,
8600                E = HistoryStack.end();
8601            I != E; ++I) {
8602         const FieldDecl *OuterField = *I;
8603         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8604           << OuterField->getType();
8605       }
8606 
8607       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8608         << QT->isPointerType()
8609         << QT;
8610       D.setInvalidType();
8611       return;
8612     }
8613   } while (!VisitStack.empty());
8614 }
8615 
8616 /// Find the DeclContext in which a tag is implicitly declared if we see an
8617 /// elaborated type specifier in the specified context, and lookup finds
8618 /// nothing.
8619 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8620   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8621     DC = DC->getParent();
8622   return DC;
8623 }
8624 
8625 /// Find the Scope in which a tag is implicitly declared if we see an
8626 /// elaborated type specifier in the specified context, and lookup finds
8627 /// nothing.
8628 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8629   while (S->isClassScope() ||
8630          (LangOpts.CPlusPlus &&
8631           S->isFunctionPrototypeScope()) ||
8632          ((S->getFlags() & Scope::DeclScope) == 0) ||
8633          (S->getEntity() && S->getEntity()->isTransparentContext()))
8634     S = S->getParent();
8635   return S;
8636 }
8637 
8638 NamedDecl*
8639 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8640                               TypeSourceInfo *TInfo, LookupResult &Previous,
8641                               MultiTemplateParamsArg TemplateParamLists,
8642                               bool &AddToScope) {
8643   QualType R = TInfo->getType();
8644 
8645   assert(R->isFunctionType());
8646 
8647   // TODO: consider using NameInfo for diagnostic.
8648   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8649   DeclarationName Name = NameInfo.getName();
8650   StorageClass SC = getFunctionStorageClass(*this, D);
8651 
8652   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8653     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8654          diag::err_invalid_thread)
8655       << DeclSpec::getSpecifierName(TSCS);
8656 
8657   if (D.isFirstDeclarationOfMember())
8658     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8659                            D.getIdentifierLoc());
8660 
8661   bool isFriend = false;
8662   FunctionTemplateDecl *FunctionTemplate = nullptr;
8663   bool isMemberSpecialization = false;
8664   bool isFunctionTemplateSpecialization = false;
8665 
8666   bool isDependentClassScopeExplicitSpecialization = false;
8667   bool HasExplicitTemplateArgs = false;
8668   TemplateArgumentListInfo TemplateArgs;
8669 
8670   bool isVirtualOkay = false;
8671 
8672   DeclContext *OriginalDC = DC;
8673   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8674 
8675   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8676                                               isVirtualOkay);
8677   if (!NewFD) return nullptr;
8678 
8679   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8680     NewFD->setTopLevelDeclInObjCContainer();
8681 
8682   // Set the lexical context. If this is a function-scope declaration, or has a
8683   // C++ scope specifier, or is the object of a friend declaration, the lexical
8684   // context will be different from the semantic context.
8685   NewFD->setLexicalDeclContext(CurContext);
8686 
8687   if (IsLocalExternDecl)
8688     NewFD->setLocalExternDecl();
8689 
8690   if (getLangOpts().CPlusPlus) {
8691     bool isInline = D.getDeclSpec().isInlineSpecified();
8692     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8693     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8694     isFriend = D.getDeclSpec().isFriendSpecified();
8695     if (isFriend && !isInline && D.isFunctionDefinition()) {
8696       // C++ [class.friend]p5
8697       //   A function can be defined in a friend declaration of a
8698       //   class . . . . Such a function is implicitly inline.
8699       NewFD->setImplicitlyInline();
8700     }
8701 
8702     // If this is a method defined in an __interface, and is not a constructor
8703     // or an overloaded operator, then set the pure flag (isVirtual will already
8704     // return true).
8705     if (const CXXRecordDecl *Parent =
8706           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8707       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8708         NewFD->setPure(true);
8709 
8710       // C++ [class.union]p2
8711       //   A union can have member functions, but not virtual functions.
8712       if (isVirtual && Parent->isUnion())
8713         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8714     }
8715 
8716     SetNestedNameSpecifier(*this, NewFD, D);
8717     isMemberSpecialization = false;
8718     isFunctionTemplateSpecialization = false;
8719     if (D.isInvalidType())
8720       NewFD->setInvalidDecl();
8721 
8722     // Match up the template parameter lists with the scope specifier, then
8723     // determine whether we have a template or a template specialization.
8724     bool Invalid = false;
8725     if (TemplateParameterList *TemplateParams =
8726             MatchTemplateParametersToScopeSpecifier(
8727                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8728                 D.getCXXScopeSpec(),
8729                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8730                     ? D.getName().TemplateId
8731                     : nullptr,
8732                 TemplateParamLists, isFriend, isMemberSpecialization,
8733                 Invalid)) {
8734       if (TemplateParams->size() > 0) {
8735         // This is a function template
8736 
8737         // Check that we can declare a template here.
8738         if (CheckTemplateDeclScope(S, TemplateParams))
8739           NewFD->setInvalidDecl();
8740 
8741         // A destructor cannot be a template.
8742         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8743           Diag(NewFD->getLocation(), diag::err_destructor_template);
8744           NewFD->setInvalidDecl();
8745         }
8746 
8747         // If we're adding a template to a dependent context, we may need to
8748         // rebuilding some of the types used within the template parameter list,
8749         // now that we know what the current instantiation is.
8750         if (DC->isDependentContext()) {
8751           ContextRAII SavedContext(*this, DC);
8752           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8753             Invalid = true;
8754         }
8755 
8756         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8757                                                         NewFD->getLocation(),
8758                                                         Name, TemplateParams,
8759                                                         NewFD);
8760         FunctionTemplate->setLexicalDeclContext(CurContext);
8761         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8762 
8763         // For source fidelity, store the other template param lists.
8764         if (TemplateParamLists.size() > 1) {
8765           NewFD->setTemplateParameterListsInfo(Context,
8766                                                TemplateParamLists.drop_back(1));
8767         }
8768       } else {
8769         // This is a function template specialization.
8770         isFunctionTemplateSpecialization = true;
8771         // For source fidelity, store all the template param lists.
8772         if (TemplateParamLists.size() > 0)
8773           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8774 
8775         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8776         if (isFriend) {
8777           // We want to remove the "template<>", found here.
8778           SourceRange RemoveRange = TemplateParams->getSourceRange();
8779 
8780           // If we remove the template<> and the name is not a
8781           // template-id, we're actually silently creating a problem:
8782           // the friend declaration will refer to an untemplated decl,
8783           // and clearly the user wants a template specialization.  So
8784           // we need to insert '<>' after the name.
8785           SourceLocation InsertLoc;
8786           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8787             InsertLoc = D.getName().getSourceRange().getEnd();
8788             InsertLoc = getLocForEndOfToken(InsertLoc);
8789           }
8790 
8791           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8792             << Name << RemoveRange
8793             << FixItHint::CreateRemoval(RemoveRange)
8794             << FixItHint::CreateInsertion(InsertLoc, "<>");
8795         }
8796       }
8797     } else {
8798       // All template param lists were matched against the scope specifier:
8799       // this is NOT (an explicit specialization of) a template.
8800       if (TemplateParamLists.size() > 0)
8801         // For source fidelity, store all the template param lists.
8802         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8803     }
8804 
8805     if (Invalid) {
8806       NewFD->setInvalidDecl();
8807       if (FunctionTemplate)
8808         FunctionTemplate->setInvalidDecl();
8809     }
8810 
8811     // C++ [dcl.fct.spec]p5:
8812     //   The virtual specifier shall only be used in declarations of
8813     //   nonstatic class member functions that appear within a
8814     //   member-specification of a class declaration; see 10.3.
8815     //
8816     if (isVirtual && !NewFD->isInvalidDecl()) {
8817       if (!isVirtualOkay) {
8818         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8819              diag::err_virtual_non_function);
8820       } else if (!CurContext->isRecord()) {
8821         // 'virtual' was specified outside of the class.
8822         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8823              diag::err_virtual_out_of_class)
8824           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8825       } else if (NewFD->getDescribedFunctionTemplate()) {
8826         // C++ [temp.mem]p3:
8827         //  A member function template shall not be virtual.
8828         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8829              diag::err_virtual_member_function_template)
8830           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8831       } else {
8832         // Okay: Add virtual to the method.
8833         NewFD->setVirtualAsWritten(true);
8834       }
8835 
8836       if (getLangOpts().CPlusPlus14 &&
8837           NewFD->getReturnType()->isUndeducedType())
8838         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8839     }
8840 
8841     if (getLangOpts().CPlusPlus14 &&
8842         (NewFD->isDependentContext() ||
8843          (isFriend && CurContext->isDependentContext())) &&
8844         NewFD->getReturnType()->isUndeducedType()) {
8845       // If the function template is referenced directly (for instance, as a
8846       // member of the current instantiation), pretend it has a dependent type.
8847       // This is not really justified by the standard, but is the only sane
8848       // thing to do.
8849       // FIXME: For a friend function, we have not marked the function as being
8850       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8851       const FunctionProtoType *FPT =
8852           NewFD->getType()->castAs<FunctionProtoType>();
8853       QualType Result =
8854           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8855       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8856                                              FPT->getExtProtoInfo()));
8857     }
8858 
8859     // C++ [dcl.fct.spec]p3:
8860     //  The inline specifier shall not appear on a block scope function
8861     //  declaration.
8862     if (isInline && !NewFD->isInvalidDecl()) {
8863       if (CurContext->isFunctionOrMethod()) {
8864         // 'inline' is not allowed on block scope function declaration.
8865         Diag(D.getDeclSpec().getInlineSpecLoc(),
8866              diag::err_inline_declaration_block_scope) << Name
8867           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8868       }
8869     }
8870 
8871     // C++ [dcl.fct.spec]p6:
8872     //  The explicit specifier shall be used only in the declaration of a
8873     //  constructor or conversion function within its class definition;
8874     //  see 12.3.1 and 12.3.2.
8875     if (hasExplicit && !NewFD->isInvalidDecl() &&
8876         !isa<CXXDeductionGuideDecl>(NewFD)) {
8877       if (!CurContext->isRecord()) {
8878         // 'explicit' was specified outside of the class.
8879         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8880              diag::err_explicit_out_of_class)
8881             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8882       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8883                  !isa<CXXConversionDecl>(NewFD)) {
8884         // 'explicit' was specified on a function that wasn't a constructor
8885         // or conversion function.
8886         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8887              diag::err_explicit_non_ctor_or_conv_function)
8888             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8889       }
8890     }
8891 
8892     if (ConstexprSpecKind ConstexprKind =
8893             D.getDeclSpec().getConstexprSpecifier()) {
8894       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8895       // are implicitly inline.
8896       NewFD->setImplicitlyInline();
8897 
8898       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8899       // be either constructors or to return a literal type. Therefore,
8900       // destructors cannot be declared constexpr.
8901       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8902         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8903             << ConstexprKind;
8904       }
8905     }
8906 
8907     // If __module_private__ was specified, mark the function accordingly.
8908     if (D.getDeclSpec().isModulePrivateSpecified()) {
8909       if (isFunctionTemplateSpecialization) {
8910         SourceLocation ModulePrivateLoc
8911           = D.getDeclSpec().getModulePrivateSpecLoc();
8912         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8913           << 0
8914           << FixItHint::CreateRemoval(ModulePrivateLoc);
8915       } else {
8916         NewFD->setModulePrivate();
8917         if (FunctionTemplate)
8918           FunctionTemplate->setModulePrivate();
8919       }
8920     }
8921 
8922     if (isFriend) {
8923       if (FunctionTemplate) {
8924         FunctionTemplate->setObjectOfFriendDecl();
8925         FunctionTemplate->setAccess(AS_public);
8926       }
8927       NewFD->setObjectOfFriendDecl();
8928       NewFD->setAccess(AS_public);
8929     }
8930 
8931     // If a function is defined as defaulted or deleted, mark it as such now.
8932     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8933     // definition kind to FDK_Definition.
8934     switch (D.getFunctionDefinitionKind()) {
8935       case FDK_Declaration:
8936       case FDK_Definition:
8937         break;
8938 
8939       case FDK_Defaulted:
8940         NewFD->setDefaulted();
8941         break;
8942 
8943       case FDK_Deleted:
8944         NewFD->setDeletedAsWritten();
8945         break;
8946     }
8947 
8948     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8949         D.isFunctionDefinition()) {
8950       // C++ [class.mfct]p2:
8951       //   A member function may be defined (8.4) in its class definition, in
8952       //   which case it is an inline member function (7.1.2)
8953       NewFD->setImplicitlyInline();
8954     }
8955 
8956     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8957         !CurContext->isRecord()) {
8958       // C++ [class.static]p1:
8959       //   A data or function member of a class may be declared static
8960       //   in a class definition, in which case it is a static member of
8961       //   the class.
8962 
8963       // Complain about the 'static' specifier if it's on an out-of-line
8964       // member function definition.
8965 
8966       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8967       // member function template declaration and class member template
8968       // declaration (MSVC versions before 2015), warn about this.
8969       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8970            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8971              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8972            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8973            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8974         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8975     }
8976 
8977     // C++11 [except.spec]p15:
8978     //   A deallocation function with no exception-specification is treated
8979     //   as if it were specified with noexcept(true).
8980     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8981     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8982          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8983         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8984       NewFD->setType(Context.getFunctionType(
8985           FPT->getReturnType(), FPT->getParamTypes(),
8986           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8987   }
8988 
8989   // Filter out previous declarations that don't match the scope.
8990   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8991                        D.getCXXScopeSpec().isNotEmpty() ||
8992                        isMemberSpecialization ||
8993                        isFunctionTemplateSpecialization);
8994 
8995   // Handle GNU asm-label extension (encoded as an attribute).
8996   if (Expr *E = (Expr*) D.getAsmLabel()) {
8997     // The parser guarantees this is a string.
8998     StringLiteral *SE = cast<StringLiteral>(E);
8999     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9000                                         /*IsLiteralLabel=*/true,
9001                                         SE->getStrTokenLoc(0)));
9002   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9003     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9004       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9005     if (I != ExtnameUndeclaredIdentifiers.end()) {
9006       if (isDeclExternC(NewFD)) {
9007         NewFD->addAttr(I->second);
9008         ExtnameUndeclaredIdentifiers.erase(I);
9009       } else
9010         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9011             << /*Variable*/0 << NewFD;
9012     }
9013   }
9014 
9015   // Copy the parameter declarations from the declarator D to the function
9016   // declaration NewFD, if they are available.  First scavenge them into Params.
9017   SmallVector<ParmVarDecl*, 16> Params;
9018   unsigned FTIIdx;
9019   if (D.isFunctionDeclarator(FTIIdx)) {
9020     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9021 
9022     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9023     // function that takes no arguments, not a function that takes a
9024     // single void argument.
9025     // We let through "const void" here because Sema::GetTypeForDeclarator
9026     // already checks for that case.
9027     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9028       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9029         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9030         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9031         Param->setDeclContext(NewFD);
9032         Params.push_back(Param);
9033 
9034         if (Param->isInvalidDecl())
9035           NewFD->setInvalidDecl();
9036       }
9037     }
9038 
9039     if (!getLangOpts().CPlusPlus) {
9040       // In C, find all the tag declarations from the prototype and move them
9041       // into the function DeclContext. Remove them from the surrounding tag
9042       // injection context of the function, which is typically but not always
9043       // the TU.
9044       DeclContext *PrototypeTagContext =
9045           getTagInjectionContext(NewFD->getLexicalDeclContext());
9046       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9047         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9048 
9049         // We don't want to reparent enumerators. Look at their parent enum
9050         // instead.
9051         if (!TD) {
9052           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9053             TD = cast<EnumDecl>(ECD->getDeclContext());
9054         }
9055         if (!TD)
9056           continue;
9057         DeclContext *TagDC = TD->getLexicalDeclContext();
9058         if (!TagDC->containsDecl(TD))
9059           continue;
9060         TagDC->removeDecl(TD);
9061         TD->setDeclContext(NewFD);
9062         NewFD->addDecl(TD);
9063 
9064         // Preserve the lexical DeclContext if it is not the surrounding tag
9065         // injection context of the FD. In this example, the semantic context of
9066         // E will be f and the lexical context will be S, while both the
9067         // semantic and lexical contexts of S will be f:
9068         //   void f(struct S { enum E { a } f; } s);
9069         if (TagDC != PrototypeTagContext)
9070           TD->setLexicalDeclContext(TagDC);
9071       }
9072     }
9073   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9074     // When we're declaring a function with a typedef, typeof, etc as in the
9075     // following example, we'll need to synthesize (unnamed)
9076     // parameters for use in the declaration.
9077     //
9078     // @code
9079     // typedef void fn(int);
9080     // fn f;
9081     // @endcode
9082 
9083     // Synthesize a parameter for each argument type.
9084     for (const auto &AI : FT->param_types()) {
9085       ParmVarDecl *Param =
9086           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9087       Param->setScopeInfo(0, Params.size());
9088       Params.push_back(Param);
9089     }
9090   } else {
9091     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9092            "Should not need args for typedef of non-prototype fn");
9093   }
9094 
9095   // Finally, we know we have the right number of parameters, install them.
9096   NewFD->setParams(Params);
9097 
9098   if (D.getDeclSpec().isNoreturnSpecified())
9099     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9100                                            D.getDeclSpec().getNoreturnSpecLoc(),
9101                                            AttributeCommonInfo::AS_Keyword));
9102 
9103   // Functions returning a variably modified type violate C99 6.7.5.2p2
9104   // because all functions have linkage.
9105   if (!NewFD->isInvalidDecl() &&
9106       NewFD->getReturnType()->isVariablyModifiedType()) {
9107     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9108     NewFD->setInvalidDecl();
9109   }
9110 
9111   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9112   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9113       !NewFD->hasAttr<SectionAttr>())
9114     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9115         Context, PragmaClangTextSection.SectionName,
9116         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9117 
9118   // Apply an implicit SectionAttr if #pragma code_seg is active.
9119   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9120       !NewFD->hasAttr<SectionAttr>()) {
9121     NewFD->addAttr(SectionAttr::CreateImplicit(
9122         Context, CodeSegStack.CurrentValue->getString(),
9123         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9124         SectionAttr::Declspec_allocate));
9125     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9126                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9127                          ASTContext::PSF_Read,
9128                      NewFD))
9129       NewFD->dropAttr<SectionAttr>();
9130   }
9131 
9132   // Apply an implicit CodeSegAttr from class declspec or
9133   // apply an implicit SectionAttr from #pragma code_seg if active.
9134   if (!NewFD->hasAttr<CodeSegAttr>()) {
9135     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9136                                                                  D.isFunctionDefinition())) {
9137       NewFD->addAttr(SAttr);
9138     }
9139   }
9140 
9141   // Handle attributes.
9142   ProcessDeclAttributes(S, NewFD, D);
9143 
9144   if (getLangOpts().OpenCL) {
9145     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9146     // type declaration will generate a compilation error.
9147     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9148     if (AddressSpace != LangAS::Default) {
9149       Diag(NewFD->getLocation(),
9150            diag::err_opencl_return_value_with_address_space);
9151       NewFD->setInvalidDecl();
9152     }
9153   }
9154 
9155   if (!getLangOpts().CPlusPlus) {
9156     // Perform semantic checking on the function declaration.
9157     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9158       CheckMain(NewFD, D.getDeclSpec());
9159 
9160     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9161       CheckMSVCRTEntryPoint(NewFD);
9162 
9163     if (!NewFD->isInvalidDecl())
9164       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9165                                                   isMemberSpecialization));
9166     else if (!Previous.empty())
9167       // Recover gracefully from an invalid redeclaration.
9168       D.setRedeclaration(true);
9169     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9170             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9171            "previous declaration set still overloaded");
9172 
9173     // Diagnose no-prototype function declarations with calling conventions that
9174     // don't support variadic calls. Only do this in C and do it after merging
9175     // possibly prototyped redeclarations.
9176     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9177     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9178       CallingConv CC = FT->getExtInfo().getCC();
9179       if (!supportsVariadicCall(CC)) {
9180         // Windows system headers sometimes accidentally use stdcall without
9181         // (void) parameters, so we relax this to a warning.
9182         int DiagID =
9183             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9184         Diag(NewFD->getLocation(), DiagID)
9185             << FunctionType::getNameForCallConv(CC);
9186       }
9187     }
9188 
9189    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9190        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9191      checkNonTrivialCUnion(NewFD->getReturnType(),
9192                            NewFD->getReturnTypeSourceRange().getBegin(),
9193                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9194   } else {
9195     // C++11 [replacement.functions]p3:
9196     //  The program's definitions shall not be specified as inline.
9197     //
9198     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9199     //
9200     // Suppress the diagnostic if the function is __attribute__((used)), since
9201     // that forces an external definition to be emitted.
9202     if (D.getDeclSpec().isInlineSpecified() &&
9203         NewFD->isReplaceableGlobalAllocationFunction() &&
9204         !NewFD->hasAttr<UsedAttr>())
9205       Diag(D.getDeclSpec().getInlineSpecLoc(),
9206            diag::ext_operator_new_delete_declared_inline)
9207         << NewFD->getDeclName();
9208 
9209     // If the declarator is a template-id, translate the parser's template
9210     // argument list into our AST format.
9211     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9212       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9213       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9214       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9215       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9216                                          TemplateId->NumArgs);
9217       translateTemplateArguments(TemplateArgsPtr,
9218                                  TemplateArgs);
9219 
9220       HasExplicitTemplateArgs = true;
9221 
9222       if (NewFD->isInvalidDecl()) {
9223         HasExplicitTemplateArgs = false;
9224       } else if (FunctionTemplate) {
9225         // Function template with explicit template arguments.
9226         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9227           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9228 
9229         HasExplicitTemplateArgs = false;
9230       } else {
9231         assert((isFunctionTemplateSpecialization ||
9232                 D.getDeclSpec().isFriendSpecified()) &&
9233                "should have a 'template<>' for this decl");
9234         // "friend void foo<>(int);" is an implicit specialization decl.
9235         isFunctionTemplateSpecialization = true;
9236       }
9237     } else if (isFriend && isFunctionTemplateSpecialization) {
9238       // This combination is only possible in a recovery case;  the user
9239       // wrote something like:
9240       //   template <> friend void foo(int);
9241       // which we're recovering from as if the user had written:
9242       //   friend void foo<>(int);
9243       // Go ahead and fake up a template id.
9244       HasExplicitTemplateArgs = true;
9245       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9246       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9247     }
9248 
9249     // We do not add HD attributes to specializations here because
9250     // they may have different constexpr-ness compared to their
9251     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9252     // may end up with different effective targets. Instead, a
9253     // specialization inherits its target attributes from its template
9254     // in the CheckFunctionTemplateSpecialization() call below.
9255     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9256       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9257 
9258     // If it's a friend (and only if it's a friend), it's possible
9259     // that either the specialized function type or the specialized
9260     // template is dependent, and therefore matching will fail.  In
9261     // this case, don't check the specialization yet.
9262     bool InstantiationDependent = false;
9263     if (isFunctionTemplateSpecialization && isFriend &&
9264         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9265          TemplateSpecializationType::anyDependentTemplateArguments(
9266             TemplateArgs,
9267             InstantiationDependent))) {
9268       assert(HasExplicitTemplateArgs &&
9269              "friend function specialization without template args");
9270       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9271                                                        Previous))
9272         NewFD->setInvalidDecl();
9273     } else if (isFunctionTemplateSpecialization) {
9274       if (CurContext->isDependentContext() && CurContext->isRecord()
9275           && !isFriend) {
9276         isDependentClassScopeExplicitSpecialization = true;
9277       } else if (!NewFD->isInvalidDecl() &&
9278                  CheckFunctionTemplateSpecialization(
9279                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9280                      Previous))
9281         NewFD->setInvalidDecl();
9282 
9283       // C++ [dcl.stc]p1:
9284       //   A storage-class-specifier shall not be specified in an explicit
9285       //   specialization (14.7.3)
9286       FunctionTemplateSpecializationInfo *Info =
9287           NewFD->getTemplateSpecializationInfo();
9288       if (Info && SC != SC_None) {
9289         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9290           Diag(NewFD->getLocation(),
9291                diag::err_explicit_specialization_inconsistent_storage_class)
9292             << SC
9293             << FixItHint::CreateRemoval(
9294                                       D.getDeclSpec().getStorageClassSpecLoc());
9295 
9296         else
9297           Diag(NewFD->getLocation(),
9298                diag::ext_explicit_specialization_storage_class)
9299             << FixItHint::CreateRemoval(
9300                                       D.getDeclSpec().getStorageClassSpecLoc());
9301       }
9302     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9303       if (CheckMemberSpecialization(NewFD, Previous))
9304           NewFD->setInvalidDecl();
9305     }
9306 
9307     // Perform semantic checking on the function declaration.
9308     if (!isDependentClassScopeExplicitSpecialization) {
9309       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9310         CheckMain(NewFD, D.getDeclSpec());
9311 
9312       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9313         CheckMSVCRTEntryPoint(NewFD);
9314 
9315       if (!NewFD->isInvalidDecl())
9316         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9317                                                     isMemberSpecialization));
9318       else if (!Previous.empty())
9319         // Recover gracefully from an invalid redeclaration.
9320         D.setRedeclaration(true);
9321     }
9322 
9323     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9324             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9325            "previous declaration set still overloaded");
9326 
9327     NamedDecl *PrincipalDecl = (FunctionTemplate
9328                                 ? cast<NamedDecl>(FunctionTemplate)
9329                                 : NewFD);
9330 
9331     if (isFriend && NewFD->getPreviousDecl()) {
9332       AccessSpecifier Access = AS_public;
9333       if (!NewFD->isInvalidDecl())
9334         Access = NewFD->getPreviousDecl()->getAccess();
9335 
9336       NewFD->setAccess(Access);
9337       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9338     }
9339 
9340     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9341         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9342       PrincipalDecl->setNonMemberOperator();
9343 
9344     // If we have a function template, check the template parameter
9345     // list. This will check and merge default template arguments.
9346     if (FunctionTemplate) {
9347       FunctionTemplateDecl *PrevTemplate =
9348                                      FunctionTemplate->getPreviousDecl();
9349       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9350                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9351                                     : nullptr,
9352                             D.getDeclSpec().isFriendSpecified()
9353                               ? (D.isFunctionDefinition()
9354                                    ? TPC_FriendFunctionTemplateDefinition
9355                                    : TPC_FriendFunctionTemplate)
9356                               : (D.getCXXScopeSpec().isSet() &&
9357                                  DC && DC->isRecord() &&
9358                                  DC->isDependentContext())
9359                                   ? TPC_ClassTemplateMember
9360                                   : TPC_FunctionTemplate);
9361     }
9362 
9363     if (NewFD->isInvalidDecl()) {
9364       // Ignore all the rest of this.
9365     } else if (!D.isRedeclaration()) {
9366       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9367                                        AddToScope };
9368       // Fake up an access specifier if it's supposed to be a class member.
9369       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9370         NewFD->setAccess(AS_public);
9371 
9372       // Qualified decls generally require a previous declaration.
9373       if (D.getCXXScopeSpec().isSet()) {
9374         // ...with the major exception of templated-scope or
9375         // dependent-scope friend declarations.
9376 
9377         // TODO: we currently also suppress this check in dependent
9378         // contexts because (1) the parameter depth will be off when
9379         // matching friend templates and (2) we might actually be
9380         // selecting a friend based on a dependent factor.  But there
9381         // are situations where these conditions don't apply and we
9382         // can actually do this check immediately.
9383         //
9384         // Unless the scope is dependent, it's always an error if qualified
9385         // redeclaration lookup found nothing at all. Diagnose that now;
9386         // nothing will diagnose that error later.
9387         if (isFriend &&
9388             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9389              (!Previous.empty() && CurContext->isDependentContext()))) {
9390           // ignore these
9391         } else {
9392           // The user tried to provide an out-of-line definition for a
9393           // function that is a member of a class or namespace, but there
9394           // was no such member function declared (C++ [class.mfct]p2,
9395           // C++ [namespace.memdef]p2). For example:
9396           //
9397           // class X {
9398           //   void f() const;
9399           // };
9400           //
9401           // void X::f() { } // ill-formed
9402           //
9403           // Complain about this problem, and attempt to suggest close
9404           // matches (e.g., those that differ only in cv-qualifiers and
9405           // whether the parameter types are references).
9406 
9407           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9408                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9409             AddToScope = ExtraArgs.AddToScope;
9410             return Result;
9411           }
9412         }
9413 
9414         // Unqualified local friend declarations are required to resolve
9415         // to something.
9416       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9417         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9418                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9419           AddToScope = ExtraArgs.AddToScope;
9420           return Result;
9421         }
9422       }
9423     } else if (!D.isFunctionDefinition() &&
9424                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9425                !isFriend && !isFunctionTemplateSpecialization &&
9426                !isMemberSpecialization) {
9427       // An out-of-line member function declaration must also be a
9428       // definition (C++ [class.mfct]p2).
9429       // Note that this is not the case for explicit specializations of
9430       // function templates or member functions of class templates, per
9431       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9432       // extension for compatibility with old SWIG code which likes to
9433       // generate them.
9434       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9435         << D.getCXXScopeSpec().getRange();
9436     }
9437   }
9438 
9439   ProcessPragmaWeak(S, NewFD);
9440   checkAttributesAfterMerging(*this, *NewFD);
9441 
9442   AddKnownFunctionAttributes(NewFD);
9443 
9444   if (NewFD->hasAttr<OverloadableAttr>() &&
9445       !NewFD->getType()->getAs<FunctionProtoType>()) {
9446     Diag(NewFD->getLocation(),
9447          diag::err_attribute_overloadable_no_prototype)
9448       << NewFD;
9449 
9450     // Turn this into a variadic function with no parameters.
9451     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9452     FunctionProtoType::ExtProtoInfo EPI(
9453         Context.getDefaultCallingConvention(true, false));
9454     EPI.Variadic = true;
9455     EPI.ExtInfo = FT->getExtInfo();
9456 
9457     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9458     NewFD->setType(R);
9459   }
9460 
9461   // If there's a #pragma GCC visibility in scope, and this isn't a class
9462   // member, set the visibility of this function.
9463   if (!DC->isRecord() && NewFD->isExternallyVisible())
9464     AddPushedVisibilityAttribute(NewFD);
9465 
9466   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9467   // marking the function.
9468   AddCFAuditedAttribute(NewFD);
9469 
9470   // If this is a function definition, check if we have to apply optnone due to
9471   // a pragma.
9472   if(D.isFunctionDefinition())
9473     AddRangeBasedOptnone(NewFD);
9474 
9475   // If this is the first declaration of an extern C variable, update
9476   // the map of such variables.
9477   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9478       isIncompleteDeclExternC(*this, NewFD))
9479     RegisterLocallyScopedExternCDecl(NewFD, S);
9480 
9481   // Set this FunctionDecl's range up to the right paren.
9482   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9483 
9484   if (D.isRedeclaration() && !Previous.empty()) {
9485     NamedDecl *Prev = Previous.getRepresentativeDecl();
9486     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9487                                    isMemberSpecialization ||
9488                                        isFunctionTemplateSpecialization,
9489                                    D.isFunctionDefinition());
9490   }
9491 
9492   if (getLangOpts().CUDA) {
9493     IdentifierInfo *II = NewFD->getIdentifier();
9494     if (II && II->isStr(getCudaConfigureFuncName()) &&
9495         !NewFD->isInvalidDecl() &&
9496         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9497       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9498         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9499             << getCudaConfigureFuncName();
9500       Context.setcudaConfigureCallDecl(NewFD);
9501     }
9502 
9503     // Variadic functions, other than a *declaration* of printf, are not allowed
9504     // in device-side CUDA code, unless someone passed
9505     // -fcuda-allow-variadic-functions.
9506     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9507         (NewFD->hasAttr<CUDADeviceAttr>() ||
9508          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9509         !(II && II->isStr("printf") && NewFD->isExternC() &&
9510           !D.isFunctionDefinition())) {
9511       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9512     }
9513   }
9514 
9515   MarkUnusedFileScopedDecl(NewFD);
9516 
9517 
9518 
9519   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9520     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9521     if ((getLangOpts().OpenCLVersion >= 120)
9522         && (SC == SC_Static)) {
9523       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9524       D.setInvalidType();
9525     }
9526 
9527     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9528     if (!NewFD->getReturnType()->isVoidType()) {
9529       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9530       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9531           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9532                                 : FixItHint());
9533       D.setInvalidType();
9534     }
9535 
9536     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9537     for (auto Param : NewFD->parameters())
9538       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9539 
9540     if (getLangOpts().OpenCLCPlusPlus) {
9541       if (DC->isRecord()) {
9542         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9543         D.setInvalidType();
9544       }
9545       if (FunctionTemplate) {
9546         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9547         D.setInvalidType();
9548       }
9549     }
9550   }
9551 
9552   if (getLangOpts().CPlusPlus) {
9553     if (FunctionTemplate) {
9554       if (NewFD->isInvalidDecl())
9555         FunctionTemplate->setInvalidDecl();
9556       return FunctionTemplate;
9557     }
9558 
9559     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9560       CompleteMemberSpecialization(NewFD, Previous);
9561   }
9562 
9563   for (const ParmVarDecl *Param : NewFD->parameters()) {
9564     QualType PT = Param->getType();
9565 
9566     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9567     // types.
9568     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9569       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9570         QualType ElemTy = PipeTy->getElementType();
9571           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9572             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9573             D.setInvalidType();
9574           }
9575       }
9576     }
9577   }
9578 
9579   // Here we have an function template explicit specialization at class scope.
9580   // The actual specialization will be postponed to template instatiation
9581   // time via the ClassScopeFunctionSpecializationDecl node.
9582   if (isDependentClassScopeExplicitSpecialization) {
9583     ClassScopeFunctionSpecializationDecl *NewSpec =
9584                          ClassScopeFunctionSpecializationDecl::Create(
9585                                 Context, CurContext, NewFD->getLocation(),
9586                                 cast<CXXMethodDecl>(NewFD),
9587                                 HasExplicitTemplateArgs, TemplateArgs);
9588     CurContext->addDecl(NewSpec);
9589     AddToScope = false;
9590   }
9591 
9592   // Diagnose availability attributes. Availability cannot be used on functions
9593   // that are run during load/unload.
9594   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9595     if (NewFD->hasAttr<ConstructorAttr>()) {
9596       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9597           << 1;
9598       NewFD->dropAttr<AvailabilityAttr>();
9599     }
9600     if (NewFD->hasAttr<DestructorAttr>()) {
9601       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9602           << 2;
9603       NewFD->dropAttr<AvailabilityAttr>();
9604     }
9605   }
9606 
9607   // Diagnose no_builtin attribute on function declaration that are not a
9608   // definition.
9609   // FIXME: We should really be doing this in
9610   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9611   // the FunctionDecl and at this point of the code
9612   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9613   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9614   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9615     switch (D.getFunctionDefinitionKind()) {
9616     case FDK_Defaulted:
9617     case FDK_Deleted:
9618       Diag(NBA->getLocation(),
9619            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9620           << NBA->getSpelling();
9621       break;
9622     case FDK_Declaration:
9623       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9624           << NBA->getSpelling();
9625       break;
9626     case FDK_Definition:
9627       break;
9628     }
9629 
9630   return NewFD;
9631 }
9632 
9633 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9634 /// when __declspec(code_seg) "is applied to a class, all member functions of
9635 /// the class and nested classes -- this includes compiler-generated special
9636 /// member functions -- are put in the specified segment."
9637 /// The actual behavior is a little more complicated. The Microsoft compiler
9638 /// won't check outer classes if there is an active value from #pragma code_seg.
9639 /// The CodeSeg is always applied from the direct parent but only from outer
9640 /// classes when the #pragma code_seg stack is empty. See:
9641 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9642 /// available since MS has removed the page.
9643 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9644   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9645   if (!Method)
9646     return nullptr;
9647   const CXXRecordDecl *Parent = Method->getParent();
9648   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9649     Attr *NewAttr = SAttr->clone(S.getASTContext());
9650     NewAttr->setImplicit(true);
9651     return NewAttr;
9652   }
9653 
9654   // The Microsoft compiler won't check outer classes for the CodeSeg
9655   // when the #pragma code_seg stack is active.
9656   if (S.CodeSegStack.CurrentValue)
9657    return nullptr;
9658 
9659   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9660     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9661       Attr *NewAttr = SAttr->clone(S.getASTContext());
9662       NewAttr->setImplicit(true);
9663       return NewAttr;
9664     }
9665   }
9666   return nullptr;
9667 }
9668 
9669 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9670 /// containing class. Otherwise it will return implicit SectionAttr if the
9671 /// function is a definition and there is an active value on CodeSegStack
9672 /// (from the current #pragma code-seg value).
9673 ///
9674 /// \param FD Function being declared.
9675 /// \param IsDefinition Whether it is a definition or just a declarartion.
9676 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9677 ///          nullptr if no attribute should be added.
9678 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9679                                                        bool IsDefinition) {
9680   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9681     return A;
9682   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9683       CodeSegStack.CurrentValue)
9684     return SectionAttr::CreateImplicit(
9685         getASTContext(), CodeSegStack.CurrentValue->getString(),
9686         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9687         SectionAttr::Declspec_allocate);
9688   return nullptr;
9689 }
9690 
9691 /// Determines if we can perform a correct type check for \p D as a
9692 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9693 /// best-effort check.
9694 ///
9695 /// \param NewD The new declaration.
9696 /// \param OldD The old declaration.
9697 /// \param NewT The portion of the type of the new declaration to check.
9698 /// \param OldT The portion of the type of the old declaration to check.
9699 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9700                                           QualType NewT, QualType OldT) {
9701   if (!NewD->getLexicalDeclContext()->isDependentContext())
9702     return true;
9703 
9704   // For dependently-typed local extern declarations and friends, we can't
9705   // perform a correct type check in general until instantiation:
9706   //
9707   //   int f();
9708   //   template<typename T> void g() { T f(); }
9709   //
9710   // (valid if g() is only instantiated with T = int).
9711   if (NewT->isDependentType() &&
9712       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9713     return false;
9714 
9715   // Similarly, if the previous declaration was a dependent local extern
9716   // declaration, we don't really know its type yet.
9717   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9718     return false;
9719 
9720   return true;
9721 }
9722 
9723 /// Checks if the new declaration declared in dependent context must be
9724 /// put in the same redeclaration chain as the specified declaration.
9725 ///
9726 /// \param D Declaration that is checked.
9727 /// \param PrevDecl Previous declaration found with proper lookup method for the
9728 ///                 same declaration name.
9729 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9730 ///          belongs to.
9731 ///
9732 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9733   if (!D->getLexicalDeclContext()->isDependentContext())
9734     return true;
9735 
9736   // Don't chain dependent friend function definitions until instantiation, to
9737   // permit cases like
9738   //
9739   //   void func();
9740   //   template<typename T> class C1 { friend void func() {} };
9741   //   template<typename T> class C2 { friend void func() {} };
9742   //
9743   // ... which is valid if only one of C1 and C2 is ever instantiated.
9744   //
9745   // FIXME: This need only apply to function definitions. For now, we proxy
9746   // this by checking for a file-scope function. We do not want this to apply
9747   // to friend declarations nominating member functions, because that gets in
9748   // the way of access checks.
9749   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9750     return false;
9751 
9752   auto *VD = dyn_cast<ValueDecl>(D);
9753   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9754   return !VD || !PrevVD ||
9755          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9756                                         PrevVD->getType());
9757 }
9758 
9759 /// Check the target attribute of the function for MultiVersion
9760 /// validity.
9761 ///
9762 /// Returns true if there was an error, false otherwise.
9763 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9764   const auto *TA = FD->getAttr<TargetAttr>();
9765   assert(TA && "MultiVersion Candidate requires a target attribute");
9766   ParsedTargetAttr ParseInfo = TA->parse();
9767   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9768   enum ErrType { Feature = 0, Architecture = 1 };
9769 
9770   if (!ParseInfo.Architecture.empty() &&
9771       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9772     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9773         << Architecture << ParseInfo.Architecture;
9774     return true;
9775   }
9776 
9777   for (const auto &Feat : ParseInfo.Features) {
9778     auto BareFeat = StringRef{Feat}.substr(1);
9779     if (Feat[0] == '-') {
9780       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9781           << Feature << ("no-" + BareFeat).str();
9782       return true;
9783     }
9784 
9785     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9786         !TargetInfo.isValidFeatureName(BareFeat)) {
9787       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9788           << Feature << BareFeat;
9789       return true;
9790     }
9791   }
9792   return false;
9793 }
9794 
9795 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9796                                          MultiVersionKind MVType) {
9797   for (const Attr *A : FD->attrs()) {
9798     switch (A->getKind()) {
9799     case attr::CPUDispatch:
9800     case attr::CPUSpecific:
9801       if (MVType != MultiVersionKind::CPUDispatch &&
9802           MVType != MultiVersionKind::CPUSpecific)
9803         return true;
9804       break;
9805     case attr::Target:
9806       if (MVType != MultiVersionKind::Target)
9807         return true;
9808       break;
9809     default:
9810       return true;
9811     }
9812   }
9813   return false;
9814 }
9815 
9816 bool Sema::areMultiversionVariantFunctionsCompatible(
9817     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9818     const PartialDiagnostic &NoProtoDiagID,
9819     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9820     const PartialDiagnosticAt &NoSupportDiagIDAt,
9821     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9822     bool ConstexprSupported, bool CLinkageMayDiffer) {
9823   enum DoesntSupport {
9824     FuncTemplates = 0,
9825     VirtFuncs = 1,
9826     DeducedReturn = 2,
9827     Constructors = 3,
9828     Destructors = 4,
9829     DeletedFuncs = 5,
9830     DefaultedFuncs = 6,
9831     ConstexprFuncs = 7,
9832     ConstevalFuncs = 8,
9833   };
9834   enum Different {
9835     CallingConv = 0,
9836     ReturnType = 1,
9837     ConstexprSpec = 2,
9838     InlineSpec = 3,
9839     StorageClass = 4,
9840     Linkage = 5,
9841   };
9842 
9843   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9844       !OldFD->getType()->getAs<FunctionProtoType>()) {
9845     Diag(OldFD->getLocation(), NoProtoDiagID);
9846     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9847     return true;
9848   }
9849 
9850   if (NoProtoDiagID.getDiagID() != 0 &&
9851       !NewFD->getType()->getAs<FunctionProtoType>())
9852     return Diag(NewFD->getLocation(), NoProtoDiagID);
9853 
9854   if (!TemplatesSupported &&
9855       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9856     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9857            << FuncTemplates;
9858 
9859   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9860     if (NewCXXFD->isVirtual())
9861       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9862              << VirtFuncs;
9863 
9864     if (isa<CXXConstructorDecl>(NewCXXFD))
9865       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9866              << Constructors;
9867 
9868     if (isa<CXXDestructorDecl>(NewCXXFD))
9869       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9870              << Destructors;
9871   }
9872 
9873   if (NewFD->isDeleted())
9874     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9875            << DeletedFuncs;
9876 
9877   if (NewFD->isDefaulted())
9878     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9879            << DefaultedFuncs;
9880 
9881   if (!ConstexprSupported && NewFD->isConstexpr())
9882     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9883            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9884 
9885   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9886   const auto *NewType = cast<FunctionType>(NewQType);
9887   QualType NewReturnType = NewType->getReturnType();
9888 
9889   if (NewReturnType->isUndeducedType())
9890     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9891            << DeducedReturn;
9892 
9893   // Ensure the return type is identical.
9894   if (OldFD) {
9895     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9896     const auto *OldType = cast<FunctionType>(OldQType);
9897     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9898     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9899 
9900     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9901       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9902 
9903     QualType OldReturnType = OldType->getReturnType();
9904 
9905     if (OldReturnType != NewReturnType)
9906       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9907 
9908     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9909       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9910 
9911     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9912       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9913 
9914     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9915       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9916 
9917     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9918       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9919 
9920     if (CheckEquivalentExceptionSpec(
9921             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9922             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9923       return true;
9924   }
9925   return false;
9926 }
9927 
9928 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9929                                              const FunctionDecl *NewFD,
9930                                              bool CausesMV,
9931                                              MultiVersionKind MVType) {
9932   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9933     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9934     if (OldFD)
9935       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9936     return true;
9937   }
9938 
9939   bool IsCPUSpecificCPUDispatchMVType =
9940       MVType == MultiVersionKind::CPUDispatch ||
9941       MVType == MultiVersionKind::CPUSpecific;
9942 
9943   // For now, disallow all other attributes.  These should be opt-in, but
9944   // an analysis of all of them is a future FIXME.
9945   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9946     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9947         << IsCPUSpecificCPUDispatchMVType;
9948     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9949     return true;
9950   }
9951 
9952   if (HasNonMultiVersionAttributes(NewFD, MVType))
9953     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9954            << IsCPUSpecificCPUDispatchMVType;
9955 
9956   // Only allow transition to MultiVersion if it hasn't been used.
9957   if (OldFD && CausesMV && OldFD->isUsed(false))
9958     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9959 
9960   return S.areMultiversionVariantFunctionsCompatible(
9961       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9962       PartialDiagnosticAt(NewFD->getLocation(),
9963                           S.PDiag(diag::note_multiversioning_caused_here)),
9964       PartialDiagnosticAt(NewFD->getLocation(),
9965                           S.PDiag(diag::err_multiversion_doesnt_support)
9966                               << IsCPUSpecificCPUDispatchMVType),
9967       PartialDiagnosticAt(NewFD->getLocation(),
9968                           S.PDiag(diag::err_multiversion_diff)),
9969       /*TemplatesSupported=*/false,
9970       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9971       /*CLinkageMayDiffer=*/false);
9972 }
9973 
9974 /// Check the validity of a multiversion function declaration that is the
9975 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9976 ///
9977 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9978 ///
9979 /// Returns true if there was an error, false otherwise.
9980 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9981                                            MultiVersionKind MVType,
9982                                            const TargetAttr *TA) {
9983   assert(MVType != MultiVersionKind::None &&
9984          "Function lacks multiversion attribute");
9985 
9986   // Target only causes MV if it is default, otherwise this is a normal
9987   // function.
9988   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9989     return false;
9990 
9991   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9992     FD->setInvalidDecl();
9993     return true;
9994   }
9995 
9996   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9997     FD->setInvalidDecl();
9998     return true;
9999   }
10000 
10001   FD->setIsMultiVersion();
10002   return false;
10003 }
10004 
10005 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10006   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10007     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10008       return true;
10009   }
10010 
10011   return false;
10012 }
10013 
10014 static bool CheckTargetCausesMultiVersioning(
10015     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10016     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10017     LookupResult &Previous) {
10018   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10019   ParsedTargetAttr NewParsed = NewTA->parse();
10020   // Sort order doesn't matter, it just needs to be consistent.
10021   llvm::sort(NewParsed.Features);
10022 
10023   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10024   // to change, this is a simple redeclaration.
10025   if (!NewTA->isDefaultVersion() &&
10026       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10027     return false;
10028 
10029   // Otherwise, this decl causes MultiVersioning.
10030   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10031     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10032     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10033     NewFD->setInvalidDecl();
10034     return true;
10035   }
10036 
10037   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10038                                        MultiVersionKind::Target)) {
10039     NewFD->setInvalidDecl();
10040     return true;
10041   }
10042 
10043   if (CheckMultiVersionValue(S, NewFD)) {
10044     NewFD->setInvalidDecl();
10045     return true;
10046   }
10047 
10048   // If this is 'default', permit the forward declaration.
10049   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10050     Redeclaration = true;
10051     OldDecl = OldFD;
10052     OldFD->setIsMultiVersion();
10053     NewFD->setIsMultiVersion();
10054     return false;
10055   }
10056 
10057   if (CheckMultiVersionValue(S, OldFD)) {
10058     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10059     NewFD->setInvalidDecl();
10060     return true;
10061   }
10062 
10063   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10064 
10065   if (OldParsed == NewParsed) {
10066     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10067     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10068     NewFD->setInvalidDecl();
10069     return true;
10070   }
10071 
10072   for (const auto *FD : OldFD->redecls()) {
10073     const auto *CurTA = FD->getAttr<TargetAttr>();
10074     // We allow forward declarations before ANY multiversioning attributes, but
10075     // nothing after the fact.
10076     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10077         (!CurTA || CurTA->isInherited())) {
10078       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10079           << 0;
10080       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10081       NewFD->setInvalidDecl();
10082       return true;
10083     }
10084   }
10085 
10086   OldFD->setIsMultiVersion();
10087   NewFD->setIsMultiVersion();
10088   Redeclaration = false;
10089   MergeTypeWithPrevious = false;
10090   OldDecl = nullptr;
10091   Previous.clear();
10092   return false;
10093 }
10094 
10095 /// Check the validity of a new function declaration being added to an existing
10096 /// multiversioned declaration collection.
10097 static bool CheckMultiVersionAdditionalDecl(
10098     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10099     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10100     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10101     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10102     LookupResult &Previous) {
10103 
10104   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10105   // Disallow mixing of multiversioning types.
10106   if ((OldMVType == MultiVersionKind::Target &&
10107        NewMVType != MultiVersionKind::Target) ||
10108       (NewMVType == MultiVersionKind::Target &&
10109        OldMVType != MultiVersionKind::Target)) {
10110     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10111     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10112     NewFD->setInvalidDecl();
10113     return true;
10114   }
10115 
10116   ParsedTargetAttr NewParsed;
10117   if (NewTA) {
10118     NewParsed = NewTA->parse();
10119     llvm::sort(NewParsed.Features);
10120   }
10121 
10122   bool UseMemberUsingDeclRules =
10123       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10124 
10125   // Next, check ALL non-overloads to see if this is a redeclaration of a
10126   // previous member of the MultiVersion set.
10127   for (NamedDecl *ND : Previous) {
10128     FunctionDecl *CurFD = ND->getAsFunction();
10129     if (!CurFD)
10130       continue;
10131     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10132       continue;
10133 
10134     if (NewMVType == MultiVersionKind::Target) {
10135       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10136       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10137         NewFD->setIsMultiVersion();
10138         Redeclaration = true;
10139         OldDecl = ND;
10140         return false;
10141       }
10142 
10143       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10144       if (CurParsed == NewParsed) {
10145         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10146         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10147         NewFD->setInvalidDecl();
10148         return true;
10149       }
10150     } else {
10151       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10152       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10153       // Handle CPUDispatch/CPUSpecific versions.
10154       // Only 1 CPUDispatch function is allowed, this will make it go through
10155       // the redeclaration errors.
10156       if (NewMVType == MultiVersionKind::CPUDispatch &&
10157           CurFD->hasAttr<CPUDispatchAttr>()) {
10158         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10159             std::equal(
10160                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10161                 NewCPUDisp->cpus_begin(),
10162                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10163                   return Cur->getName() == New->getName();
10164                 })) {
10165           NewFD->setIsMultiVersion();
10166           Redeclaration = true;
10167           OldDecl = ND;
10168           return false;
10169         }
10170 
10171         // If the declarations don't match, this is an error condition.
10172         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10173         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10174         NewFD->setInvalidDecl();
10175         return true;
10176       }
10177       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10178 
10179         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10180             std::equal(
10181                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10182                 NewCPUSpec->cpus_begin(),
10183                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10184                   return Cur->getName() == New->getName();
10185                 })) {
10186           NewFD->setIsMultiVersion();
10187           Redeclaration = true;
10188           OldDecl = ND;
10189           return false;
10190         }
10191 
10192         // Only 1 version of CPUSpecific is allowed for each CPU.
10193         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10194           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10195             if (CurII == NewII) {
10196               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10197                   << NewII;
10198               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10199               NewFD->setInvalidDecl();
10200               return true;
10201             }
10202           }
10203         }
10204       }
10205       // If the two decls aren't the same MVType, there is no possible error
10206       // condition.
10207     }
10208   }
10209 
10210   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10211   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10212   // handled in the attribute adding step.
10213   if (NewMVType == MultiVersionKind::Target &&
10214       CheckMultiVersionValue(S, NewFD)) {
10215     NewFD->setInvalidDecl();
10216     return true;
10217   }
10218 
10219   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10220                                        !OldFD->isMultiVersion(), NewMVType)) {
10221     NewFD->setInvalidDecl();
10222     return true;
10223   }
10224 
10225   // Permit forward declarations in the case where these two are compatible.
10226   if (!OldFD->isMultiVersion()) {
10227     OldFD->setIsMultiVersion();
10228     NewFD->setIsMultiVersion();
10229     Redeclaration = true;
10230     OldDecl = OldFD;
10231     return false;
10232   }
10233 
10234   NewFD->setIsMultiVersion();
10235   Redeclaration = false;
10236   MergeTypeWithPrevious = false;
10237   OldDecl = nullptr;
10238   Previous.clear();
10239   return false;
10240 }
10241 
10242 
10243 /// Check the validity of a mulitversion function declaration.
10244 /// Also sets the multiversion'ness' of the function itself.
10245 ///
10246 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10247 ///
10248 /// Returns true if there was an error, false otherwise.
10249 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10250                                       bool &Redeclaration, NamedDecl *&OldDecl,
10251                                       bool &MergeTypeWithPrevious,
10252                                       LookupResult &Previous) {
10253   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10254   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10255   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10256 
10257   // Mixing Multiversioning types is prohibited.
10258   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10259       (NewCPUDisp && NewCPUSpec)) {
10260     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10261     NewFD->setInvalidDecl();
10262     return true;
10263   }
10264 
10265   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10266 
10267   // Main isn't allowed to become a multiversion function, however it IS
10268   // permitted to have 'main' be marked with the 'target' optimization hint.
10269   if (NewFD->isMain()) {
10270     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10271         MVType == MultiVersionKind::CPUDispatch ||
10272         MVType == MultiVersionKind::CPUSpecific) {
10273       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10274       NewFD->setInvalidDecl();
10275       return true;
10276     }
10277     return false;
10278   }
10279 
10280   if (!OldDecl || !OldDecl->getAsFunction() ||
10281       OldDecl->getDeclContext()->getRedeclContext() !=
10282           NewFD->getDeclContext()->getRedeclContext()) {
10283     // If there's no previous declaration, AND this isn't attempting to cause
10284     // multiversioning, this isn't an error condition.
10285     if (MVType == MultiVersionKind::None)
10286       return false;
10287     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10288   }
10289 
10290   FunctionDecl *OldFD = OldDecl->getAsFunction();
10291 
10292   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10293     return false;
10294 
10295   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10296     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10297         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10298     NewFD->setInvalidDecl();
10299     return true;
10300   }
10301 
10302   // Handle the target potentially causes multiversioning case.
10303   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10304     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10305                                             Redeclaration, OldDecl,
10306                                             MergeTypeWithPrevious, Previous);
10307 
10308   // At this point, we have a multiversion function decl (in OldFD) AND an
10309   // appropriate attribute in the current function decl.  Resolve that these are
10310   // still compatible with previous declarations.
10311   return CheckMultiVersionAdditionalDecl(
10312       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10313       OldDecl, MergeTypeWithPrevious, Previous);
10314 }
10315 
10316 /// Perform semantic checking of a new function declaration.
10317 ///
10318 /// Performs semantic analysis of the new function declaration
10319 /// NewFD. This routine performs all semantic checking that does not
10320 /// require the actual declarator involved in the declaration, and is
10321 /// used both for the declaration of functions as they are parsed
10322 /// (called via ActOnDeclarator) and for the declaration of functions
10323 /// that have been instantiated via C++ template instantiation (called
10324 /// via InstantiateDecl).
10325 ///
10326 /// \param IsMemberSpecialization whether this new function declaration is
10327 /// a member specialization (that replaces any definition provided by the
10328 /// previous declaration).
10329 ///
10330 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10331 ///
10332 /// \returns true if the function declaration is a redeclaration.
10333 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10334                                     LookupResult &Previous,
10335                                     bool IsMemberSpecialization) {
10336   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10337          "Variably modified return types are not handled here");
10338 
10339   // Determine whether the type of this function should be merged with
10340   // a previous visible declaration. This never happens for functions in C++,
10341   // and always happens in C if the previous declaration was visible.
10342   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10343                                !Previous.isShadowed();
10344 
10345   bool Redeclaration = false;
10346   NamedDecl *OldDecl = nullptr;
10347   bool MayNeedOverloadableChecks = false;
10348 
10349   // Merge or overload the declaration with an existing declaration of
10350   // the same name, if appropriate.
10351   if (!Previous.empty()) {
10352     // Determine whether NewFD is an overload of PrevDecl or
10353     // a declaration that requires merging. If it's an overload,
10354     // there's no more work to do here; we'll just add the new
10355     // function to the scope.
10356     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10357       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10358       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10359         Redeclaration = true;
10360         OldDecl = Candidate;
10361       }
10362     } else {
10363       MayNeedOverloadableChecks = true;
10364       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10365                             /*NewIsUsingDecl*/ false)) {
10366       case Ovl_Match:
10367         Redeclaration = true;
10368         break;
10369 
10370       case Ovl_NonFunction:
10371         Redeclaration = true;
10372         break;
10373 
10374       case Ovl_Overload:
10375         Redeclaration = false;
10376         break;
10377       }
10378     }
10379   }
10380 
10381   // Check for a previous extern "C" declaration with this name.
10382   if (!Redeclaration &&
10383       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10384     if (!Previous.empty()) {
10385       // This is an extern "C" declaration with the same name as a previous
10386       // declaration, and thus redeclares that entity...
10387       Redeclaration = true;
10388       OldDecl = Previous.getFoundDecl();
10389       MergeTypeWithPrevious = false;
10390 
10391       // ... except in the presence of __attribute__((overloadable)).
10392       if (OldDecl->hasAttr<OverloadableAttr>() ||
10393           NewFD->hasAttr<OverloadableAttr>()) {
10394         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10395           MayNeedOverloadableChecks = true;
10396           Redeclaration = false;
10397           OldDecl = nullptr;
10398         }
10399       }
10400     }
10401   }
10402 
10403   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10404                                 MergeTypeWithPrevious, Previous))
10405     return Redeclaration;
10406 
10407   // C++11 [dcl.constexpr]p8:
10408   //   A constexpr specifier for a non-static member function that is not
10409   //   a constructor declares that member function to be const.
10410   //
10411   // This needs to be delayed until we know whether this is an out-of-line
10412   // definition of a static member function.
10413   //
10414   // This rule is not present in C++1y, so we produce a backwards
10415   // compatibility warning whenever it happens in C++11.
10416   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10417   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10418       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10419       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10420     CXXMethodDecl *OldMD = nullptr;
10421     if (OldDecl)
10422       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10423     if (!OldMD || !OldMD->isStatic()) {
10424       const FunctionProtoType *FPT =
10425         MD->getType()->castAs<FunctionProtoType>();
10426       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10427       EPI.TypeQuals.addConst();
10428       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10429                                           FPT->getParamTypes(), EPI));
10430 
10431       // Warn that we did this, if we're not performing template instantiation.
10432       // In that case, we'll have warned already when the template was defined.
10433       if (!inTemplateInstantiation()) {
10434         SourceLocation AddConstLoc;
10435         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10436                 .IgnoreParens().getAs<FunctionTypeLoc>())
10437           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10438 
10439         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10440           << FixItHint::CreateInsertion(AddConstLoc, " const");
10441       }
10442     }
10443   }
10444 
10445   if (Redeclaration) {
10446     // NewFD and OldDecl represent declarations that need to be
10447     // merged.
10448     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10449       NewFD->setInvalidDecl();
10450       return Redeclaration;
10451     }
10452 
10453     Previous.clear();
10454     Previous.addDecl(OldDecl);
10455 
10456     if (FunctionTemplateDecl *OldTemplateDecl =
10457             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10458       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10459       FunctionTemplateDecl *NewTemplateDecl
10460         = NewFD->getDescribedFunctionTemplate();
10461       assert(NewTemplateDecl && "Template/non-template mismatch");
10462 
10463       // The call to MergeFunctionDecl above may have created some state in
10464       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10465       // can add it as a redeclaration.
10466       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10467 
10468       NewFD->setPreviousDeclaration(OldFD);
10469       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10470       if (NewFD->isCXXClassMember()) {
10471         NewFD->setAccess(OldTemplateDecl->getAccess());
10472         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10473       }
10474 
10475       // If this is an explicit specialization of a member that is a function
10476       // template, mark it as a member specialization.
10477       if (IsMemberSpecialization &&
10478           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10479         NewTemplateDecl->setMemberSpecialization();
10480         assert(OldTemplateDecl->isMemberSpecialization());
10481         // Explicit specializations of a member template do not inherit deleted
10482         // status from the parent member template that they are specializing.
10483         if (OldFD->isDeleted()) {
10484           // FIXME: This assert will not hold in the presence of modules.
10485           assert(OldFD->getCanonicalDecl() == OldFD);
10486           // FIXME: We need an update record for this AST mutation.
10487           OldFD->setDeletedAsWritten(false);
10488         }
10489       }
10490 
10491     } else {
10492       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10493         auto *OldFD = cast<FunctionDecl>(OldDecl);
10494         // This needs to happen first so that 'inline' propagates.
10495         NewFD->setPreviousDeclaration(OldFD);
10496         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10497         if (NewFD->isCXXClassMember())
10498           NewFD->setAccess(OldFD->getAccess());
10499       }
10500     }
10501   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10502              !NewFD->getAttr<OverloadableAttr>()) {
10503     assert((Previous.empty() ||
10504             llvm::any_of(Previous,
10505                          [](const NamedDecl *ND) {
10506                            return ND->hasAttr<OverloadableAttr>();
10507                          })) &&
10508            "Non-redecls shouldn't happen without overloadable present");
10509 
10510     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10511       const auto *FD = dyn_cast<FunctionDecl>(ND);
10512       return FD && !FD->hasAttr<OverloadableAttr>();
10513     });
10514 
10515     if (OtherUnmarkedIter != Previous.end()) {
10516       Diag(NewFD->getLocation(),
10517            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10518       Diag((*OtherUnmarkedIter)->getLocation(),
10519            diag::note_attribute_overloadable_prev_overload)
10520           << false;
10521 
10522       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10523     }
10524   }
10525 
10526   // Semantic checking for this function declaration (in isolation).
10527 
10528   if (getLangOpts().CPlusPlus) {
10529     // C++-specific checks.
10530     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10531       CheckConstructor(Constructor);
10532     } else if (CXXDestructorDecl *Destructor =
10533                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10534       CXXRecordDecl *Record = Destructor->getParent();
10535       QualType ClassType = Context.getTypeDeclType(Record);
10536 
10537       // FIXME: Shouldn't we be able to perform this check even when the class
10538       // type is dependent? Both gcc and edg can handle that.
10539       if (!ClassType->isDependentType()) {
10540         DeclarationName Name
10541           = Context.DeclarationNames.getCXXDestructorName(
10542                                         Context.getCanonicalType(ClassType));
10543         if (NewFD->getDeclName() != Name) {
10544           Diag(NewFD->getLocation(), diag::err_destructor_name);
10545           NewFD->setInvalidDecl();
10546           return Redeclaration;
10547         }
10548       }
10549     } else if (CXXConversionDecl *Conversion
10550                = dyn_cast<CXXConversionDecl>(NewFD)) {
10551       ActOnConversionDeclarator(Conversion);
10552     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10553       if (auto *TD = Guide->getDescribedFunctionTemplate())
10554         CheckDeductionGuideTemplate(TD);
10555 
10556       // A deduction guide is not on the list of entities that can be
10557       // explicitly specialized.
10558       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10559         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10560             << /*explicit specialization*/ 1;
10561     }
10562 
10563     // Find any virtual functions that this function overrides.
10564     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10565       if (!Method->isFunctionTemplateSpecialization() &&
10566           !Method->getDescribedFunctionTemplate() &&
10567           Method->isCanonicalDecl()) {
10568         if (AddOverriddenMethods(Method->getParent(), Method)) {
10569           // If the function was marked as "static", we have a problem.
10570           if (NewFD->getStorageClass() == SC_Static) {
10571             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10572           }
10573         }
10574       }
10575 
10576       if (Method->isStatic())
10577         checkThisInStaticMemberFunctionType(Method);
10578     }
10579 
10580     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10581     if (NewFD->isOverloadedOperator() &&
10582         CheckOverloadedOperatorDeclaration(NewFD)) {
10583       NewFD->setInvalidDecl();
10584       return Redeclaration;
10585     }
10586 
10587     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10588     if (NewFD->getLiteralIdentifier() &&
10589         CheckLiteralOperatorDeclaration(NewFD)) {
10590       NewFD->setInvalidDecl();
10591       return Redeclaration;
10592     }
10593 
10594     // In C++, check default arguments now that we have merged decls. Unless
10595     // the lexical context is the class, because in this case this is done
10596     // during delayed parsing anyway.
10597     if (!CurContext->isRecord())
10598       CheckCXXDefaultArguments(NewFD);
10599 
10600     // If this function declares a builtin function, check the type of this
10601     // declaration against the expected type for the builtin.
10602     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10603       ASTContext::GetBuiltinTypeError Error;
10604       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10605       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10606       // If the type of the builtin differs only in its exception
10607       // specification, that's OK.
10608       // FIXME: If the types do differ in this way, it would be better to
10609       // retain the 'noexcept' form of the type.
10610       if (!T.isNull() &&
10611           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10612                                                             NewFD->getType()))
10613         // The type of this function differs from the type of the builtin,
10614         // so forget about the builtin entirely.
10615         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10616     }
10617 
10618     // If this function is declared as being extern "C", then check to see if
10619     // the function returns a UDT (class, struct, or union type) that is not C
10620     // compatible, and if it does, warn the user.
10621     // But, issue any diagnostic on the first declaration only.
10622     if (Previous.empty() && NewFD->isExternC()) {
10623       QualType R = NewFD->getReturnType();
10624       if (R->isIncompleteType() && !R->isVoidType())
10625         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10626             << NewFD << R;
10627       else if (!R.isPODType(Context) && !R->isVoidType() &&
10628                !R->isObjCObjectPointerType())
10629         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10630     }
10631 
10632     // C++1z [dcl.fct]p6:
10633     //   [...] whether the function has a non-throwing exception-specification
10634     //   [is] part of the function type
10635     //
10636     // This results in an ABI break between C++14 and C++17 for functions whose
10637     // declared type includes an exception-specification in a parameter or
10638     // return type. (Exception specifications on the function itself are OK in
10639     // most cases, and exception specifications are not permitted in most other
10640     // contexts where they could make it into a mangling.)
10641     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10642       auto HasNoexcept = [&](QualType T) -> bool {
10643         // Strip off declarator chunks that could be between us and a function
10644         // type. We don't need to look far, exception specifications are very
10645         // restricted prior to C++17.
10646         if (auto *RT = T->getAs<ReferenceType>())
10647           T = RT->getPointeeType();
10648         else if (T->isAnyPointerType())
10649           T = T->getPointeeType();
10650         else if (auto *MPT = T->getAs<MemberPointerType>())
10651           T = MPT->getPointeeType();
10652         if (auto *FPT = T->getAs<FunctionProtoType>())
10653           if (FPT->isNothrow())
10654             return true;
10655         return false;
10656       };
10657 
10658       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10659       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10660       for (QualType T : FPT->param_types())
10661         AnyNoexcept |= HasNoexcept(T);
10662       if (AnyNoexcept)
10663         Diag(NewFD->getLocation(),
10664              diag::warn_cxx17_compat_exception_spec_in_signature)
10665             << NewFD;
10666     }
10667 
10668     if (!Redeclaration && LangOpts.CUDA)
10669       checkCUDATargetOverload(NewFD, Previous);
10670   }
10671   return Redeclaration;
10672 }
10673 
10674 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10675   // C++11 [basic.start.main]p3:
10676   //   A program that [...] declares main to be inline, static or
10677   //   constexpr is ill-formed.
10678   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10679   //   appear in a declaration of main.
10680   // static main is not an error under C99, but we should warn about it.
10681   // We accept _Noreturn main as an extension.
10682   if (FD->getStorageClass() == SC_Static)
10683     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10684          ? diag::err_static_main : diag::warn_static_main)
10685       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10686   if (FD->isInlineSpecified())
10687     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10688       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10689   if (DS.isNoreturnSpecified()) {
10690     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10691     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10692     Diag(NoreturnLoc, diag::ext_noreturn_main);
10693     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10694       << FixItHint::CreateRemoval(NoreturnRange);
10695   }
10696   if (FD->isConstexpr()) {
10697     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10698         << FD->isConsteval()
10699         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10700     FD->setConstexprKind(CSK_unspecified);
10701   }
10702 
10703   if (getLangOpts().OpenCL) {
10704     Diag(FD->getLocation(), diag::err_opencl_no_main)
10705         << FD->hasAttr<OpenCLKernelAttr>();
10706     FD->setInvalidDecl();
10707     return;
10708   }
10709 
10710   QualType T = FD->getType();
10711   assert(T->isFunctionType() && "function decl is not of function type");
10712   const FunctionType* FT = T->castAs<FunctionType>();
10713 
10714   // Set default calling convention for main()
10715   if (FT->getCallConv() != CC_C) {
10716     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10717     FD->setType(QualType(FT, 0));
10718     T = Context.getCanonicalType(FD->getType());
10719   }
10720 
10721   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10722     // In C with GNU extensions we allow main() to have non-integer return
10723     // type, but we should warn about the extension, and we disable the
10724     // implicit-return-zero rule.
10725 
10726     // GCC in C mode accepts qualified 'int'.
10727     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10728       FD->setHasImplicitReturnZero(true);
10729     else {
10730       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10731       SourceRange RTRange = FD->getReturnTypeSourceRange();
10732       if (RTRange.isValid())
10733         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10734             << FixItHint::CreateReplacement(RTRange, "int");
10735     }
10736   } else {
10737     // In C and C++, main magically returns 0 if you fall off the end;
10738     // set the flag which tells us that.
10739     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10740 
10741     // All the standards say that main() should return 'int'.
10742     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10743       FD->setHasImplicitReturnZero(true);
10744     else {
10745       // Otherwise, this is just a flat-out error.
10746       SourceRange RTRange = FD->getReturnTypeSourceRange();
10747       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10748           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10749                                 : FixItHint());
10750       FD->setInvalidDecl(true);
10751     }
10752   }
10753 
10754   // Treat protoless main() as nullary.
10755   if (isa<FunctionNoProtoType>(FT)) return;
10756 
10757   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10758   unsigned nparams = FTP->getNumParams();
10759   assert(FD->getNumParams() == nparams);
10760 
10761   bool HasExtraParameters = (nparams > 3);
10762 
10763   if (FTP->isVariadic()) {
10764     Diag(FD->getLocation(), diag::ext_variadic_main);
10765     // FIXME: if we had information about the location of the ellipsis, we
10766     // could add a FixIt hint to remove it as a parameter.
10767   }
10768 
10769   // Darwin passes an undocumented fourth argument of type char**.  If
10770   // other platforms start sprouting these, the logic below will start
10771   // getting shifty.
10772   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10773     HasExtraParameters = false;
10774 
10775   if (HasExtraParameters) {
10776     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10777     FD->setInvalidDecl(true);
10778     nparams = 3;
10779   }
10780 
10781   // FIXME: a lot of the following diagnostics would be improved
10782   // if we had some location information about types.
10783 
10784   QualType CharPP =
10785     Context.getPointerType(Context.getPointerType(Context.CharTy));
10786   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10787 
10788   for (unsigned i = 0; i < nparams; ++i) {
10789     QualType AT = FTP->getParamType(i);
10790 
10791     bool mismatch = true;
10792 
10793     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10794       mismatch = false;
10795     else if (Expected[i] == CharPP) {
10796       // As an extension, the following forms are okay:
10797       //   char const **
10798       //   char const * const *
10799       //   char * const *
10800 
10801       QualifierCollector qs;
10802       const PointerType* PT;
10803       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10804           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10805           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10806                               Context.CharTy)) {
10807         qs.removeConst();
10808         mismatch = !qs.empty();
10809       }
10810     }
10811 
10812     if (mismatch) {
10813       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10814       // TODO: suggest replacing given type with expected type
10815       FD->setInvalidDecl(true);
10816     }
10817   }
10818 
10819   if (nparams == 1 && !FD->isInvalidDecl()) {
10820     Diag(FD->getLocation(), diag::warn_main_one_arg);
10821   }
10822 
10823   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10824     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10825     FD->setInvalidDecl();
10826   }
10827 }
10828 
10829 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10830   QualType T = FD->getType();
10831   assert(T->isFunctionType() && "function decl is not of function type");
10832   const FunctionType *FT = T->castAs<FunctionType>();
10833 
10834   // Set an implicit return of 'zero' if the function can return some integral,
10835   // enumeration, pointer or nullptr type.
10836   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10837       FT->getReturnType()->isAnyPointerType() ||
10838       FT->getReturnType()->isNullPtrType())
10839     // DllMain is exempt because a return value of zero means it failed.
10840     if (FD->getName() != "DllMain")
10841       FD->setHasImplicitReturnZero(true);
10842 
10843   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10844     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10845     FD->setInvalidDecl();
10846   }
10847 }
10848 
10849 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10850   // FIXME: Need strict checking.  In C89, we need to check for
10851   // any assignment, increment, decrement, function-calls, or
10852   // commas outside of a sizeof.  In C99, it's the same list,
10853   // except that the aforementioned are allowed in unevaluated
10854   // expressions.  Everything else falls under the
10855   // "may accept other forms of constant expressions" exception.
10856   // (We never end up here for C++, so the constant expression
10857   // rules there don't matter.)
10858   const Expr *Culprit;
10859   if (Init->isConstantInitializer(Context, false, &Culprit))
10860     return false;
10861   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10862     << Culprit->getSourceRange();
10863   return true;
10864 }
10865 
10866 namespace {
10867   // Visits an initialization expression to see if OrigDecl is evaluated in
10868   // its own initialization and throws a warning if it does.
10869   class SelfReferenceChecker
10870       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10871     Sema &S;
10872     Decl *OrigDecl;
10873     bool isRecordType;
10874     bool isPODType;
10875     bool isReferenceType;
10876 
10877     bool isInitList;
10878     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10879 
10880   public:
10881     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10882 
10883     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10884                                                     S(S), OrigDecl(OrigDecl) {
10885       isPODType = false;
10886       isRecordType = false;
10887       isReferenceType = false;
10888       isInitList = false;
10889       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10890         isPODType = VD->getType().isPODType(S.Context);
10891         isRecordType = VD->getType()->isRecordType();
10892         isReferenceType = VD->getType()->isReferenceType();
10893       }
10894     }
10895 
10896     // For most expressions, just call the visitor.  For initializer lists,
10897     // track the index of the field being initialized since fields are
10898     // initialized in order allowing use of previously initialized fields.
10899     void CheckExpr(Expr *E) {
10900       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10901       if (!InitList) {
10902         Visit(E);
10903         return;
10904       }
10905 
10906       // Track and increment the index here.
10907       isInitList = true;
10908       InitFieldIndex.push_back(0);
10909       for (auto Child : InitList->children()) {
10910         CheckExpr(cast<Expr>(Child));
10911         ++InitFieldIndex.back();
10912       }
10913       InitFieldIndex.pop_back();
10914     }
10915 
10916     // Returns true if MemberExpr is checked and no further checking is needed.
10917     // Returns false if additional checking is required.
10918     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10919       llvm::SmallVector<FieldDecl*, 4> Fields;
10920       Expr *Base = E;
10921       bool ReferenceField = false;
10922 
10923       // Get the field members used.
10924       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10925         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10926         if (!FD)
10927           return false;
10928         Fields.push_back(FD);
10929         if (FD->getType()->isReferenceType())
10930           ReferenceField = true;
10931         Base = ME->getBase()->IgnoreParenImpCasts();
10932       }
10933 
10934       // Keep checking only if the base Decl is the same.
10935       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10936       if (!DRE || DRE->getDecl() != OrigDecl)
10937         return false;
10938 
10939       // A reference field can be bound to an unininitialized field.
10940       if (CheckReference && !ReferenceField)
10941         return true;
10942 
10943       // Convert FieldDecls to their index number.
10944       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10945       for (const FieldDecl *I : llvm::reverse(Fields))
10946         UsedFieldIndex.push_back(I->getFieldIndex());
10947 
10948       // See if a warning is needed by checking the first difference in index
10949       // numbers.  If field being used has index less than the field being
10950       // initialized, then the use is safe.
10951       for (auto UsedIter = UsedFieldIndex.begin(),
10952                 UsedEnd = UsedFieldIndex.end(),
10953                 OrigIter = InitFieldIndex.begin(),
10954                 OrigEnd = InitFieldIndex.end();
10955            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10956         if (*UsedIter < *OrigIter)
10957           return true;
10958         if (*UsedIter > *OrigIter)
10959           break;
10960       }
10961 
10962       // TODO: Add a different warning which will print the field names.
10963       HandleDeclRefExpr(DRE);
10964       return true;
10965     }
10966 
10967     // For most expressions, the cast is directly above the DeclRefExpr.
10968     // For conditional operators, the cast can be outside the conditional
10969     // operator if both expressions are DeclRefExpr's.
10970     void HandleValue(Expr *E) {
10971       E = E->IgnoreParens();
10972       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10973         HandleDeclRefExpr(DRE);
10974         return;
10975       }
10976 
10977       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10978         Visit(CO->getCond());
10979         HandleValue(CO->getTrueExpr());
10980         HandleValue(CO->getFalseExpr());
10981         return;
10982       }
10983 
10984       if (BinaryConditionalOperator *BCO =
10985               dyn_cast<BinaryConditionalOperator>(E)) {
10986         Visit(BCO->getCond());
10987         HandleValue(BCO->getFalseExpr());
10988         return;
10989       }
10990 
10991       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10992         HandleValue(OVE->getSourceExpr());
10993         return;
10994       }
10995 
10996       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10997         if (BO->getOpcode() == BO_Comma) {
10998           Visit(BO->getLHS());
10999           HandleValue(BO->getRHS());
11000           return;
11001         }
11002       }
11003 
11004       if (isa<MemberExpr>(E)) {
11005         if (isInitList) {
11006           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11007                                       false /*CheckReference*/))
11008             return;
11009         }
11010 
11011         Expr *Base = E->IgnoreParenImpCasts();
11012         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11013           // Check for static member variables and don't warn on them.
11014           if (!isa<FieldDecl>(ME->getMemberDecl()))
11015             return;
11016           Base = ME->getBase()->IgnoreParenImpCasts();
11017         }
11018         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11019           HandleDeclRefExpr(DRE);
11020         return;
11021       }
11022 
11023       Visit(E);
11024     }
11025 
11026     // Reference types not handled in HandleValue are handled here since all
11027     // uses of references are bad, not just r-value uses.
11028     void VisitDeclRefExpr(DeclRefExpr *E) {
11029       if (isReferenceType)
11030         HandleDeclRefExpr(E);
11031     }
11032 
11033     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11034       if (E->getCastKind() == CK_LValueToRValue) {
11035         HandleValue(E->getSubExpr());
11036         return;
11037       }
11038 
11039       Inherited::VisitImplicitCastExpr(E);
11040     }
11041 
11042     void VisitMemberExpr(MemberExpr *E) {
11043       if (isInitList) {
11044         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11045           return;
11046       }
11047 
11048       // Don't warn on arrays since they can be treated as pointers.
11049       if (E->getType()->canDecayToPointerType()) return;
11050 
11051       // Warn when a non-static method call is followed by non-static member
11052       // field accesses, which is followed by a DeclRefExpr.
11053       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11054       bool Warn = (MD && !MD->isStatic());
11055       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11056       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11057         if (!isa<FieldDecl>(ME->getMemberDecl()))
11058           Warn = false;
11059         Base = ME->getBase()->IgnoreParenImpCasts();
11060       }
11061 
11062       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11063         if (Warn)
11064           HandleDeclRefExpr(DRE);
11065         return;
11066       }
11067 
11068       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11069       // Visit that expression.
11070       Visit(Base);
11071     }
11072 
11073     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11074       Expr *Callee = E->getCallee();
11075 
11076       if (isa<UnresolvedLookupExpr>(Callee))
11077         return Inherited::VisitCXXOperatorCallExpr(E);
11078 
11079       Visit(Callee);
11080       for (auto Arg: E->arguments())
11081         HandleValue(Arg->IgnoreParenImpCasts());
11082     }
11083 
11084     void VisitUnaryOperator(UnaryOperator *E) {
11085       // For POD record types, addresses of its own members are well-defined.
11086       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11087           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11088         if (!isPODType)
11089           HandleValue(E->getSubExpr());
11090         return;
11091       }
11092 
11093       if (E->isIncrementDecrementOp()) {
11094         HandleValue(E->getSubExpr());
11095         return;
11096       }
11097 
11098       Inherited::VisitUnaryOperator(E);
11099     }
11100 
11101     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11102 
11103     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11104       if (E->getConstructor()->isCopyConstructor()) {
11105         Expr *ArgExpr = E->getArg(0);
11106         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11107           if (ILE->getNumInits() == 1)
11108             ArgExpr = ILE->getInit(0);
11109         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11110           if (ICE->getCastKind() == CK_NoOp)
11111             ArgExpr = ICE->getSubExpr();
11112         HandleValue(ArgExpr);
11113         return;
11114       }
11115       Inherited::VisitCXXConstructExpr(E);
11116     }
11117 
11118     void VisitCallExpr(CallExpr *E) {
11119       // Treat std::move as a use.
11120       if (E->isCallToStdMove()) {
11121         HandleValue(E->getArg(0));
11122         return;
11123       }
11124 
11125       Inherited::VisitCallExpr(E);
11126     }
11127 
11128     void VisitBinaryOperator(BinaryOperator *E) {
11129       if (E->isCompoundAssignmentOp()) {
11130         HandleValue(E->getLHS());
11131         Visit(E->getRHS());
11132         return;
11133       }
11134 
11135       Inherited::VisitBinaryOperator(E);
11136     }
11137 
11138     // A custom visitor for BinaryConditionalOperator is needed because the
11139     // regular visitor would check the condition and true expression separately
11140     // but both point to the same place giving duplicate diagnostics.
11141     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11142       Visit(E->getCond());
11143       Visit(E->getFalseExpr());
11144     }
11145 
11146     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11147       Decl* ReferenceDecl = DRE->getDecl();
11148       if (OrigDecl != ReferenceDecl) return;
11149       unsigned diag;
11150       if (isReferenceType) {
11151         diag = diag::warn_uninit_self_reference_in_reference_init;
11152       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11153         diag = diag::warn_static_self_reference_in_init;
11154       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11155                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11156                  DRE->getDecl()->getType()->isRecordType()) {
11157         diag = diag::warn_uninit_self_reference_in_init;
11158       } else {
11159         // Local variables will be handled by the CFG analysis.
11160         return;
11161       }
11162 
11163       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11164                             S.PDiag(diag)
11165                                 << DRE->getDecl() << OrigDecl->getLocation()
11166                                 << DRE->getSourceRange());
11167     }
11168   };
11169 
11170   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11171   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11172                                  bool DirectInit) {
11173     // Parameters arguments are occassionially constructed with itself,
11174     // for instance, in recursive functions.  Skip them.
11175     if (isa<ParmVarDecl>(OrigDecl))
11176       return;
11177 
11178     E = E->IgnoreParens();
11179 
11180     // Skip checking T a = a where T is not a record or reference type.
11181     // Doing so is a way to silence uninitialized warnings.
11182     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11183       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11184         if (ICE->getCastKind() == CK_LValueToRValue)
11185           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11186             if (DRE->getDecl() == OrigDecl)
11187               return;
11188 
11189     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11190   }
11191 } // end anonymous namespace
11192 
11193 namespace {
11194   // Simple wrapper to add the name of a variable or (if no variable is
11195   // available) a DeclarationName into a diagnostic.
11196   struct VarDeclOrName {
11197     VarDecl *VDecl;
11198     DeclarationName Name;
11199 
11200     friend const Sema::SemaDiagnosticBuilder &
11201     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11202       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11203     }
11204   };
11205 } // end anonymous namespace
11206 
11207 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11208                                             DeclarationName Name, QualType Type,
11209                                             TypeSourceInfo *TSI,
11210                                             SourceRange Range, bool DirectInit,
11211                                             Expr *Init) {
11212   bool IsInitCapture = !VDecl;
11213   assert((!VDecl || !VDecl->isInitCapture()) &&
11214          "init captures are expected to be deduced prior to initialization");
11215 
11216   VarDeclOrName VN{VDecl, Name};
11217 
11218   DeducedType *Deduced = Type->getContainedDeducedType();
11219   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11220 
11221   // C++11 [dcl.spec.auto]p3
11222   if (!Init) {
11223     assert(VDecl && "no init for init capture deduction?");
11224 
11225     // Except for class argument deduction, and then for an initializing
11226     // declaration only, i.e. no static at class scope or extern.
11227     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11228         VDecl->hasExternalStorage() ||
11229         VDecl->isStaticDataMember()) {
11230       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11231         << VDecl->getDeclName() << Type;
11232       return QualType();
11233     }
11234   }
11235 
11236   ArrayRef<Expr*> DeduceInits;
11237   if (Init)
11238     DeduceInits = Init;
11239 
11240   if (DirectInit) {
11241     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11242       DeduceInits = PL->exprs();
11243   }
11244 
11245   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11246     assert(VDecl && "non-auto type for init capture deduction?");
11247     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11248     InitializationKind Kind = InitializationKind::CreateForInit(
11249         VDecl->getLocation(), DirectInit, Init);
11250     // FIXME: Initialization should not be taking a mutable list of inits.
11251     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11252     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11253                                                        InitsCopy);
11254   }
11255 
11256   if (DirectInit) {
11257     if (auto *IL = dyn_cast<InitListExpr>(Init))
11258       DeduceInits = IL->inits();
11259   }
11260 
11261   // Deduction only works if we have exactly one source expression.
11262   if (DeduceInits.empty()) {
11263     // It isn't possible to write this directly, but it is possible to
11264     // end up in this situation with "auto x(some_pack...);"
11265     Diag(Init->getBeginLoc(), IsInitCapture
11266                                   ? diag::err_init_capture_no_expression
11267                                   : diag::err_auto_var_init_no_expression)
11268         << VN << Type << Range;
11269     return QualType();
11270   }
11271 
11272   if (DeduceInits.size() > 1) {
11273     Diag(DeduceInits[1]->getBeginLoc(),
11274          IsInitCapture ? diag::err_init_capture_multiple_expressions
11275                        : diag::err_auto_var_init_multiple_expressions)
11276         << VN << Type << Range;
11277     return QualType();
11278   }
11279 
11280   Expr *DeduceInit = DeduceInits[0];
11281   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11282     Diag(Init->getBeginLoc(), IsInitCapture
11283                                   ? diag::err_init_capture_paren_braces
11284                                   : diag::err_auto_var_init_paren_braces)
11285         << isa<InitListExpr>(Init) << VN << Type << Range;
11286     return QualType();
11287   }
11288 
11289   // Expressions default to 'id' when we're in a debugger.
11290   bool DefaultedAnyToId = false;
11291   if (getLangOpts().DebuggerCastResultToId &&
11292       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11293     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11294     if (Result.isInvalid()) {
11295       return QualType();
11296     }
11297     Init = Result.get();
11298     DefaultedAnyToId = true;
11299   }
11300 
11301   // C++ [dcl.decomp]p1:
11302   //   If the assignment-expression [...] has array type A and no ref-qualifier
11303   //   is present, e has type cv A
11304   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11305       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11306       DeduceInit->getType()->isConstantArrayType())
11307     return Context.getQualifiedType(DeduceInit->getType(),
11308                                     Type.getQualifiers());
11309 
11310   QualType DeducedType;
11311   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11312     if (!IsInitCapture)
11313       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11314     else if (isa<InitListExpr>(Init))
11315       Diag(Range.getBegin(),
11316            diag::err_init_capture_deduction_failure_from_init_list)
11317           << VN
11318           << (DeduceInit->getType().isNull() ? TSI->getType()
11319                                              : DeduceInit->getType())
11320           << DeduceInit->getSourceRange();
11321     else
11322       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11323           << VN << TSI->getType()
11324           << (DeduceInit->getType().isNull() ? TSI->getType()
11325                                              : DeduceInit->getType())
11326           << DeduceInit->getSourceRange();
11327   }
11328 
11329   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11330   // 'id' instead of a specific object type prevents most of our usual
11331   // checks.
11332   // We only want to warn outside of template instantiations, though:
11333   // inside a template, the 'id' could have come from a parameter.
11334   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11335       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11336     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11337     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11338   }
11339 
11340   return DeducedType;
11341 }
11342 
11343 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11344                                          Expr *Init) {
11345   QualType DeducedType = deduceVarTypeFromInitializer(
11346       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11347       VDecl->getSourceRange(), DirectInit, Init);
11348   if (DeducedType.isNull()) {
11349     VDecl->setInvalidDecl();
11350     return true;
11351   }
11352 
11353   VDecl->setType(DeducedType);
11354   assert(VDecl->isLinkageValid());
11355 
11356   // In ARC, infer lifetime.
11357   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11358     VDecl->setInvalidDecl();
11359 
11360   if (getLangOpts().OpenCL)
11361     deduceOpenCLAddressSpace(VDecl);
11362 
11363   // If this is a redeclaration, check that the type we just deduced matches
11364   // the previously declared type.
11365   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11366     // We never need to merge the type, because we cannot form an incomplete
11367     // array of auto, nor deduce such a type.
11368     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11369   }
11370 
11371   // Check the deduced type is valid for a variable declaration.
11372   CheckVariableDeclarationType(VDecl);
11373   return VDecl->isInvalidDecl();
11374 }
11375 
11376 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11377                                               SourceLocation Loc) {
11378   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11379     Init = CE->getSubExpr();
11380 
11381   QualType InitType = Init->getType();
11382   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11383           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11384          "shouldn't be called if type doesn't have a non-trivial C struct");
11385   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11386     for (auto I : ILE->inits()) {
11387       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11388           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11389         continue;
11390       SourceLocation SL = I->getExprLoc();
11391       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11392     }
11393     return;
11394   }
11395 
11396   if (isa<ImplicitValueInitExpr>(Init)) {
11397     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11398       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11399                             NTCUK_Init);
11400   } else {
11401     // Assume all other explicit initializers involving copying some existing
11402     // object.
11403     // TODO: ignore any explicit initializers where we can guarantee
11404     // copy-elision.
11405     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11406       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11407   }
11408 }
11409 
11410 namespace {
11411 
11412 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11413   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11414   // in the source code or implicitly by the compiler if it is in a union
11415   // defined in a system header and has non-trivial ObjC ownership
11416   // qualifications. We don't want those fields to participate in determining
11417   // whether the containing union is non-trivial.
11418   return FD->hasAttr<UnavailableAttr>();
11419 }
11420 
11421 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11422     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11423                                     void> {
11424   using Super =
11425       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11426                                     void>;
11427 
11428   DiagNonTrivalCUnionDefaultInitializeVisitor(
11429       QualType OrigTy, SourceLocation OrigLoc,
11430       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11431       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11432 
11433   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11434                      const FieldDecl *FD, bool InNonTrivialUnion) {
11435     if (const auto *AT = S.Context.getAsArrayType(QT))
11436       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11437                                      InNonTrivialUnion);
11438     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11439   }
11440 
11441   void visitARCStrong(QualType QT, const FieldDecl *FD,
11442                       bool InNonTrivialUnion) {
11443     if (InNonTrivialUnion)
11444       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11445           << 1 << 0 << QT << FD->getName();
11446   }
11447 
11448   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11449     if (InNonTrivialUnion)
11450       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11451           << 1 << 0 << QT << FD->getName();
11452   }
11453 
11454   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11455     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11456     if (RD->isUnion()) {
11457       if (OrigLoc.isValid()) {
11458         bool IsUnion = false;
11459         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11460           IsUnion = OrigRD->isUnion();
11461         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11462             << 0 << OrigTy << IsUnion << UseContext;
11463         // Reset OrigLoc so that this diagnostic is emitted only once.
11464         OrigLoc = SourceLocation();
11465       }
11466       InNonTrivialUnion = true;
11467     }
11468 
11469     if (InNonTrivialUnion)
11470       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11471           << 0 << 0 << QT.getUnqualifiedType() << "";
11472 
11473     for (const FieldDecl *FD : RD->fields())
11474       if (!shouldIgnoreForRecordTriviality(FD))
11475         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11476   }
11477 
11478   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11479 
11480   // The non-trivial C union type or the struct/union type that contains a
11481   // non-trivial C union.
11482   QualType OrigTy;
11483   SourceLocation OrigLoc;
11484   Sema::NonTrivialCUnionContext UseContext;
11485   Sema &S;
11486 };
11487 
11488 struct DiagNonTrivalCUnionDestructedTypeVisitor
11489     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11490   using Super =
11491       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11492 
11493   DiagNonTrivalCUnionDestructedTypeVisitor(
11494       QualType OrigTy, SourceLocation OrigLoc,
11495       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11496       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11497 
11498   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11499                      const FieldDecl *FD, bool InNonTrivialUnion) {
11500     if (const auto *AT = S.Context.getAsArrayType(QT))
11501       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11502                                      InNonTrivialUnion);
11503     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11504   }
11505 
11506   void visitARCStrong(QualType QT, const FieldDecl *FD,
11507                       bool InNonTrivialUnion) {
11508     if (InNonTrivialUnion)
11509       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11510           << 1 << 1 << QT << FD->getName();
11511   }
11512 
11513   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11514     if (InNonTrivialUnion)
11515       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11516           << 1 << 1 << QT << FD->getName();
11517   }
11518 
11519   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11520     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11521     if (RD->isUnion()) {
11522       if (OrigLoc.isValid()) {
11523         bool IsUnion = false;
11524         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11525           IsUnion = OrigRD->isUnion();
11526         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11527             << 1 << OrigTy << IsUnion << UseContext;
11528         // Reset OrigLoc so that this diagnostic is emitted only once.
11529         OrigLoc = SourceLocation();
11530       }
11531       InNonTrivialUnion = true;
11532     }
11533 
11534     if (InNonTrivialUnion)
11535       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11536           << 0 << 1 << QT.getUnqualifiedType() << "";
11537 
11538     for (const FieldDecl *FD : RD->fields())
11539       if (!shouldIgnoreForRecordTriviality(FD))
11540         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11541   }
11542 
11543   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11544   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11545                           bool InNonTrivialUnion) {}
11546 
11547   // The non-trivial C union type or the struct/union type that contains a
11548   // non-trivial C union.
11549   QualType OrigTy;
11550   SourceLocation OrigLoc;
11551   Sema::NonTrivialCUnionContext UseContext;
11552   Sema &S;
11553 };
11554 
11555 struct DiagNonTrivalCUnionCopyVisitor
11556     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11557   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11558 
11559   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11560                                  Sema::NonTrivialCUnionContext UseContext,
11561                                  Sema &S)
11562       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11563 
11564   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11565                      const FieldDecl *FD, bool InNonTrivialUnion) {
11566     if (const auto *AT = S.Context.getAsArrayType(QT))
11567       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11568                                      InNonTrivialUnion);
11569     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11570   }
11571 
11572   void visitARCStrong(QualType QT, const FieldDecl *FD,
11573                       bool InNonTrivialUnion) {
11574     if (InNonTrivialUnion)
11575       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11576           << 1 << 2 << QT << FD->getName();
11577   }
11578 
11579   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11580     if (InNonTrivialUnion)
11581       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11582           << 1 << 2 << QT << FD->getName();
11583   }
11584 
11585   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11586     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11587     if (RD->isUnion()) {
11588       if (OrigLoc.isValid()) {
11589         bool IsUnion = false;
11590         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11591           IsUnion = OrigRD->isUnion();
11592         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11593             << 2 << OrigTy << IsUnion << UseContext;
11594         // Reset OrigLoc so that this diagnostic is emitted only once.
11595         OrigLoc = SourceLocation();
11596       }
11597       InNonTrivialUnion = true;
11598     }
11599 
11600     if (InNonTrivialUnion)
11601       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11602           << 0 << 2 << QT.getUnqualifiedType() << "";
11603 
11604     for (const FieldDecl *FD : RD->fields())
11605       if (!shouldIgnoreForRecordTriviality(FD))
11606         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11607   }
11608 
11609   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11610                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11611   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11612   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11613                             bool InNonTrivialUnion) {}
11614 
11615   // The non-trivial C union type or the struct/union type that contains a
11616   // non-trivial C union.
11617   QualType OrigTy;
11618   SourceLocation OrigLoc;
11619   Sema::NonTrivialCUnionContext UseContext;
11620   Sema &S;
11621 };
11622 
11623 } // namespace
11624 
11625 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11626                                  NonTrivialCUnionContext UseContext,
11627                                  unsigned NonTrivialKind) {
11628   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11629           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11630           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11631          "shouldn't be called if type doesn't have a non-trivial C union");
11632 
11633   if ((NonTrivialKind & NTCUK_Init) &&
11634       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11635     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11636         .visit(QT, nullptr, false);
11637   if ((NonTrivialKind & NTCUK_Destruct) &&
11638       QT.hasNonTrivialToPrimitiveDestructCUnion())
11639     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11640         .visit(QT, nullptr, false);
11641   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11642     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11643         .visit(QT, nullptr, false);
11644 }
11645 
11646 /// AddInitializerToDecl - Adds the initializer Init to the
11647 /// declaration dcl. If DirectInit is true, this is C++ direct
11648 /// initialization rather than copy initialization.
11649 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11650   // If there is no declaration, there was an error parsing it.  Just ignore
11651   // the initializer.
11652   if (!RealDecl || RealDecl->isInvalidDecl()) {
11653     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11654     return;
11655   }
11656 
11657   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11658     // Pure-specifiers are handled in ActOnPureSpecifier.
11659     Diag(Method->getLocation(), diag::err_member_function_initialization)
11660       << Method->getDeclName() << Init->getSourceRange();
11661     Method->setInvalidDecl();
11662     return;
11663   }
11664 
11665   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11666   if (!VDecl) {
11667     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11668     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11669     RealDecl->setInvalidDecl();
11670     return;
11671   }
11672 
11673   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11674   if (VDecl->getType()->isUndeducedType()) {
11675     // Attempt typo correction early so that the type of the init expression can
11676     // be deduced based on the chosen correction if the original init contains a
11677     // TypoExpr.
11678     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11679     if (!Res.isUsable()) {
11680       RealDecl->setInvalidDecl();
11681       return;
11682     }
11683     Init = Res.get();
11684 
11685     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11686       return;
11687   }
11688 
11689   // dllimport cannot be used on variable definitions.
11690   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11691     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11692     VDecl->setInvalidDecl();
11693     return;
11694   }
11695 
11696   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11697     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11698     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11699     VDecl->setInvalidDecl();
11700     return;
11701   }
11702 
11703   if (!VDecl->getType()->isDependentType()) {
11704     // A definition must end up with a complete type, which means it must be
11705     // complete with the restriction that an array type might be completed by
11706     // the initializer; note that later code assumes this restriction.
11707     QualType BaseDeclType = VDecl->getType();
11708     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11709       BaseDeclType = Array->getElementType();
11710     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11711                             diag::err_typecheck_decl_incomplete_type)) {
11712       RealDecl->setInvalidDecl();
11713       return;
11714     }
11715 
11716     // The variable can not have an abstract class type.
11717     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11718                                diag::err_abstract_type_in_decl,
11719                                AbstractVariableType))
11720       VDecl->setInvalidDecl();
11721   }
11722 
11723   // If adding the initializer will turn this declaration into a definition,
11724   // and we already have a definition for this variable, diagnose or otherwise
11725   // handle the situation.
11726   VarDecl *Def;
11727   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11728       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11729       !VDecl->isThisDeclarationADemotedDefinition() &&
11730       checkVarDeclRedefinition(Def, VDecl))
11731     return;
11732 
11733   if (getLangOpts().CPlusPlus) {
11734     // C++ [class.static.data]p4
11735     //   If a static data member is of const integral or const
11736     //   enumeration type, its declaration in the class definition can
11737     //   specify a constant-initializer which shall be an integral
11738     //   constant expression (5.19). In that case, the member can appear
11739     //   in integral constant expressions. The member shall still be
11740     //   defined in a namespace scope if it is used in the program and the
11741     //   namespace scope definition shall not contain an initializer.
11742     //
11743     // We already performed a redefinition check above, but for static
11744     // data members we also need to check whether there was an in-class
11745     // declaration with an initializer.
11746     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11747       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11748           << VDecl->getDeclName();
11749       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11750            diag::note_previous_initializer)
11751           << 0;
11752       return;
11753     }
11754 
11755     if (VDecl->hasLocalStorage())
11756       setFunctionHasBranchProtectedScope();
11757 
11758     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11759       VDecl->setInvalidDecl();
11760       return;
11761     }
11762   }
11763 
11764   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11765   // a kernel function cannot be initialized."
11766   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11767     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11768     VDecl->setInvalidDecl();
11769     return;
11770   }
11771 
11772   // Get the decls type and save a reference for later, since
11773   // CheckInitializerTypes may change it.
11774   QualType DclT = VDecl->getType(), SavT = DclT;
11775 
11776   // Expressions default to 'id' when we're in a debugger
11777   // and we are assigning it to a variable of Objective-C pointer type.
11778   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11779       Init->getType() == Context.UnknownAnyTy) {
11780     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11781     if (Result.isInvalid()) {
11782       VDecl->setInvalidDecl();
11783       return;
11784     }
11785     Init = Result.get();
11786   }
11787 
11788   // Perform the initialization.
11789   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11790   if (!VDecl->isInvalidDecl()) {
11791     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11792     InitializationKind Kind = InitializationKind::CreateForInit(
11793         VDecl->getLocation(), DirectInit, Init);
11794 
11795     MultiExprArg Args = Init;
11796     if (CXXDirectInit)
11797       Args = MultiExprArg(CXXDirectInit->getExprs(),
11798                           CXXDirectInit->getNumExprs());
11799 
11800     // Try to correct any TypoExprs in the initialization arguments.
11801     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11802       ExprResult Res = CorrectDelayedTyposInExpr(
11803           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11804             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11805             return Init.Failed() ? ExprError() : E;
11806           });
11807       if (Res.isInvalid()) {
11808         VDecl->setInvalidDecl();
11809       } else if (Res.get() != Args[Idx]) {
11810         Args[Idx] = Res.get();
11811       }
11812     }
11813     if (VDecl->isInvalidDecl())
11814       return;
11815 
11816     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11817                                    /*TopLevelOfInitList=*/false,
11818                                    /*TreatUnavailableAsInvalid=*/false);
11819     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11820     if (Result.isInvalid()) {
11821       VDecl->setInvalidDecl();
11822       return;
11823     }
11824 
11825     Init = Result.getAs<Expr>();
11826   }
11827 
11828   // Check for self-references within variable initializers.
11829   // Variables declared within a function/method body (except for references)
11830   // are handled by a dataflow analysis.
11831   // This is undefined behavior in C++, but valid in C.
11832   if (getLangOpts().CPlusPlus) {
11833     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11834         VDecl->getType()->isReferenceType()) {
11835       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11836     }
11837   }
11838 
11839   // If the type changed, it means we had an incomplete type that was
11840   // completed by the initializer. For example:
11841   //   int ary[] = { 1, 3, 5 };
11842   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11843   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11844     VDecl->setType(DclT);
11845 
11846   if (!VDecl->isInvalidDecl()) {
11847     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11848 
11849     if (VDecl->hasAttr<BlocksAttr>())
11850       checkRetainCycles(VDecl, Init);
11851 
11852     // It is safe to assign a weak reference into a strong variable.
11853     // Although this code can still have problems:
11854     //   id x = self.weakProp;
11855     //   id y = self.weakProp;
11856     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11857     // paths through the function. This should be revisited if
11858     // -Wrepeated-use-of-weak is made flow-sensitive.
11859     if (FunctionScopeInfo *FSI = getCurFunction())
11860       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11861            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11862           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11863                            Init->getBeginLoc()))
11864         FSI->markSafeWeakUse(Init);
11865   }
11866 
11867   // The initialization is usually a full-expression.
11868   //
11869   // FIXME: If this is a braced initialization of an aggregate, it is not
11870   // an expression, and each individual field initializer is a separate
11871   // full-expression. For instance, in:
11872   //
11873   //   struct Temp { ~Temp(); };
11874   //   struct S { S(Temp); };
11875   //   struct T { S a, b; } t = { Temp(), Temp() }
11876   //
11877   // we should destroy the first Temp before constructing the second.
11878   ExprResult Result =
11879       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11880                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11881   if (Result.isInvalid()) {
11882     VDecl->setInvalidDecl();
11883     return;
11884   }
11885   Init = Result.get();
11886 
11887   // Attach the initializer to the decl.
11888   VDecl->setInit(Init);
11889 
11890   if (VDecl->isLocalVarDecl()) {
11891     // Don't check the initializer if the declaration is malformed.
11892     if (VDecl->isInvalidDecl()) {
11893       // do nothing
11894 
11895     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11896     // This is true even in C++ for OpenCL.
11897     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11898       CheckForConstantInitializer(Init, DclT);
11899 
11900     // Otherwise, C++ does not restrict the initializer.
11901     } else if (getLangOpts().CPlusPlus) {
11902       // do nothing
11903 
11904     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11905     // static storage duration shall be constant expressions or string literals.
11906     } else if (VDecl->getStorageClass() == SC_Static) {
11907       CheckForConstantInitializer(Init, DclT);
11908 
11909     // C89 is stricter than C99 for aggregate initializers.
11910     // C89 6.5.7p3: All the expressions [...] in an initializer list
11911     // for an object that has aggregate or union type shall be
11912     // constant expressions.
11913     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11914                isa<InitListExpr>(Init)) {
11915       const Expr *Culprit;
11916       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11917         Diag(Culprit->getExprLoc(),
11918              diag::ext_aggregate_init_not_constant)
11919           << Culprit->getSourceRange();
11920       }
11921     }
11922 
11923     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11924       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11925         if (VDecl->hasLocalStorage())
11926           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11927   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11928              VDecl->getLexicalDeclContext()->isRecord()) {
11929     // This is an in-class initialization for a static data member, e.g.,
11930     //
11931     // struct S {
11932     //   static const int value = 17;
11933     // };
11934 
11935     // C++ [class.mem]p4:
11936     //   A member-declarator can contain a constant-initializer only
11937     //   if it declares a static member (9.4) of const integral or
11938     //   const enumeration type, see 9.4.2.
11939     //
11940     // C++11 [class.static.data]p3:
11941     //   If a non-volatile non-inline const static data member is of integral
11942     //   or enumeration type, its declaration in the class definition can
11943     //   specify a brace-or-equal-initializer in which every initializer-clause
11944     //   that is an assignment-expression is a constant expression. A static
11945     //   data member of literal type can be declared in the class definition
11946     //   with the constexpr specifier; if so, its declaration shall specify a
11947     //   brace-or-equal-initializer in which every initializer-clause that is
11948     //   an assignment-expression is a constant expression.
11949 
11950     // Do nothing on dependent types.
11951     if (DclT->isDependentType()) {
11952 
11953     // Allow any 'static constexpr' members, whether or not they are of literal
11954     // type. We separately check that every constexpr variable is of literal
11955     // type.
11956     } else if (VDecl->isConstexpr()) {
11957 
11958     // Require constness.
11959     } else if (!DclT.isConstQualified()) {
11960       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11961         << Init->getSourceRange();
11962       VDecl->setInvalidDecl();
11963 
11964     // We allow integer constant expressions in all cases.
11965     } else if (DclT->isIntegralOrEnumerationType()) {
11966       // Check whether the expression is a constant expression.
11967       SourceLocation Loc;
11968       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11969         // In C++11, a non-constexpr const static data member with an
11970         // in-class initializer cannot be volatile.
11971         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11972       else if (Init->isValueDependent())
11973         ; // Nothing to check.
11974       else if (Init->isIntegerConstantExpr(Context, &Loc))
11975         ; // Ok, it's an ICE!
11976       else if (Init->getType()->isScopedEnumeralType() &&
11977                Init->isCXX11ConstantExpr(Context))
11978         ; // Ok, it is a scoped-enum constant expression.
11979       else if (Init->isEvaluatable(Context)) {
11980         // If we can constant fold the initializer through heroics, accept it,
11981         // but report this as a use of an extension for -pedantic.
11982         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11983           << Init->getSourceRange();
11984       } else {
11985         // Otherwise, this is some crazy unknown case.  Report the issue at the
11986         // location provided by the isIntegerConstantExpr failed check.
11987         Diag(Loc, diag::err_in_class_initializer_non_constant)
11988           << Init->getSourceRange();
11989         VDecl->setInvalidDecl();
11990       }
11991 
11992     // We allow foldable floating-point constants as an extension.
11993     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11994       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11995       // it anyway and provide a fixit to add the 'constexpr'.
11996       if (getLangOpts().CPlusPlus11) {
11997         Diag(VDecl->getLocation(),
11998              diag::ext_in_class_initializer_float_type_cxx11)
11999             << DclT << Init->getSourceRange();
12000         Diag(VDecl->getBeginLoc(),
12001              diag::note_in_class_initializer_float_type_cxx11)
12002             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12003       } else {
12004         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12005           << DclT << Init->getSourceRange();
12006 
12007         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12008           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12009             << Init->getSourceRange();
12010           VDecl->setInvalidDecl();
12011         }
12012       }
12013 
12014     // Suggest adding 'constexpr' in C++11 for literal types.
12015     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12016       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12017           << DclT << Init->getSourceRange()
12018           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12019       VDecl->setConstexpr(true);
12020 
12021     } else {
12022       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12023         << DclT << Init->getSourceRange();
12024       VDecl->setInvalidDecl();
12025     }
12026   } else if (VDecl->isFileVarDecl()) {
12027     // In C, extern is typically used to avoid tentative definitions when
12028     // declaring variables in headers, but adding an intializer makes it a
12029     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12030     // In C++, extern is often used to give implictly static const variables
12031     // external linkage, so don't warn in that case. If selectany is present,
12032     // this might be header code intended for C and C++ inclusion, so apply the
12033     // C++ rules.
12034     if (VDecl->getStorageClass() == SC_Extern &&
12035         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12036          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12037         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12038         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12039       Diag(VDecl->getLocation(), diag::warn_extern_init);
12040 
12041     // In Microsoft C++ mode, a const variable defined in namespace scope has
12042     // external linkage by default if the variable is declared with
12043     // __declspec(dllexport).
12044     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12045         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12046         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12047       VDecl->setStorageClass(SC_Extern);
12048 
12049     // C99 6.7.8p4. All file scoped initializers need to be constant.
12050     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12051       CheckForConstantInitializer(Init, DclT);
12052   }
12053 
12054   QualType InitType = Init->getType();
12055   if (!InitType.isNull() &&
12056       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12057        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12058     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12059 
12060   // We will represent direct-initialization similarly to copy-initialization:
12061   //    int x(1);  -as-> int x = 1;
12062   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12063   //
12064   // Clients that want to distinguish between the two forms, can check for
12065   // direct initializer using VarDecl::getInitStyle().
12066   // A major benefit is that clients that don't particularly care about which
12067   // exactly form was it (like the CodeGen) can handle both cases without
12068   // special case code.
12069 
12070   // C++ 8.5p11:
12071   // The form of initialization (using parentheses or '=') is generally
12072   // insignificant, but does matter when the entity being initialized has a
12073   // class type.
12074   if (CXXDirectInit) {
12075     assert(DirectInit && "Call-style initializer must be direct init.");
12076     VDecl->setInitStyle(VarDecl::CallInit);
12077   } else if (DirectInit) {
12078     // This must be list-initialization. No other way is direct-initialization.
12079     VDecl->setInitStyle(VarDecl::ListInit);
12080   }
12081 
12082   CheckCompleteVariableDeclaration(VDecl);
12083 }
12084 
12085 /// ActOnInitializerError - Given that there was an error parsing an
12086 /// initializer for the given declaration, try to return to some form
12087 /// of sanity.
12088 void Sema::ActOnInitializerError(Decl *D) {
12089   // Our main concern here is re-establishing invariants like "a
12090   // variable's type is either dependent or complete".
12091   if (!D || D->isInvalidDecl()) return;
12092 
12093   VarDecl *VD = dyn_cast<VarDecl>(D);
12094   if (!VD) return;
12095 
12096   // Bindings are not usable if we can't make sense of the initializer.
12097   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12098     for (auto *BD : DD->bindings())
12099       BD->setInvalidDecl();
12100 
12101   // Auto types are meaningless if we can't make sense of the initializer.
12102   if (ParsingInitForAutoVars.count(D)) {
12103     D->setInvalidDecl();
12104     return;
12105   }
12106 
12107   QualType Ty = VD->getType();
12108   if (Ty->isDependentType()) return;
12109 
12110   // Require a complete type.
12111   if (RequireCompleteType(VD->getLocation(),
12112                           Context.getBaseElementType(Ty),
12113                           diag::err_typecheck_decl_incomplete_type)) {
12114     VD->setInvalidDecl();
12115     return;
12116   }
12117 
12118   // Require a non-abstract type.
12119   if (RequireNonAbstractType(VD->getLocation(), Ty,
12120                              diag::err_abstract_type_in_decl,
12121                              AbstractVariableType)) {
12122     VD->setInvalidDecl();
12123     return;
12124   }
12125 
12126   // Don't bother complaining about constructors or destructors,
12127   // though.
12128 }
12129 
12130 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12131   // If there is no declaration, there was an error parsing it. Just ignore it.
12132   if (!RealDecl)
12133     return;
12134 
12135   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12136     QualType Type = Var->getType();
12137 
12138     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12139     if (isa<DecompositionDecl>(RealDecl)) {
12140       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12141       Var->setInvalidDecl();
12142       return;
12143     }
12144 
12145     if (Type->isUndeducedType() &&
12146         DeduceVariableDeclarationType(Var, false, nullptr))
12147       return;
12148 
12149     // C++11 [class.static.data]p3: A static data member can be declared with
12150     // the constexpr specifier; if so, its declaration shall specify
12151     // a brace-or-equal-initializer.
12152     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12153     // the definition of a variable [...] or the declaration of a static data
12154     // member.
12155     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12156         !Var->isThisDeclarationADemotedDefinition()) {
12157       if (Var->isStaticDataMember()) {
12158         // C++1z removes the relevant rule; the in-class declaration is always
12159         // a definition there.
12160         if (!getLangOpts().CPlusPlus17 &&
12161             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12162           Diag(Var->getLocation(),
12163                diag::err_constexpr_static_mem_var_requires_init)
12164             << Var->getDeclName();
12165           Var->setInvalidDecl();
12166           return;
12167         }
12168       } else {
12169         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12170         Var->setInvalidDecl();
12171         return;
12172       }
12173     }
12174 
12175     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12176     // be initialized.
12177     if (!Var->isInvalidDecl() &&
12178         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12179         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12180       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12181       Var->setInvalidDecl();
12182       return;
12183     }
12184 
12185     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12186     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12187         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12188       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12189                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12190 
12191 
12192     switch (DefKind) {
12193     case VarDecl::Definition:
12194       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12195         break;
12196 
12197       // We have an out-of-line definition of a static data member
12198       // that has an in-class initializer, so we type-check this like
12199       // a declaration.
12200       //
12201       LLVM_FALLTHROUGH;
12202 
12203     case VarDecl::DeclarationOnly:
12204       // It's only a declaration.
12205 
12206       // Block scope. C99 6.7p7: If an identifier for an object is
12207       // declared with no linkage (C99 6.2.2p6), the type for the
12208       // object shall be complete.
12209       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12210           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12211           RequireCompleteType(Var->getLocation(), Type,
12212                               diag::err_typecheck_decl_incomplete_type))
12213         Var->setInvalidDecl();
12214 
12215       // Make sure that the type is not abstract.
12216       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12217           RequireNonAbstractType(Var->getLocation(), Type,
12218                                  diag::err_abstract_type_in_decl,
12219                                  AbstractVariableType))
12220         Var->setInvalidDecl();
12221       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12222           Var->getStorageClass() == SC_PrivateExtern) {
12223         Diag(Var->getLocation(), diag::warn_private_extern);
12224         Diag(Var->getLocation(), diag::note_private_extern);
12225       }
12226 
12227       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12228           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12229         ExternalDeclarations.push_back(Var);
12230 
12231       return;
12232 
12233     case VarDecl::TentativeDefinition:
12234       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12235       // object that has file scope without an initializer, and without a
12236       // storage-class specifier or with the storage-class specifier "static",
12237       // constitutes a tentative definition. Note: A tentative definition with
12238       // external linkage is valid (C99 6.2.2p5).
12239       if (!Var->isInvalidDecl()) {
12240         if (const IncompleteArrayType *ArrayT
12241                                     = Context.getAsIncompleteArrayType(Type)) {
12242           if (RequireCompleteType(Var->getLocation(),
12243                                   ArrayT->getElementType(),
12244                                   diag::err_illegal_decl_array_incomplete_type))
12245             Var->setInvalidDecl();
12246         } else if (Var->getStorageClass() == SC_Static) {
12247           // C99 6.9.2p3: If the declaration of an identifier for an object is
12248           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12249           // declared type shall not be an incomplete type.
12250           // NOTE: code such as the following
12251           //     static struct s;
12252           //     struct s { int a; };
12253           // is accepted by gcc. Hence here we issue a warning instead of
12254           // an error and we do not invalidate the static declaration.
12255           // NOTE: to avoid multiple warnings, only check the first declaration.
12256           if (Var->isFirstDecl())
12257             RequireCompleteType(Var->getLocation(), Type,
12258                                 diag::ext_typecheck_decl_incomplete_type);
12259         }
12260       }
12261 
12262       // Record the tentative definition; we're done.
12263       if (!Var->isInvalidDecl())
12264         TentativeDefinitions.push_back(Var);
12265       return;
12266     }
12267 
12268     // Provide a specific diagnostic for uninitialized variable
12269     // definitions with incomplete array type.
12270     if (Type->isIncompleteArrayType()) {
12271       Diag(Var->getLocation(),
12272            diag::err_typecheck_incomplete_array_needs_initializer);
12273       Var->setInvalidDecl();
12274       return;
12275     }
12276 
12277     // Provide a specific diagnostic for uninitialized variable
12278     // definitions with reference type.
12279     if (Type->isReferenceType()) {
12280       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12281         << Var->getDeclName()
12282         << SourceRange(Var->getLocation(), Var->getLocation());
12283       Var->setInvalidDecl();
12284       return;
12285     }
12286 
12287     // Do not attempt to type-check the default initializer for a
12288     // variable with dependent type.
12289     if (Type->isDependentType())
12290       return;
12291 
12292     if (Var->isInvalidDecl())
12293       return;
12294 
12295     if (!Var->hasAttr<AliasAttr>()) {
12296       if (RequireCompleteType(Var->getLocation(),
12297                               Context.getBaseElementType(Type),
12298                               diag::err_typecheck_decl_incomplete_type)) {
12299         Var->setInvalidDecl();
12300         return;
12301       }
12302     } else {
12303       return;
12304     }
12305 
12306     // The variable can not have an abstract class type.
12307     if (RequireNonAbstractType(Var->getLocation(), Type,
12308                                diag::err_abstract_type_in_decl,
12309                                AbstractVariableType)) {
12310       Var->setInvalidDecl();
12311       return;
12312     }
12313 
12314     // Check for jumps past the implicit initializer.  C++0x
12315     // clarifies that this applies to a "variable with automatic
12316     // storage duration", not a "local variable".
12317     // C++11 [stmt.dcl]p3
12318     //   A program that jumps from a point where a variable with automatic
12319     //   storage duration is not in scope to a point where it is in scope is
12320     //   ill-formed unless the variable has scalar type, class type with a
12321     //   trivial default constructor and a trivial destructor, a cv-qualified
12322     //   version of one of these types, or an array of one of the preceding
12323     //   types and is declared without an initializer.
12324     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12325       if (const RecordType *Record
12326             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12327         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12328         // Mark the function (if we're in one) for further checking even if the
12329         // looser rules of C++11 do not require such checks, so that we can
12330         // diagnose incompatibilities with C++98.
12331         if (!CXXRecord->isPOD())
12332           setFunctionHasBranchProtectedScope();
12333       }
12334     }
12335     // In OpenCL, we can't initialize objects in the __local address space,
12336     // even implicitly, so don't synthesize an implicit initializer.
12337     if (getLangOpts().OpenCL &&
12338         Var->getType().getAddressSpace() == LangAS::opencl_local)
12339       return;
12340     // C++03 [dcl.init]p9:
12341     //   If no initializer is specified for an object, and the
12342     //   object is of (possibly cv-qualified) non-POD class type (or
12343     //   array thereof), the object shall be default-initialized; if
12344     //   the object is of const-qualified type, the underlying class
12345     //   type shall have a user-declared default
12346     //   constructor. Otherwise, if no initializer is specified for
12347     //   a non- static object, the object and its subobjects, if
12348     //   any, have an indeterminate initial value); if the object
12349     //   or any of its subobjects are of const-qualified type, the
12350     //   program is ill-formed.
12351     // C++0x [dcl.init]p11:
12352     //   If no initializer is specified for an object, the object is
12353     //   default-initialized; [...].
12354     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12355     InitializationKind Kind
12356       = InitializationKind::CreateDefault(Var->getLocation());
12357 
12358     InitializationSequence InitSeq(*this, Entity, Kind, None);
12359     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12360     if (Init.isInvalid())
12361       Var->setInvalidDecl();
12362     else if (Init.get()) {
12363       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12364       // This is important for template substitution.
12365       Var->setInitStyle(VarDecl::CallInit);
12366     }
12367 
12368     CheckCompleteVariableDeclaration(Var);
12369   }
12370 }
12371 
12372 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12373   // If there is no declaration, there was an error parsing it. Ignore it.
12374   if (!D)
12375     return;
12376 
12377   VarDecl *VD = dyn_cast<VarDecl>(D);
12378   if (!VD) {
12379     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12380     D->setInvalidDecl();
12381     return;
12382   }
12383 
12384   VD->setCXXForRangeDecl(true);
12385 
12386   // for-range-declaration cannot be given a storage class specifier.
12387   int Error = -1;
12388   switch (VD->getStorageClass()) {
12389   case SC_None:
12390     break;
12391   case SC_Extern:
12392     Error = 0;
12393     break;
12394   case SC_Static:
12395     Error = 1;
12396     break;
12397   case SC_PrivateExtern:
12398     Error = 2;
12399     break;
12400   case SC_Auto:
12401     Error = 3;
12402     break;
12403   case SC_Register:
12404     Error = 4;
12405     break;
12406   }
12407   if (Error != -1) {
12408     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12409       << VD->getDeclName() << Error;
12410     D->setInvalidDecl();
12411   }
12412 }
12413 
12414 StmtResult
12415 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12416                                  IdentifierInfo *Ident,
12417                                  ParsedAttributes &Attrs,
12418                                  SourceLocation AttrEnd) {
12419   // C++1y [stmt.iter]p1:
12420   //   A range-based for statement of the form
12421   //      for ( for-range-identifier : for-range-initializer ) statement
12422   //   is equivalent to
12423   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12424   DeclSpec DS(Attrs.getPool().getFactory());
12425 
12426   const char *PrevSpec;
12427   unsigned DiagID;
12428   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12429                      getPrintingPolicy());
12430 
12431   Declarator D(DS, DeclaratorContext::ForContext);
12432   D.SetIdentifier(Ident, IdentLoc);
12433   D.takeAttributes(Attrs, AttrEnd);
12434 
12435   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12436                 IdentLoc);
12437   Decl *Var = ActOnDeclarator(S, D);
12438   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12439   FinalizeDeclaration(Var);
12440   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12441                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12442 }
12443 
12444 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12445   if (var->isInvalidDecl()) return;
12446 
12447   if (getLangOpts().OpenCL) {
12448     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12449     // initialiser
12450     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12451         !var->hasInit()) {
12452       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12453           << 1 /*Init*/;
12454       var->setInvalidDecl();
12455       return;
12456     }
12457   }
12458 
12459   // In Objective-C, don't allow jumps past the implicit initialization of a
12460   // local retaining variable.
12461   if (getLangOpts().ObjC &&
12462       var->hasLocalStorage()) {
12463     switch (var->getType().getObjCLifetime()) {
12464     case Qualifiers::OCL_None:
12465     case Qualifiers::OCL_ExplicitNone:
12466     case Qualifiers::OCL_Autoreleasing:
12467       break;
12468 
12469     case Qualifiers::OCL_Weak:
12470     case Qualifiers::OCL_Strong:
12471       setFunctionHasBranchProtectedScope();
12472       break;
12473     }
12474   }
12475 
12476   if (var->hasLocalStorage() &&
12477       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12478     setFunctionHasBranchProtectedScope();
12479 
12480   // Warn about externally-visible variables being defined without a
12481   // prior declaration.  We only want to do this for global
12482   // declarations, but we also specifically need to avoid doing it for
12483   // class members because the linkage of an anonymous class can
12484   // change if it's later given a typedef name.
12485   if (var->isThisDeclarationADefinition() &&
12486       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12487       var->isExternallyVisible() && var->hasLinkage() &&
12488       !var->isInline() && !var->getDescribedVarTemplate() &&
12489       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12490       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12491                                   var->getLocation())) {
12492     // Find a previous declaration that's not a definition.
12493     VarDecl *prev = var->getPreviousDecl();
12494     while (prev && prev->isThisDeclarationADefinition())
12495       prev = prev->getPreviousDecl();
12496 
12497     if (!prev) {
12498       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12499       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12500           << /* variable */ 0;
12501     }
12502   }
12503 
12504   // Cache the result of checking for constant initialization.
12505   Optional<bool> CacheHasConstInit;
12506   const Expr *CacheCulprit = nullptr;
12507   auto checkConstInit = [&]() mutable {
12508     if (!CacheHasConstInit)
12509       CacheHasConstInit = var->getInit()->isConstantInitializer(
12510             Context, var->getType()->isReferenceType(), &CacheCulprit);
12511     return *CacheHasConstInit;
12512   };
12513 
12514   if (var->getTLSKind() == VarDecl::TLS_Static) {
12515     if (var->getType().isDestructedType()) {
12516       // GNU C++98 edits for __thread, [basic.start.term]p3:
12517       //   The type of an object with thread storage duration shall not
12518       //   have a non-trivial destructor.
12519       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12520       if (getLangOpts().CPlusPlus11)
12521         Diag(var->getLocation(), diag::note_use_thread_local);
12522     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12523       if (!checkConstInit()) {
12524         // GNU C++98 edits for __thread, [basic.start.init]p4:
12525         //   An object of thread storage duration shall not require dynamic
12526         //   initialization.
12527         // FIXME: Need strict checking here.
12528         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12529           << CacheCulprit->getSourceRange();
12530         if (getLangOpts().CPlusPlus11)
12531           Diag(var->getLocation(), diag::note_use_thread_local);
12532       }
12533     }
12534   }
12535 
12536   // Apply section attributes and pragmas to global variables.
12537   bool GlobalStorage = var->hasGlobalStorage();
12538   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12539       !inTemplateInstantiation()) {
12540     PragmaStack<StringLiteral *> *Stack = nullptr;
12541     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12542     if (var->getType().isConstQualified())
12543       Stack = &ConstSegStack;
12544     else if (!var->getInit()) {
12545       Stack = &BSSSegStack;
12546       SectionFlags |= ASTContext::PSF_Write;
12547     } else {
12548       Stack = &DataSegStack;
12549       SectionFlags |= ASTContext::PSF_Write;
12550     }
12551     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12552       var->addAttr(SectionAttr::CreateImplicit(
12553           Context, Stack->CurrentValue->getString(),
12554           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12555           SectionAttr::Declspec_allocate));
12556     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12557       if (UnifySection(SA->getName(), SectionFlags, var))
12558         var->dropAttr<SectionAttr>();
12559 
12560     // Apply the init_seg attribute if this has an initializer.  If the
12561     // initializer turns out to not be dynamic, we'll end up ignoring this
12562     // attribute.
12563     if (CurInitSeg && var->getInit())
12564       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12565                                                CurInitSegLoc,
12566                                                AttributeCommonInfo::AS_Pragma));
12567   }
12568 
12569   // All the following checks are C++ only.
12570   if (!getLangOpts().CPlusPlus) {
12571       // If this variable must be emitted, add it as an initializer for the
12572       // current module.
12573      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12574        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12575      return;
12576   }
12577 
12578   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12579     CheckCompleteDecompositionDeclaration(DD);
12580 
12581   QualType type = var->getType();
12582   if (type->isDependentType()) return;
12583 
12584   if (var->hasAttr<BlocksAttr>())
12585     getCurFunction()->addByrefBlockVar(var);
12586 
12587   Expr *Init = var->getInit();
12588   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12589   QualType baseType = Context.getBaseElementType(type);
12590 
12591   if (Init && !Init->isValueDependent()) {
12592     if (var->isConstexpr()) {
12593       SmallVector<PartialDiagnosticAt, 8> Notes;
12594       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12595         SourceLocation DiagLoc = var->getLocation();
12596         // If the note doesn't add any useful information other than a source
12597         // location, fold it into the primary diagnostic.
12598         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12599               diag::note_invalid_subexpr_in_const_expr) {
12600           DiagLoc = Notes[0].first;
12601           Notes.clear();
12602         }
12603         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12604           << var << Init->getSourceRange();
12605         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12606           Diag(Notes[I].first, Notes[I].second);
12607       }
12608     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12609       // Check whether the initializer of a const variable of integral or
12610       // enumeration type is an ICE now, since we can't tell whether it was
12611       // initialized by a constant expression if we check later.
12612       var->checkInitIsICE();
12613     }
12614 
12615     // Don't emit further diagnostics about constexpr globals since they
12616     // were just diagnosed.
12617     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12618       // FIXME: Need strict checking in C++03 here.
12619       bool DiagErr = getLangOpts().CPlusPlus11
12620           ? !var->checkInitIsICE() : !checkConstInit();
12621       if (DiagErr) {
12622         auto *Attr = var->getAttr<ConstInitAttr>();
12623         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12624           << Init->getSourceRange();
12625         Diag(Attr->getLocation(),
12626              diag::note_declared_required_constant_init_here)
12627             << Attr->getRange() << Attr->isConstinit();
12628         if (getLangOpts().CPlusPlus11) {
12629           APValue Value;
12630           SmallVector<PartialDiagnosticAt, 8> Notes;
12631           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12632           for (auto &it : Notes)
12633             Diag(it.first, it.second);
12634         } else {
12635           Diag(CacheCulprit->getExprLoc(),
12636                diag::note_invalid_subexpr_in_const_expr)
12637               << CacheCulprit->getSourceRange();
12638         }
12639       }
12640     }
12641     else if (!var->isConstexpr() && IsGlobal &&
12642              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12643                                     var->getLocation())) {
12644       // Warn about globals which don't have a constant initializer.  Don't
12645       // warn about globals with a non-trivial destructor because we already
12646       // warned about them.
12647       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12648       if (!(RD && !RD->hasTrivialDestructor())) {
12649         if (!checkConstInit())
12650           Diag(var->getLocation(), diag::warn_global_constructor)
12651             << Init->getSourceRange();
12652       }
12653     }
12654   }
12655 
12656   // Require the destructor.
12657   if (const RecordType *recordType = baseType->getAs<RecordType>())
12658     FinalizeVarWithDestructor(var, recordType);
12659 
12660   // If this variable must be emitted, add it as an initializer for the current
12661   // module.
12662   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12663     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12664 }
12665 
12666 /// Determines if a variable's alignment is dependent.
12667 static bool hasDependentAlignment(VarDecl *VD) {
12668   if (VD->getType()->isDependentType())
12669     return true;
12670   for (auto *I : VD->specific_attrs<AlignedAttr>())
12671     if (I->isAlignmentDependent())
12672       return true;
12673   return false;
12674 }
12675 
12676 /// Check if VD needs to be dllexport/dllimport due to being in a
12677 /// dllexport/import function.
12678 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12679   assert(VD->isStaticLocal());
12680 
12681   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12682 
12683   // Find outermost function when VD is in lambda function.
12684   while (FD && !getDLLAttr(FD) &&
12685          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12686          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12687     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12688   }
12689 
12690   if (!FD)
12691     return;
12692 
12693   // Static locals inherit dll attributes from their function.
12694   if (Attr *A = getDLLAttr(FD)) {
12695     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12696     NewAttr->setInherited(true);
12697     VD->addAttr(NewAttr);
12698   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12699     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12700     NewAttr->setInherited(true);
12701     VD->addAttr(NewAttr);
12702 
12703     // Export this function to enforce exporting this static variable even
12704     // if it is not used in this compilation unit.
12705     if (!FD->hasAttr<DLLExportAttr>())
12706       FD->addAttr(NewAttr);
12707 
12708   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12709     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12710     NewAttr->setInherited(true);
12711     VD->addAttr(NewAttr);
12712   }
12713 }
12714 
12715 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12716 /// any semantic actions necessary after any initializer has been attached.
12717 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12718   // Note that we are no longer parsing the initializer for this declaration.
12719   ParsingInitForAutoVars.erase(ThisDecl);
12720 
12721   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12722   if (!VD)
12723     return;
12724 
12725   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12726   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12727       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12728     if (PragmaClangBSSSection.Valid)
12729       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12730           Context, PragmaClangBSSSection.SectionName,
12731           PragmaClangBSSSection.PragmaLocation,
12732           AttributeCommonInfo::AS_Pragma));
12733     if (PragmaClangDataSection.Valid)
12734       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12735           Context, PragmaClangDataSection.SectionName,
12736           PragmaClangDataSection.PragmaLocation,
12737           AttributeCommonInfo::AS_Pragma));
12738     if (PragmaClangRodataSection.Valid)
12739       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12740           Context, PragmaClangRodataSection.SectionName,
12741           PragmaClangRodataSection.PragmaLocation,
12742           AttributeCommonInfo::AS_Pragma));
12743     if (PragmaClangRelroSection.Valid)
12744       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12745           Context, PragmaClangRelroSection.SectionName,
12746           PragmaClangRelroSection.PragmaLocation,
12747           AttributeCommonInfo::AS_Pragma));
12748   }
12749 
12750   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12751     for (auto *BD : DD->bindings()) {
12752       FinalizeDeclaration(BD);
12753     }
12754   }
12755 
12756   checkAttributesAfterMerging(*this, *VD);
12757 
12758   // Perform TLS alignment check here after attributes attached to the variable
12759   // which may affect the alignment have been processed. Only perform the check
12760   // if the target has a maximum TLS alignment (zero means no constraints).
12761   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12762     // Protect the check so that it's not performed on dependent types and
12763     // dependent alignments (we can't determine the alignment in that case).
12764     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12765         !VD->isInvalidDecl()) {
12766       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12767       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12768         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12769           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12770           << (unsigned)MaxAlignChars.getQuantity();
12771       }
12772     }
12773   }
12774 
12775   if (VD->isStaticLocal()) {
12776     CheckStaticLocalForDllExport(VD);
12777 
12778     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12779       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12780       // function, only __shared__ variables or variables without any device
12781       // memory qualifiers may be declared with static storage class.
12782       // Note: It is unclear how a function-scope non-const static variable
12783       // without device memory qualifier is implemented, therefore only static
12784       // const variable without device memory qualifier is allowed.
12785       [&]() {
12786         if (!getLangOpts().CUDA)
12787           return;
12788         if (VD->hasAttr<CUDASharedAttr>())
12789           return;
12790         if (VD->getType().isConstQualified() &&
12791             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12792           return;
12793         if (CUDADiagIfDeviceCode(VD->getLocation(),
12794                                  diag::err_device_static_local_var)
12795             << CurrentCUDATarget())
12796           VD->setInvalidDecl();
12797       }();
12798     }
12799   }
12800 
12801   // Perform check for initializers of device-side global variables.
12802   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12803   // 7.5). We must also apply the same checks to all __shared__
12804   // variables whether they are local or not. CUDA also allows
12805   // constant initializers for __constant__ and __device__ variables.
12806   if (getLangOpts().CUDA)
12807     checkAllowedCUDAInitializer(VD);
12808 
12809   // Grab the dllimport or dllexport attribute off of the VarDecl.
12810   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12811 
12812   // Imported static data members cannot be defined out-of-line.
12813   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12814     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12815         VD->isThisDeclarationADefinition()) {
12816       // We allow definitions of dllimport class template static data members
12817       // with a warning.
12818       CXXRecordDecl *Context =
12819         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12820       bool IsClassTemplateMember =
12821           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12822           Context->getDescribedClassTemplate();
12823 
12824       Diag(VD->getLocation(),
12825            IsClassTemplateMember
12826                ? diag::warn_attribute_dllimport_static_field_definition
12827                : diag::err_attribute_dllimport_static_field_definition);
12828       Diag(IA->getLocation(), diag::note_attribute);
12829       if (!IsClassTemplateMember)
12830         VD->setInvalidDecl();
12831     }
12832   }
12833 
12834   // dllimport/dllexport variables cannot be thread local, their TLS index
12835   // isn't exported with the variable.
12836   if (DLLAttr && VD->getTLSKind()) {
12837     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12838     if (F && getDLLAttr(F)) {
12839       assert(VD->isStaticLocal());
12840       // But if this is a static local in a dlimport/dllexport function, the
12841       // function will never be inlined, which means the var would never be
12842       // imported, so having it marked import/export is safe.
12843     } else {
12844       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12845                                                                     << DLLAttr;
12846       VD->setInvalidDecl();
12847     }
12848   }
12849 
12850   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12851     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12852       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12853       VD->dropAttr<UsedAttr>();
12854     }
12855   }
12856 
12857   const DeclContext *DC = VD->getDeclContext();
12858   // If there's a #pragma GCC visibility in scope, and this isn't a class
12859   // member, set the visibility of this variable.
12860   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12861     AddPushedVisibilityAttribute(VD);
12862 
12863   // FIXME: Warn on unused var template partial specializations.
12864   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12865     MarkUnusedFileScopedDecl(VD);
12866 
12867   // Now we have parsed the initializer and can update the table of magic
12868   // tag values.
12869   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12870       !VD->getType()->isIntegralOrEnumerationType())
12871     return;
12872 
12873   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12874     const Expr *MagicValueExpr = VD->getInit();
12875     if (!MagicValueExpr) {
12876       continue;
12877     }
12878     llvm::APSInt MagicValueInt;
12879     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12880       Diag(I->getRange().getBegin(),
12881            diag::err_type_tag_for_datatype_not_ice)
12882         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12883       continue;
12884     }
12885     if (MagicValueInt.getActiveBits() > 64) {
12886       Diag(I->getRange().getBegin(),
12887            diag::err_type_tag_for_datatype_too_large)
12888         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12889       continue;
12890     }
12891     uint64_t MagicValue = MagicValueInt.getZExtValue();
12892     RegisterTypeTagForDatatype(I->getArgumentKind(),
12893                                MagicValue,
12894                                I->getMatchingCType(),
12895                                I->getLayoutCompatible(),
12896                                I->getMustBeNull());
12897   }
12898 }
12899 
12900 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12901   auto *VD = dyn_cast<VarDecl>(DD);
12902   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12903 }
12904 
12905 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12906                                                    ArrayRef<Decl *> Group) {
12907   SmallVector<Decl*, 8> Decls;
12908 
12909   if (DS.isTypeSpecOwned())
12910     Decls.push_back(DS.getRepAsDecl());
12911 
12912   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12913   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12914   bool DiagnosedMultipleDecomps = false;
12915   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12916   bool DiagnosedNonDeducedAuto = false;
12917 
12918   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12919     if (Decl *D = Group[i]) {
12920       // For declarators, there are some additional syntactic-ish checks we need
12921       // to perform.
12922       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12923         if (!FirstDeclaratorInGroup)
12924           FirstDeclaratorInGroup = DD;
12925         if (!FirstDecompDeclaratorInGroup)
12926           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12927         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12928             !hasDeducedAuto(DD))
12929           FirstNonDeducedAutoInGroup = DD;
12930 
12931         if (FirstDeclaratorInGroup != DD) {
12932           // A decomposition declaration cannot be combined with any other
12933           // declaration in the same group.
12934           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12935             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12936                  diag::err_decomp_decl_not_alone)
12937                 << FirstDeclaratorInGroup->getSourceRange()
12938                 << DD->getSourceRange();
12939             DiagnosedMultipleDecomps = true;
12940           }
12941 
12942           // A declarator that uses 'auto' in any way other than to declare a
12943           // variable with a deduced type cannot be combined with any other
12944           // declarator in the same group.
12945           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12946             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12947                  diag::err_auto_non_deduced_not_alone)
12948                 << FirstNonDeducedAutoInGroup->getType()
12949                        ->hasAutoForTrailingReturnType()
12950                 << FirstDeclaratorInGroup->getSourceRange()
12951                 << DD->getSourceRange();
12952             DiagnosedNonDeducedAuto = true;
12953           }
12954         }
12955       }
12956 
12957       Decls.push_back(D);
12958     }
12959   }
12960 
12961   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12962     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12963       handleTagNumbering(Tag, S);
12964       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12965           getLangOpts().CPlusPlus)
12966         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12967     }
12968   }
12969 
12970   return BuildDeclaratorGroup(Decls);
12971 }
12972 
12973 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12974 /// group, performing any necessary semantic checking.
12975 Sema::DeclGroupPtrTy
12976 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12977   // C++14 [dcl.spec.auto]p7: (DR1347)
12978   //   If the type that replaces the placeholder type is not the same in each
12979   //   deduction, the program is ill-formed.
12980   if (Group.size() > 1) {
12981     QualType Deduced;
12982     VarDecl *DeducedDecl = nullptr;
12983     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12984       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12985       if (!D || D->isInvalidDecl())
12986         break;
12987       DeducedType *DT = D->getType()->getContainedDeducedType();
12988       if (!DT || DT->getDeducedType().isNull())
12989         continue;
12990       if (Deduced.isNull()) {
12991         Deduced = DT->getDeducedType();
12992         DeducedDecl = D;
12993       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12994         auto *AT = dyn_cast<AutoType>(DT);
12995         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12996              diag::err_auto_different_deductions)
12997           << (AT ? (unsigned)AT->getKeyword() : 3)
12998           << Deduced << DeducedDecl->getDeclName()
12999           << DT->getDeducedType() << D->getDeclName()
13000           << DeducedDecl->getInit()->getSourceRange()
13001           << D->getInit()->getSourceRange();
13002         D->setInvalidDecl();
13003         break;
13004       }
13005     }
13006   }
13007 
13008   ActOnDocumentableDecls(Group);
13009 
13010   return DeclGroupPtrTy::make(
13011       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13012 }
13013 
13014 void Sema::ActOnDocumentableDecl(Decl *D) {
13015   ActOnDocumentableDecls(D);
13016 }
13017 
13018 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13019   // Don't parse the comment if Doxygen diagnostics are ignored.
13020   if (Group.empty() || !Group[0])
13021     return;
13022 
13023   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13024                       Group[0]->getLocation()) &&
13025       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13026                       Group[0]->getLocation()))
13027     return;
13028 
13029   if (Group.size() >= 2) {
13030     // This is a decl group.  Normally it will contain only declarations
13031     // produced from declarator list.  But in case we have any definitions or
13032     // additional declaration references:
13033     //   'typedef struct S {} S;'
13034     //   'typedef struct S *S;'
13035     //   'struct S *pS;'
13036     // FinalizeDeclaratorGroup adds these as separate declarations.
13037     Decl *MaybeTagDecl = Group[0];
13038     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13039       Group = Group.slice(1);
13040     }
13041   }
13042 
13043   // FIMXE: We assume every Decl in the group is in the same file.
13044   // This is false when preprocessor constructs the group from decls in
13045   // different files (e. g. macros or #include).
13046   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13047 }
13048 
13049 /// Common checks for a parameter-declaration that should apply to both function
13050 /// parameters and non-type template parameters.
13051 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13052   // Check that there are no default arguments inside the type of this
13053   // parameter.
13054   if (getLangOpts().CPlusPlus)
13055     CheckExtraCXXDefaultArguments(D);
13056 
13057   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13058   if (D.getCXXScopeSpec().isSet()) {
13059     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13060       << D.getCXXScopeSpec().getRange();
13061   }
13062 
13063   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13064   // simple identifier except [...irrelevant cases...].
13065   switch (D.getName().getKind()) {
13066   case UnqualifiedIdKind::IK_Identifier:
13067     break;
13068 
13069   case UnqualifiedIdKind::IK_OperatorFunctionId:
13070   case UnqualifiedIdKind::IK_ConversionFunctionId:
13071   case UnqualifiedIdKind::IK_LiteralOperatorId:
13072   case UnqualifiedIdKind::IK_ConstructorName:
13073   case UnqualifiedIdKind::IK_DestructorName:
13074   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13075   case UnqualifiedIdKind::IK_DeductionGuideName:
13076     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13077       << GetNameForDeclarator(D).getName();
13078     break;
13079 
13080   case UnqualifiedIdKind::IK_TemplateId:
13081   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13082     // GetNameForDeclarator would not produce a useful name in this case.
13083     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13084     break;
13085   }
13086 }
13087 
13088 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13089 /// to introduce parameters into function prototype scope.
13090 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13091   const DeclSpec &DS = D.getDeclSpec();
13092 
13093   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13094 
13095   // C++03 [dcl.stc]p2 also permits 'auto'.
13096   StorageClass SC = SC_None;
13097   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13098     SC = SC_Register;
13099     // In C++11, the 'register' storage class specifier is deprecated.
13100     // In C++17, it is not allowed, but we tolerate it as an extension.
13101     if (getLangOpts().CPlusPlus11) {
13102       Diag(DS.getStorageClassSpecLoc(),
13103            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13104                                      : diag::warn_deprecated_register)
13105         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13106     }
13107   } else if (getLangOpts().CPlusPlus &&
13108              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13109     SC = SC_Auto;
13110   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13111     Diag(DS.getStorageClassSpecLoc(),
13112          diag::err_invalid_storage_class_in_func_decl);
13113     D.getMutableDeclSpec().ClearStorageClassSpecs();
13114   }
13115 
13116   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13117     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13118       << DeclSpec::getSpecifierName(TSCS);
13119   if (DS.isInlineSpecified())
13120     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13121         << getLangOpts().CPlusPlus17;
13122   if (DS.hasConstexprSpecifier())
13123     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13124         << 0 << D.getDeclSpec().getConstexprSpecifier();
13125 
13126   DiagnoseFunctionSpecifiers(DS);
13127 
13128   CheckFunctionOrTemplateParamDeclarator(S, D);
13129 
13130   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13131   QualType parmDeclType = TInfo->getType();
13132 
13133   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13134   IdentifierInfo *II = D.getIdentifier();
13135   if (II) {
13136     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13137                    ForVisibleRedeclaration);
13138     LookupName(R, S);
13139     if (R.isSingleResult()) {
13140       NamedDecl *PrevDecl = R.getFoundDecl();
13141       if (PrevDecl->isTemplateParameter()) {
13142         // Maybe we will complain about the shadowed template parameter.
13143         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13144         // Just pretend that we didn't see the previous declaration.
13145         PrevDecl = nullptr;
13146       } else if (S->isDeclScope(PrevDecl)) {
13147         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13148         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13149 
13150         // Recover by removing the name
13151         II = nullptr;
13152         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13153         D.setInvalidType(true);
13154       }
13155     }
13156   }
13157 
13158   // Temporarily put parameter variables in the translation unit, not
13159   // the enclosing context.  This prevents them from accidentally
13160   // looking like class members in C++.
13161   ParmVarDecl *New =
13162       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13163                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13164 
13165   if (D.isInvalidType())
13166     New->setInvalidDecl();
13167 
13168   assert(S->isFunctionPrototypeScope());
13169   assert(S->getFunctionPrototypeDepth() >= 1);
13170   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13171                     S->getNextFunctionPrototypeIndex());
13172 
13173   // Add the parameter declaration into this scope.
13174   S->AddDecl(New);
13175   if (II)
13176     IdResolver.AddDecl(New);
13177 
13178   ProcessDeclAttributes(S, New, D);
13179 
13180   if (D.getDeclSpec().isModulePrivateSpecified())
13181     Diag(New->getLocation(), diag::err_module_private_local)
13182       << 1 << New->getDeclName()
13183       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13184       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13185 
13186   if (New->hasAttr<BlocksAttr>()) {
13187     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13188   }
13189 
13190   if (getLangOpts().OpenCL)
13191     deduceOpenCLAddressSpace(New);
13192 
13193   return New;
13194 }
13195 
13196 /// Synthesizes a variable for a parameter arising from a
13197 /// typedef.
13198 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13199                                               SourceLocation Loc,
13200                                               QualType T) {
13201   /* FIXME: setting StartLoc == Loc.
13202      Would it be worth to modify callers so as to provide proper source
13203      location for the unnamed parameters, embedding the parameter's type? */
13204   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13205                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13206                                            SC_None, nullptr);
13207   Param->setImplicit();
13208   return Param;
13209 }
13210 
13211 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13212   // Don't diagnose unused-parameter errors in template instantiations; we
13213   // will already have done so in the template itself.
13214   if (inTemplateInstantiation())
13215     return;
13216 
13217   for (const ParmVarDecl *Parameter : Parameters) {
13218     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13219         !Parameter->hasAttr<UnusedAttr>()) {
13220       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13221         << Parameter->getDeclName();
13222     }
13223   }
13224 }
13225 
13226 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13227     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13228   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13229     return;
13230 
13231   // Warn if the return value is pass-by-value and larger than the specified
13232   // threshold.
13233   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13234     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13235     if (Size > LangOpts.NumLargeByValueCopy)
13236       Diag(D->getLocation(), diag::warn_return_value_size)
13237           << D->getDeclName() << Size;
13238   }
13239 
13240   // Warn if any parameter is pass-by-value and larger than the specified
13241   // threshold.
13242   for (const ParmVarDecl *Parameter : Parameters) {
13243     QualType T = Parameter->getType();
13244     if (T->isDependentType() || !T.isPODType(Context))
13245       continue;
13246     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13247     if (Size > LangOpts.NumLargeByValueCopy)
13248       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13249           << Parameter->getDeclName() << Size;
13250   }
13251 }
13252 
13253 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13254                                   SourceLocation NameLoc, IdentifierInfo *Name,
13255                                   QualType T, TypeSourceInfo *TSInfo,
13256                                   StorageClass SC) {
13257   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13258   if (getLangOpts().ObjCAutoRefCount &&
13259       T.getObjCLifetime() == Qualifiers::OCL_None &&
13260       T->isObjCLifetimeType()) {
13261 
13262     Qualifiers::ObjCLifetime lifetime;
13263 
13264     // Special cases for arrays:
13265     //   - if it's const, use __unsafe_unretained
13266     //   - otherwise, it's an error
13267     if (T->isArrayType()) {
13268       if (!T.isConstQualified()) {
13269         if (DelayedDiagnostics.shouldDelayDiagnostics())
13270           DelayedDiagnostics.add(
13271               sema::DelayedDiagnostic::makeForbiddenType(
13272               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13273         else
13274           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13275               << TSInfo->getTypeLoc().getSourceRange();
13276       }
13277       lifetime = Qualifiers::OCL_ExplicitNone;
13278     } else {
13279       lifetime = T->getObjCARCImplicitLifetime();
13280     }
13281     T = Context.getLifetimeQualifiedType(T, lifetime);
13282   }
13283 
13284   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13285                                          Context.getAdjustedParameterType(T),
13286                                          TSInfo, SC, nullptr);
13287 
13288   // Make a note if we created a new pack in the scope of a lambda, so that
13289   // we know that references to that pack must also be expanded within the
13290   // lambda scope.
13291   if (New->isParameterPack())
13292     if (auto *LSI = getEnclosingLambda())
13293       LSI->LocalPacks.push_back(New);
13294 
13295   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13296       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13297     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13298                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13299 
13300   // Parameters can not be abstract class types.
13301   // For record types, this is done by the AbstractClassUsageDiagnoser once
13302   // the class has been completely parsed.
13303   if (!CurContext->isRecord() &&
13304       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13305                              AbstractParamType))
13306     New->setInvalidDecl();
13307 
13308   // Parameter declarators cannot be interface types. All ObjC objects are
13309   // passed by reference.
13310   if (T->isObjCObjectType()) {
13311     SourceLocation TypeEndLoc =
13312         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13313     Diag(NameLoc,
13314          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13315       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13316     T = Context.getObjCObjectPointerType(T);
13317     New->setType(T);
13318   }
13319 
13320   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13321   // duration shall not be qualified by an address-space qualifier."
13322   // Since all parameters have automatic store duration, they can not have
13323   // an address space.
13324   if (T.getAddressSpace() != LangAS::Default &&
13325       // OpenCL allows function arguments declared to be an array of a type
13326       // to be qualified with an address space.
13327       !(getLangOpts().OpenCL &&
13328         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13329     Diag(NameLoc, diag::err_arg_with_address_space);
13330     New->setInvalidDecl();
13331   }
13332 
13333   return New;
13334 }
13335 
13336 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13337                                            SourceLocation LocAfterDecls) {
13338   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13339 
13340   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13341   // for a K&R function.
13342   if (!FTI.hasPrototype) {
13343     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13344       --i;
13345       if (FTI.Params[i].Param == nullptr) {
13346         SmallString<256> Code;
13347         llvm::raw_svector_ostream(Code)
13348             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13349         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13350             << FTI.Params[i].Ident
13351             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13352 
13353         // Implicitly declare the argument as type 'int' for lack of a better
13354         // type.
13355         AttributeFactory attrs;
13356         DeclSpec DS(attrs);
13357         const char* PrevSpec; // unused
13358         unsigned DiagID; // unused
13359         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13360                            DiagID, Context.getPrintingPolicy());
13361         // Use the identifier location for the type source range.
13362         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13363         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13364         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13365         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13366         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13367       }
13368     }
13369   }
13370 }
13371 
13372 Decl *
13373 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13374                               MultiTemplateParamsArg TemplateParameterLists,
13375                               SkipBodyInfo *SkipBody) {
13376   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13377   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13378   Scope *ParentScope = FnBodyScope->getParent();
13379 
13380   D.setFunctionDefinitionKind(FDK_Definition);
13381   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13382   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13383 }
13384 
13385 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13386   Consumer.HandleInlineFunctionDefinition(D);
13387 }
13388 
13389 static bool
13390 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13391                                 const FunctionDecl *&PossiblePrototype) {
13392   // Don't warn about invalid declarations.
13393   if (FD->isInvalidDecl())
13394     return false;
13395 
13396   // Or declarations that aren't global.
13397   if (!FD->isGlobal())
13398     return false;
13399 
13400   // Don't warn about C++ member functions.
13401   if (isa<CXXMethodDecl>(FD))
13402     return false;
13403 
13404   // Don't warn about 'main'.
13405   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13406     if (IdentifierInfo *II = FD->getIdentifier())
13407       if (II->isStr("main"))
13408         return false;
13409 
13410   // Don't warn about inline functions.
13411   if (FD->isInlined())
13412     return false;
13413 
13414   // Don't warn about function templates.
13415   if (FD->getDescribedFunctionTemplate())
13416     return false;
13417 
13418   // Don't warn about function template specializations.
13419   if (FD->isFunctionTemplateSpecialization())
13420     return false;
13421 
13422   // Don't warn for OpenCL kernels.
13423   if (FD->hasAttr<OpenCLKernelAttr>())
13424     return false;
13425 
13426   // Don't warn on explicitly deleted functions.
13427   if (FD->isDeleted())
13428     return false;
13429 
13430   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13431        Prev; Prev = Prev->getPreviousDecl()) {
13432     // Ignore any declarations that occur in function or method
13433     // scope, because they aren't visible from the header.
13434     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13435       continue;
13436 
13437     PossiblePrototype = Prev;
13438     return Prev->getType()->isFunctionNoProtoType();
13439   }
13440 
13441   return true;
13442 }
13443 
13444 void
13445 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13446                                    const FunctionDecl *EffectiveDefinition,
13447                                    SkipBodyInfo *SkipBody) {
13448   const FunctionDecl *Definition = EffectiveDefinition;
13449   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13450     // If this is a friend function defined in a class template, it does not
13451     // have a body until it is used, nevertheless it is a definition, see
13452     // [temp.inst]p2:
13453     //
13454     // ... for the purpose of determining whether an instantiated redeclaration
13455     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13456     // corresponds to a definition in the template is considered to be a
13457     // definition.
13458     //
13459     // The following code must produce redefinition error:
13460     //
13461     //     template<typename T> struct C20 { friend void func_20() {} };
13462     //     C20<int> c20i;
13463     //     void func_20() {}
13464     //
13465     for (auto I : FD->redecls()) {
13466       if (I != FD && !I->isInvalidDecl() &&
13467           I->getFriendObjectKind() != Decl::FOK_None) {
13468         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13469           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13470             // A merged copy of the same function, instantiated as a member of
13471             // the same class, is OK.
13472             if (declaresSameEntity(OrigFD, Original) &&
13473                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13474                                    cast<Decl>(FD->getLexicalDeclContext())))
13475               continue;
13476           }
13477 
13478           if (Original->isThisDeclarationADefinition()) {
13479             Definition = I;
13480             break;
13481           }
13482         }
13483       }
13484     }
13485   }
13486 
13487   if (!Definition)
13488     // Similar to friend functions a friend function template may be a
13489     // definition and do not have a body if it is instantiated in a class
13490     // template.
13491     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13492       for (auto I : FTD->redecls()) {
13493         auto D = cast<FunctionTemplateDecl>(I);
13494         if (D != FTD) {
13495           assert(!D->isThisDeclarationADefinition() &&
13496                  "More than one definition in redeclaration chain");
13497           if (D->getFriendObjectKind() != Decl::FOK_None)
13498             if (FunctionTemplateDecl *FT =
13499                                        D->getInstantiatedFromMemberTemplate()) {
13500               if (FT->isThisDeclarationADefinition()) {
13501                 Definition = D->getTemplatedDecl();
13502                 break;
13503               }
13504             }
13505         }
13506       }
13507     }
13508 
13509   if (!Definition)
13510     return;
13511 
13512   if (canRedefineFunction(Definition, getLangOpts()))
13513     return;
13514 
13515   // Don't emit an error when this is redefinition of a typo-corrected
13516   // definition.
13517   if (TypoCorrectedFunctionDefinitions.count(Definition))
13518     return;
13519 
13520   // If we don't have a visible definition of the function, and it's inline or
13521   // a template, skip the new definition.
13522   if (SkipBody && !hasVisibleDefinition(Definition) &&
13523       (Definition->getFormalLinkage() == InternalLinkage ||
13524        Definition->isInlined() ||
13525        Definition->getDescribedFunctionTemplate() ||
13526        Definition->getNumTemplateParameterLists())) {
13527     SkipBody->ShouldSkip = true;
13528     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13529     if (auto *TD = Definition->getDescribedFunctionTemplate())
13530       makeMergedDefinitionVisible(TD);
13531     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13532     return;
13533   }
13534 
13535   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13536       Definition->getStorageClass() == SC_Extern)
13537     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13538         << FD->getDeclName() << getLangOpts().CPlusPlus;
13539   else
13540     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13541 
13542   Diag(Definition->getLocation(), diag::note_previous_definition);
13543   FD->setInvalidDecl();
13544 }
13545 
13546 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13547                                    Sema &S) {
13548   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13549 
13550   LambdaScopeInfo *LSI = S.PushLambdaScope();
13551   LSI->CallOperator = CallOperator;
13552   LSI->Lambda = LambdaClass;
13553   LSI->ReturnType = CallOperator->getReturnType();
13554   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13555 
13556   if (LCD == LCD_None)
13557     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13558   else if (LCD == LCD_ByCopy)
13559     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13560   else if (LCD == LCD_ByRef)
13561     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13562   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13563 
13564   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13565   LSI->Mutable = !CallOperator->isConst();
13566 
13567   // Add the captures to the LSI so they can be noted as already
13568   // captured within tryCaptureVar.
13569   auto I = LambdaClass->field_begin();
13570   for (const auto &C : LambdaClass->captures()) {
13571     if (C.capturesVariable()) {
13572       VarDecl *VD = C.getCapturedVar();
13573       if (VD->isInitCapture())
13574         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13575       QualType CaptureType = VD->getType();
13576       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13577       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13578           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13579           /*EllipsisLoc*/C.isPackExpansion()
13580                          ? C.getEllipsisLoc() : SourceLocation(),
13581           CaptureType, /*Invalid*/false);
13582 
13583     } else if (C.capturesThis()) {
13584       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13585                           C.getCaptureKind() == LCK_StarThis);
13586     } else {
13587       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13588                              I->getType());
13589     }
13590     ++I;
13591   }
13592 }
13593 
13594 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13595                                     SkipBodyInfo *SkipBody) {
13596   if (!D) {
13597     // Parsing the function declaration failed in some way. Push on a fake scope
13598     // anyway so we can try to parse the function body.
13599     PushFunctionScope();
13600     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13601     return D;
13602   }
13603 
13604   FunctionDecl *FD = nullptr;
13605 
13606   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13607     FD = FunTmpl->getTemplatedDecl();
13608   else
13609     FD = cast<FunctionDecl>(D);
13610 
13611   // Do not push if it is a lambda because one is already pushed when building
13612   // the lambda in ActOnStartOfLambdaDefinition().
13613   if (!isLambdaCallOperator(FD))
13614     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13615 
13616   // Check for defining attributes before the check for redefinition.
13617   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13618     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13619     FD->dropAttr<AliasAttr>();
13620     FD->setInvalidDecl();
13621   }
13622   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13623     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13624     FD->dropAttr<IFuncAttr>();
13625     FD->setInvalidDecl();
13626   }
13627 
13628   // See if this is a redefinition. If 'will have body' is already set, then
13629   // these checks were already performed when it was set.
13630   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13631     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13632 
13633     // If we're skipping the body, we're done. Don't enter the scope.
13634     if (SkipBody && SkipBody->ShouldSkip)
13635       return D;
13636   }
13637 
13638   // Mark this function as "will have a body eventually".  This lets users to
13639   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13640   // this function.
13641   FD->setWillHaveBody();
13642 
13643   // If we are instantiating a generic lambda call operator, push
13644   // a LambdaScopeInfo onto the function stack.  But use the information
13645   // that's already been calculated (ActOnLambdaExpr) to prime the current
13646   // LambdaScopeInfo.
13647   // When the template operator is being specialized, the LambdaScopeInfo,
13648   // has to be properly restored so that tryCaptureVariable doesn't try
13649   // and capture any new variables. In addition when calculating potential
13650   // captures during transformation of nested lambdas, it is necessary to
13651   // have the LSI properly restored.
13652   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13653     assert(inTemplateInstantiation() &&
13654            "There should be an active template instantiation on the stack "
13655            "when instantiating a generic lambda!");
13656     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13657   } else {
13658     // Enter a new function scope
13659     PushFunctionScope();
13660   }
13661 
13662   // Builtin functions cannot be defined.
13663   if (unsigned BuiltinID = FD->getBuiltinID()) {
13664     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13665         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13666       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13667       FD->setInvalidDecl();
13668     }
13669   }
13670 
13671   // The return type of a function definition must be complete
13672   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13673   QualType ResultType = FD->getReturnType();
13674   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13675       !FD->isInvalidDecl() &&
13676       RequireCompleteType(FD->getLocation(), ResultType,
13677                           diag::err_func_def_incomplete_result))
13678     FD->setInvalidDecl();
13679 
13680   if (FnBodyScope)
13681     PushDeclContext(FnBodyScope, FD);
13682 
13683   // Check the validity of our function parameters
13684   CheckParmsForFunctionDef(FD->parameters(),
13685                            /*CheckParameterNames=*/true);
13686 
13687   // Add non-parameter declarations already in the function to the current
13688   // scope.
13689   if (FnBodyScope) {
13690     for (Decl *NPD : FD->decls()) {
13691       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13692       if (!NonParmDecl)
13693         continue;
13694       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13695              "parameters should not be in newly created FD yet");
13696 
13697       // If the decl has a name, make it accessible in the current scope.
13698       if (NonParmDecl->getDeclName())
13699         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13700 
13701       // Similarly, dive into enums and fish their constants out, making them
13702       // accessible in this scope.
13703       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13704         for (auto *EI : ED->enumerators())
13705           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13706       }
13707     }
13708   }
13709 
13710   // Introduce our parameters into the function scope
13711   for (auto Param : FD->parameters()) {
13712     Param->setOwningFunction(FD);
13713 
13714     // If this has an identifier, add it to the scope stack.
13715     if (Param->getIdentifier() && FnBodyScope) {
13716       CheckShadow(FnBodyScope, Param);
13717 
13718       PushOnScopeChains(Param, FnBodyScope);
13719     }
13720   }
13721 
13722   // Ensure that the function's exception specification is instantiated.
13723   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13724     ResolveExceptionSpec(D->getLocation(), FPT);
13725 
13726   // dllimport cannot be applied to non-inline function definitions.
13727   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13728       !FD->isTemplateInstantiation()) {
13729     assert(!FD->hasAttr<DLLExportAttr>());
13730     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13731     FD->setInvalidDecl();
13732     return D;
13733   }
13734   // We want to attach documentation to original Decl (which might be
13735   // a function template).
13736   ActOnDocumentableDecl(D);
13737   if (getCurLexicalContext()->isObjCContainer() &&
13738       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13739       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13740     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13741 
13742   return D;
13743 }
13744 
13745 /// Given the set of return statements within a function body,
13746 /// compute the variables that are subject to the named return value
13747 /// optimization.
13748 ///
13749 /// Each of the variables that is subject to the named return value
13750 /// optimization will be marked as NRVO variables in the AST, and any
13751 /// return statement that has a marked NRVO variable as its NRVO candidate can
13752 /// use the named return value optimization.
13753 ///
13754 /// This function applies a very simplistic algorithm for NRVO: if every return
13755 /// statement in the scope of a variable has the same NRVO candidate, that
13756 /// candidate is an NRVO variable.
13757 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13758   ReturnStmt **Returns = Scope->Returns.data();
13759 
13760   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13761     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13762       if (!NRVOCandidate->isNRVOVariable())
13763         Returns[I]->setNRVOCandidate(nullptr);
13764     }
13765   }
13766 }
13767 
13768 bool Sema::canDelayFunctionBody(const Declarator &D) {
13769   // We can't delay parsing the body of a constexpr function template (yet).
13770   if (D.getDeclSpec().hasConstexprSpecifier())
13771     return false;
13772 
13773   // We can't delay parsing the body of a function template with a deduced
13774   // return type (yet).
13775   if (D.getDeclSpec().hasAutoTypeSpec()) {
13776     // If the placeholder introduces a non-deduced trailing return type,
13777     // we can still delay parsing it.
13778     if (D.getNumTypeObjects()) {
13779       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13780       if (Outer.Kind == DeclaratorChunk::Function &&
13781           Outer.Fun.hasTrailingReturnType()) {
13782         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13783         return Ty.isNull() || !Ty->isUndeducedType();
13784       }
13785     }
13786     return false;
13787   }
13788 
13789   return true;
13790 }
13791 
13792 bool Sema::canSkipFunctionBody(Decl *D) {
13793   // We cannot skip the body of a function (or function template) which is
13794   // constexpr, since we may need to evaluate its body in order to parse the
13795   // rest of the file.
13796   // We cannot skip the body of a function with an undeduced return type,
13797   // because any callers of that function need to know the type.
13798   if (const FunctionDecl *FD = D->getAsFunction()) {
13799     if (FD->isConstexpr())
13800       return false;
13801     // We can't simply call Type::isUndeducedType here, because inside template
13802     // auto can be deduced to a dependent type, which is not considered
13803     // "undeduced".
13804     if (FD->getReturnType()->getContainedDeducedType())
13805       return false;
13806   }
13807   return Consumer.shouldSkipFunctionBody(D);
13808 }
13809 
13810 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13811   if (!Decl)
13812     return nullptr;
13813   if (FunctionDecl *FD = Decl->getAsFunction())
13814     FD->setHasSkippedBody();
13815   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13816     MD->setHasSkippedBody();
13817   return Decl;
13818 }
13819 
13820 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13821   return ActOnFinishFunctionBody(D, BodyArg, false);
13822 }
13823 
13824 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13825 /// body.
13826 class ExitFunctionBodyRAII {
13827 public:
13828   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13829   ~ExitFunctionBodyRAII() {
13830     if (!IsLambda)
13831       S.PopExpressionEvaluationContext();
13832   }
13833 
13834 private:
13835   Sema &S;
13836   bool IsLambda = false;
13837 };
13838 
13839 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13840   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13841 
13842   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13843     if (EscapeInfo.count(BD))
13844       return EscapeInfo[BD];
13845 
13846     bool R = false;
13847     const BlockDecl *CurBD = BD;
13848 
13849     do {
13850       R = !CurBD->doesNotEscape();
13851       if (R)
13852         break;
13853       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13854     } while (CurBD);
13855 
13856     return EscapeInfo[BD] = R;
13857   };
13858 
13859   // If the location where 'self' is implicitly retained is inside a escaping
13860   // block, emit a diagnostic.
13861   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13862        S.ImplicitlyRetainedSelfLocs)
13863     if (IsOrNestedInEscapingBlock(P.second))
13864       S.Diag(P.first, diag::warn_implicitly_retains_self)
13865           << FixItHint::CreateInsertion(P.first, "self->");
13866 }
13867 
13868 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13869                                     bool IsInstantiation) {
13870   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13871 
13872   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13873   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13874 
13875   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13876     CheckCompletedCoroutineBody(FD, Body);
13877 
13878   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13879   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13880   // meant to pop the context added in ActOnStartOfFunctionDef().
13881   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13882 
13883   if (FD) {
13884     FD->setBody(Body);
13885     FD->setWillHaveBody(false);
13886 
13887     if (getLangOpts().CPlusPlus14) {
13888       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13889           FD->getReturnType()->isUndeducedType()) {
13890         // If the function has a deduced result type but contains no 'return'
13891         // statements, the result type as written must be exactly 'auto', and
13892         // the deduced result type is 'void'.
13893         if (!FD->getReturnType()->getAs<AutoType>()) {
13894           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13895               << FD->getReturnType();
13896           FD->setInvalidDecl();
13897         } else {
13898           // Substitute 'void' for the 'auto' in the type.
13899           TypeLoc ResultType = getReturnTypeLoc(FD);
13900           Context.adjustDeducedFunctionResultType(
13901               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13902         }
13903       }
13904     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13905       // In C++11, we don't use 'auto' deduction rules for lambda call
13906       // operators because we don't support return type deduction.
13907       auto *LSI = getCurLambda();
13908       if (LSI->HasImplicitReturnType) {
13909         deduceClosureReturnType(*LSI);
13910 
13911         // C++11 [expr.prim.lambda]p4:
13912         //   [...] if there are no return statements in the compound-statement
13913         //   [the deduced type is] the type void
13914         QualType RetType =
13915             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13916 
13917         // Update the return type to the deduced type.
13918         const FunctionProtoType *Proto =
13919             FD->getType()->getAs<FunctionProtoType>();
13920         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13921                                             Proto->getExtProtoInfo()));
13922       }
13923     }
13924 
13925     // If the function implicitly returns zero (like 'main') or is naked,
13926     // don't complain about missing return statements.
13927     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13928       WP.disableCheckFallThrough();
13929 
13930     // MSVC permits the use of pure specifier (=0) on function definition,
13931     // defined at class scope, warn about this non-standard construct.
13932     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13933       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13934 
13935     if (!FD->isInvalidDecl()) {
13936       // Don't diagnose unused parameters of defaulted or deleted functions.
13937       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13938         DiagnoseUnusedParameters(FD->parameters());
13939       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13940                                              FD->getReturnType(), FD);
13941 
13942       // If this is a structor, we need a vtable.
13943       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13944         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13945       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13946         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13947 
13948       // Try to apply the named return value optimization. We have to check
13949       // if we can do this here because lambdas keep return statements around
13950       // to deduce an implicit return type.
13951       if (FD->getReturnType()->isRecordType() &&
13952           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13953         computeNRVO(Body, getCurFunction());
13954     }
13955 
13956     // GNU warning -Wmissing-prototypes:
13957     //   Warn if a global function is defined without a previous
13958     //   prototype declaration. This warning is issued even if the
13959     //   definition itself provides a prototype. The aim is to detect
13960     //   global functions that fail to be declared in header files.
13961     const FunctionDecl *PossiblePrototype = nullptr;
13962     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13963       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13964 
13965       if (PossiblePrototype) {
13966         // We found a declaration that is not a prototype,
13967         // but that could be a zero-parameter prototype
13968         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13969           TypeLoc TL = TI->getTypeLoc();
13970           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13971             Diag(PossiblePrototype->getLocation(),
13972                  diag::note_declaration_not_a_prototype)
13973                 << (FD->getNumParams() != 0)
13974                 << (FD->getNumParams() == 0
13975                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13976                         : FixItHint{});
13977         }
13978       } else {
13979         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13980             << /* function */ 1
13981             << (FD->getStorageClass() == SC_None
13982                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13983                                                  "static ")
13984                     : FixItHint{});
13985       }
13986 
13987       // GNU warning -Wstrict-prototypes
13988       //   Warn if K&R function is defined without a previous declaration.
13989       //   This warning is issued only if the definition itself does not provide
13990       //   a prototype. Only K&R definitions do not provide a prototype.
13991       //   An empty list in a function declarator that is part of a definition
13992       //   of that function specifies that the function has no parameters
13993       //   (C99 6.7.5.3p14)
13994       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13995           !LangOpts.CPlusPlus) {
13996         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13997         TypeLoc TL = TI->getTypeLoc();
13998         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13999         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14000       }
14001     }
14002 
14003     // Warn on CPUDispatch with an actual body.
14004     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14005       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14006         if (!CmpndBody->body_empty())
14007           Diag(CmpndBody->body_front()->getBeginLoc(),
14008                diag::warn_dispatch_body_ignored);
14009 
14010     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14011       const CXXMethodDecl *KeyFunction;
14012       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14013           MD->isVirtual() &&
14014           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14015           MD == KeyFunction->getCanonicalDecl()) {
14016         // Update the key-function state if necessary for this ABI.
14017         if (FD->isInlined() &&
14018             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14019           Context.setNonKeyFunction(MD);
14020 
14021           // If the newly-chosen key function is already defined, then we
14022           // need to mark the vtable as used retroactively.
14023           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14024           const FunctionDecl *Definition;
14025           if (KeyFunction && KeyFunction->isDefined(Definition))
14026             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14027         } else {
14028           // We just defined they key function; mark the vtable as used.
14029           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14030         }
14031       }
14032     }
14033 
14034     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14035            "Function parsing confused");
14036   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14037     assert(MD == getCurMethodDecl() && "Method parsing confused");
14038     MD->setBody(Body);
14039     if (!MD->isInvalidDecl()) {
14040       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14041                                              MD->getReturnType(), MD);
14042 
14043       if (Body)
14044         computeNRVO(Body, getCurFunction());
14045     }
14046     if (getCurFunction()->ObjCShouldCallSuper) {
14047       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14048           << MD->getSelector().getAsString();
14049       getCurFunction()->ObjCShouldCallSuper = false;
14050     }
14051     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14052       const ObjCMethodDecl *InitMethod = nullptr;
14053       bool isDesignated =
14054           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14055       assert(isDesignated && InitMethod);
14056       (void)isDesignated;
14057 
14058       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14059         auto IFace = MD->getClassInterface();
14060         if (!IFace)
14061           return false;
14062         auto SuperD = IFace->getSuperClass();
14063         if (!SuperD)
14064           return false;
14065         return SuperD->getIdentifier() ==
14066             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14067       };
14068       // Don't issue this warning for unavailable inits or direct subclasses
14069       // of NSObject.
14070       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14071         Diag(MD->getLocation(),
14072              diag::warn_objc_designated_init_missing_super_call);
14073         Diag(InitMethod->getLocation(),
14074              diag::note_objc_designated_init_marked_here);
14075       }
14076       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14077     }
14078     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14079       // Don't issue this warning for unavaialable inits.
14080       if (!MD->isUnavailable())
14081         Diag(MD->getLocation(),
14082              diag::warn_objc_secondary_init_missing_init_call);
14083       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14084     }
14085 
14086     diagnoseImplicitlyRetainedSelf(*this);
14087   } else {
14088     // Parsing the function declaration failed in some way. Pop the fake scope
14089     // we pushed on.
14090     PopFunctionScopeInfo(ActivePolicy, dcl);
14091     return nullptr;
14092   }
14093 
14094   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14095     DiagnoseUnguardedAvailabilityViolations(dcl);
14096 
14097   assert(!getCurFunction()->ObjCShouldCallSuper &&
14098          "This should only be set for ObjC methods, which should have been "
14099          "handled in the block above.");
14100 
14101   // Verify and clean out per-function state.
14102   if (Body && (!FD || !FD->isDefaulted())) {
14103     // C++ constructors that have function-try-blocks can't have return
14104     // statements in the handlers of that block. (C++ [except.handle]p14)
14105     // Verify this.
14106     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14107       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14108 
14109     // Verify that gotos and switch cases don't jump into scopes illegally.
14110     if (getCurFunction()->NeedsScopeChecking() &&
14111         !PP.isCodeCompletionEnabled())
14112       DiagnoseInvalidJumps(Body);
14113 
14114     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14115       if (!Destructor->getParent()->isDependentType())
14116         CheckDestructor(Destructor);
14117 
14118       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14119                                              Destructor->getParent());
14120     }
14121 
14122     // If any errors have occurred, clear out any temporaries that may have
14123     // been leftover. This ensures that these temporaries won't be picked up for
14124     // deletion in some later function.
14125     if (getDiagnostics().hasErrorOccurred() ||
14126         getDiagnostics().getSuppressAllDiagnostics()) {
14127       DiscardCleanupsInEvaluationContext();
14128     }
14129     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14130         !isa<FunctionTemplateDecl>(dcl)) {
14131       // Since the body is valid, issue any analysis-based warnings that are
14132       // enabled.
14133       ActivePolicy = &WP;
14134     }
14135 
14136     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14137         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14138       FD->setInvalidDecl();
14139 
14140     if (FD && FD->hasAttr<NakedAttr>()) {
14141       for (const Stmt *S : Body->children()) {
14142         // Allow local register variables without initializer as they don't
14143         // require prologue.
14144         bool RegisterVariables = false;
14145         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14146           for (const auto *Decl : DS->decls()) {
14147             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14148               RegisterVariables =
14149                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14150               if (!RegisterVariables)
14151                 break;
14152             }
14153           }
14154         }
14155         if (RegisterVariables)
14156           continue;
14157         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14158           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14159           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14160           FD->setInvalidDecl();
14161           break;
14162         }
14163       }
14164     }
14165 
14166     assert(ExprCleanupObjects.size() ==
14167                ExprEvalContexts.back().NumCleanupObjects &&
14168            "Leftover temporaries in function");
14169     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14170     assert(MaybeODRUseExprs.empty() &&
14171            "Leftover expressions for odr-use checking");
14172   }
14173 
14174   if (!IsInstantiation)
14175     PopDeclContext();
14176 
14177   PopFunctionScopeInfo(ActivePolicy, dcl);
14178   // If any errors have occurred, clear out any temporaries that may have
14179   // been leftover. This ensures that these temporaries won't be picked up for
14180   // deletion in some later function.
14181   if (getDiagnostics().hasErrorOccurred()) {
14182     DiscardCleanupsInEvaluationContext();
14183   }
14184 
14185   return dcl;
14186 }
14187 
14188 /// When we finish delayed parsing of an attribute, we must attach it to the
14189 /// relevant Decl.
14190 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14191                                        ParsedAttributes &Attrs) {
14192   // Always attach attributes to the underlying decl.
14193   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14194     D = TD->getTemplatedDecl();
14195   ProcessDeclAttributeList(S, D, Attrs);
14196 
14197   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14198     if (Method->isStatic())
14199       checkThisInStaticMemberFunctionAttributes(Method);
14200 }
14201 
14202 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14203 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14204 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14205                                           IdentifierInfo &II, Scope *S) {
14206   // Find the scope in which the identifier is injected and the corresponding
14207   // DeclContext.
14208   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14209   // In that case, we inject the declaration into the translation unit scope
14210   // instead.
14211   Scope *BlockScope = S;
14212   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14213     BlockScope = BlockScope->getParent();
14214 
14215   Scope *ContextScope = BlockScope;
14216   while (!ContextScope->getEntity())
14217     ContextScope = ContextScope->getParent();
14218   ContextRAII SavedContext(*this, ContextScope->getEntity());
14219 
14220   // Before we produce a declaration for an implicitly defined
14221   // function, see whether there was a locally-scoped declaration of
14222   // this name as a function or variable. If so, use that
14223   // (non-visible) declaration, and complain about it.
14224   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14225   if (ExternCPrev) {
14226     // We still need to inject the function into the enclosing block scope so
14227     // that later (non-call) uses can see it.
14228     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14229 
14230     // C89 footnote 38:
14231     //   If in fact it is not defined as having type "function returning int",
14232     //   the behavior is undefined.
14233     if (!isa<FunctionDecl>(ExternCPrev) ||
14234         !Context.typesAreCompatible(
14235             cast<FunctionDecl>(ExternCPrev)->getType(),
14236             Context.getFunctionNoProtoType(Context.IntTy))) {
14237       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14238           << ExternCPrev << !getLangOpts().C99;
14239       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14240       return ExternCPrev;
14241     }
14242   }
14243 
14244   // Extension in C99.  Legal in C90, but warn about it.
14245   unsigned diag_id;
14246   if (II.getName().startswith("__builtin_"))
14247     diag_id = diag::warn_builtin_unknown;
14248   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14249   else if (getLangOpts().OpenCL)
14250     diag_id = diag::err_opencl_implicit_function_decl;
14251   else if (getLangOpts().C99)
14252     diag_id = diag::ext_implicit_function_decl;
14253   else
14254     diag_id = diag::warn_implicit_function_decl;
14255   Diag(Loc, diag_id) << &II;
14256 
14257   // If we found a prior declaration of this function, don't bother building
14258   // another one. We've already pushed that one into scope, so there's nothing
14259   // more to do.
14260   if (ExternCPrev)
14261     return ExternCPrev;
14262 
14263   // Because typo correction is expensive, only do it if the implicit
14264   // function declaration is going to be treated as an error.
14265   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14266     TypoCorrection Corrected;
14267     DeclFilterCCC<FunctionDecl> CCC{};
14268     if (S && (Corrected =
14269                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14270                               S, nullptr, CCC, CTK_NonError)))
14271       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14272                    /*ErrorRecovery*/false);
14273   }
14274 
14275   // Set a Declarator for the implicit definition: int foo();
14276   const char *Dummy;
14277   AttributeFactory attrFactory;
14278   DeclSpec DS(attrFactory);
14279   unsigned DiagID;
14280   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14281                                   Context.getPrintingPolicy());
14282   (void)Error; // Silence warning.
14283   assert(!Error && "Error setting up implicit decl!");
14284   SourceLocation NoLoc;
14285   Declarator D(DS, DeclaratorContext::BlockContext);
14286   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14287                                              /*IsAmbiguous=*/false,
14288                                              /*LParenLoc=*/NoLoc,
14289                                              /*Params=*/nullptr,
14290                                              /*NumParams=*/0,
14291                                              /*EllipsisLoc=*/NoLoc,
14292                                              /*RParenLoc=*/NoLoc,
14293                                              /*RefQualifierIsLvalueRef=*/true,
14294                                              /*RefQualifierLoc=*/NoLoc,
14295                                              /*MutableLoc=*/NoLoc, EST_None,
14296                                              /*ESpecRange=*/SourceRange(),
14297                                              /*Exceptions=*/nullptr,
14298                                              /*ExceptionRanges=*/nullptr,
14299                                              /*NumExceptions=*/0,
14300                                              /*NoexceptExpr=*/nullptr,
14301                                              /*ExceptionSpecTokens=*/nullptr,
14302                                              /*DeclsInPrototype=*/None, Loc,
14303                                              Loc, D),
14304                 std::move(DS.getAttributes()), SourceLocation());
14305   D.SetIdentifier(&II, Loc);
14306 
14307   // Insert this function into the enclosing block scope.
14308   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14309   FD->setImplicit();
14310 
14311   AddKnownFunctionAttributes(FD);
14312 
14313   return FD;
14314 }
14315 
14316 /// Adds any function attributes that we know a priori based on
14317 /// the declaration of this function.
14318 ///
14319 /// These attributes can apply both to implicitly-declared builtins
14320 /// (like __builtin___printf_chk) or to library-declared functions
14321 /// like NSLog or printf.
14322 ///
14323 /// We need to check for duplicate attributes both here and where user-written
14324 /// attributes are applied to declarations.
14325 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14326   if (FD->isInvalidDecl())
14327     return;
14328 
14329   // If this is a built-in function, map its builtin attributes to
14330   // actual attributes.
14331   if (unsigned BuiltinID = FD->getBuiltinID()) {
14332     // Handle printf-formatting attributes.
14333     unsigned FormatIdx;
14334     bool HasVAListArg;
14335     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14336       if (!FD->hasAttr<FormatAttr>()) {
14337         const char *fmt = "printf";
14338         unsigned int NumParams = FD->getNumParams();
14339         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14340             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14341           fmt = "NSString";
14342         FD->addAttr(FormatAttr::CreateImplicit(Context,
14343                                                &Context.Idents.get(fmt),
14344                                                FormatIdx+1,
14345                                                HasVAListArg ? 0 : FormatIdx+2,
14346                                                FD->getLocation()));
14347       }
14348     }
14349     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14350                                              HasVAListArg)) {
14351      if (!FD->hasAttr<FormatAttr>())
14352        FD->addAttr(FormatAttr::CreateImplicit(Context,
14353                                               &Context.Idents.get("scanf"),
14354                                               FormatIdx+1,
14355                                               HasVAListArg ? 0 : FormatIdx+2,
14356                                               FD->getLocation()));
14357     }
14358 
14359     // Handle automatically recognized callbacks.
14360     SmallVector<int, 4> Encoding;
14361     if (!FD->hasAttr<CallbackAttr>() &&
14362         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14363       FD->addAttr(CallbackAttr::CreateImplicit(
14364           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14365 
14366     // Mark const if we don't care about errno and that is the only thing
14367     // preventing the function from being const. This allows IRgen to use LLVM
14368     // intrinsics for such functions.
14369     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14370         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14371       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14372 
14373     // We make "fma" on some platforms const because we know it does not set
14374     // errno in those environments even though it could set errno based on the
14375     // C standard.
14376     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14377     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14378         !FD->hasAttr<ConstAttr>()) {
14379       switch (BuiltinID) {
14380       case Builtin::BI__builtin_fma:
14381       case Builtin::BI__builtin_fmaf:
14382       case Builtin::BI__builtin_fmal:
14383       case Builtin::BIfma:
14384       case Builtin::BIfmaf:
14385       case Builtin::BIfmal:
14386         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14387         break;
14388       default:
14389         break;
14390       }
14391     }
14392 
14393     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14394         !FD->hasAttr<ReturnsTwiceAttr>())
14395       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14396                                          FD->getLocation()));
14397     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14398       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14399     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14400       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14401     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14402       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14403     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14404         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14405       // Add the appropriate attribute, depending on the CUDA compilation mode
14406       // and which target the builtin belongs to. For example, during host
14407       // compilation, aux builtins are __device__, while the rest are __host__.
14408       if (getLangOpts().CUDAIsDevice !=
14409           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14410         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14411       else
14412         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14413     }
14414   }
14415 
14416   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14417   // throw, add an implicit nothrow attribute to any extern "C" function we come
14418   // across.
14419   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14420       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14421     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14422     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14423       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14424   }
14425 
14426   IdentifierInfo *Name = FD->getIdentifier();
14427   if (!Name)
14428     return;
14429   if ((!getLangOpts().CPlusPlus &&
14430        FD->getDeclContext()->isTranslationUnit()) ||
14431       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14432        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14433        LinkageSpecDecl::lang_c)) {
14434     // Okay: this could be a libc/libm/Objective-C function we know
14435     // about.
14436   } else
14437     return;
14438 
14439   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14440     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14441     // target-specific builtins, perhaps?
14442     if (!FD->hasAttr<FormatAttr>())
14443       FD->addAttr(FormatAttr::CreateImplicit(Context,
14444                                              &Context.Idents.get("printf"), 2,
14445                                              Name->isStr("vasprintf") ? 0 : 3,
14446                                              FD->getLocation()));
14447   }
14448 
14449   if (Name->isStr("__CFStringMakeConstantString")) {
14450     // We already have a __builtin___CFStringMakeConstantString,
14451     // but builds that use -fno-constant-cfstrings don't go through that.
14452     if (!FD->hasAttr<FormatArgAttr>())
14453       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14454                                                 FD->getLocation()));
14455   }
14456 }
14457 
14458 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14459                                     TypeSourceInfo *TInfo) {
14460   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14461   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14462 
14463   if (!TInfo) {
14464     assert(D.isInvalidType() && "no declarator info for valid type");
14465     TInfo = Context.getTrivialTypeSourceInfo(T);
14466   }
14467 
14468   // Scope manipulation handled by caller.
14469   TypedefDecl *NewTD =
14470       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14471                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14472 
14473   // Bail out immediately if we have an invalid declaration.
14474   if (D.isInvalidType()) {
14475     NewTD->setInvalidDecl();
14476     return NewTD;
14477   }
14478 
14479   if (D.getDeclSpec().isModulePrivateSpecified()) {
14480     if (CurContext->isFunctionOrMethod())
14481       Diag(NewTD->getLocation(), diag::err_module_private_local)
14482         << 2 << NewTD->getDeclName()
14483         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14484         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14485     else
14486       NewTD->setModulePrivate();
14487   }
14488 
14489   // C++ [dcl.typedef]p8:
14490   //   If the typedef declaration defines an unnamed class (or
14491   //   enum), the first typedef-name declared by the declaration
14492   //   to be that class type (or enum type) is used to denote the
14493   //   class type (or enum type) for linkage purposes only.
14494   // We need to check whether the type was declared in the declaration.
14495   switch (D.getDeclSpec().getTypeSpecType()) {
14496   case TST_enum:
14497   case TST_struct:
14498   case TST_interface:
14499   case TST_union:
14500   case TST_class: {
14501     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14502     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14503     break;
14504   }
14505 
14506   default:
14507     break;
14508   }
14509 
14510   return NewTD;
14511 }
14512 
14513 /// Check that this is a valid underlying type for an enum declaration.
14514 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14515   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14516   QualType T = TI->getType();
14517 
14518   if (T->isDependentType())
14519     return false;
14520 
14521   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14522     if (BT->isInteger())
14523       return false;
14524 
14525   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14526   return true;
14527 }
14528 
14529 /// Check whether this is a valid redeclaration of a previous enumeration.
14530 /// \return true if the redeclaration was invalid.
14531 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14532                                   QualType EnumUnderlyingTy, bool IsFixed,
14533                                   const EnumDecl *Prev) {
14534   if (IsScoped != Prev->isScoped()) {
14535     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14536       << Prev->isScoped();
14537     Diag(Prev->getLocation(), diag::note_previous_declaration);
14538     return true;
14539   }
14540 
14541   if (IsFixed && Prev->isFixed()) {
14542     if (!EnumUnderlyingTy->isDependentType() &&
14543         !Prev->getIntegerType()->isDependentType() &&
14544         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14545                                         Prev->getIntegerType())) {
14546       // TODO: Highlight the underlying type of the redeclaration.
14547       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14548         << EnumUnderlyingTy << Prev->getIntegerType();
14549       Diag(Prev->getLocation(), diag::note_previous_declaration)
14550           << Prev->getIntegerTypeRange();
14551       return true;
14552     }
14553   } else if (IsFixed != Prev->isFixed()) {
14554     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14555       << Prev->isFixed();
14556     Diag(Prev->getLocation(), diag::note_previous_declaration);
14557     return true;
14558   }
14559 
14560   return false;
14561 }
14562 
14563 /// Get diagnostic %select index for tag kind for
14564 /// redeclaration diagnostic message.
14565 /// WARNING: Indexes apply to particular diagnostics only!
14566 ///
14567 /// \returns diagnostic %select index.
14568 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14569   switch (Tag) {
14570   case TTK_Struct: return 0;
14571   case TTK_Interface: return 1;
14572   case TTK_Class:  return 2;
14573   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14574   }
14575 }
14576 
14577 /// Determine if tag kind is a class-key compatible with
14578 /// class for redeclaration (class, struct, or __interface).
14579 ///
14580 /// \returns true iff the tag kind is compatible.
14581 static bool isClassCompatTagKind(TagTypeKind Tag)
14582 {
14583   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14584 }
14585 
14586 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14587                                              TagTypeKind TTK) {
14588   if (isa<TypedefDecl>(PrevDecl))
14589     return NTK_Typedef;
14590   else if (isa<TypeAliasDecl>(PrevDecl))
14591     return NTK_TypeAlias;
14592   else if (isa<ClassTemplateDecl>(PrevDecl))
14593     return NTK_Template;
14594   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14595     return NTK_TypeAliasTemplate;
14596   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14597     return NTK_TemplateTemplateArgument;
14598   switch (TTK) {
14599   case TTK_Struct:
14600   case TTK_Interface:
14601   case TTK_Class:
14602     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14603   case TTK_Union:
14604     return NTK_NonUnion;
14605   case TTK_Enum:
14606     return NTK_NonEnum;
14607   }
14608   llvm_unreachable("invalid TTK");
14609 }
14610 
14611 /// Determine whether a tag with a given kind is acceptable
14612 /// as a redeclaration of the given tag declaration.
14613 ///
14614 /// \returns true if the new tag kind is acceptable, false otherwise.
14615 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14616                                         TagTypeKind NewTag, bool isDefinition,
14617                                         SourceLocation NewTagLoc,
14618                                         const IdentifierInfo *Name) {
14619   // C++ [dcl.type.elab]p3:
14620   //   The class-key or enum keyword present in the
14621   //   elaborated-type-specifier shall agree in kind with the
14622   //   declaration to which the name in the elaborated-type-specifier
14623   //   refers. This rule also applies to the form of
14624   //   elaborated-type-specifier that declares a class-name or
14625   //   friend class since it can be construed as referring to the
14626   //   definition of the class. Thus, in any
14627   //   elaborated-type-specifier, the enum keyword shall be used to
14628   //   refer to an enumeration (7.2), the union class-key shall be
14629   //   used to refer to a union (clause 9), and either the class or
14630   //   struct class-key shall be used to refer to a class (clause 9)
14631   //   declared using the class or struct class-key.
14632   TagTypeKind OldTag = Previous->getTagKind();
14633   if (OldTag != NewTag &&
14634       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14635     return false;
14636 
14637   // Tags are compatible, but we might still want to warn on mismatched tags.
14638   // Non-class tags can't be mismatched at this point.
14639   if (!isClassCompatTagKind(NewTag))
14640     return true;
14641 
14642   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14643   // by our warning analysis. We don't want to warn about mismatches with (eg)
14644   // declarations in system headers that are designed to be specialized, but if
14645   // a user asks us to warn, we should warn if their code contains mismatched
14646   // declarations.
14647   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14648     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14649                                       Loc);
14650   };
14651   if (IsIgnoredLoc(NewTagLoc))
14652     return true;
14653 
14654   auto IsIgnored = [&](const TagDecl *Tag) {
14655     return IsIgnoredLoc(Tag->getLocation());
14656   };
14657   while (IsIgnored(Previous)) {
14658     Previous = Previous->getPreviousDecl();
14659     if (!Previous)
14660       return true;
14661     OldTag = Previous->getTagKind();
14662   }
14663 
14664   bool isTemplate = false;
14665   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14666     isTemplate = Record->getDescribedClassTemplate();
14667 
14668   if (inTemplateInstantiation()) {
14669     if (OldTag != NewTag) {
14670       // In a template instantiation, do not offer fix-its for tag mismatches
14671       // since they usually mess up the template instead of fixing the problem.
14672       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14673         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14674         << getRedeclDiagFromTagKind(OldTag);
14675       // FIXME: Note previous location?
14676     }
14677     return true;
14678   }
14679 
14680   if (isDefinition) {
14681     // On definitions, check all previous tags and issue a fix-it for each
14682     // one that doesn't match the current tag.
14683     if (Previous->getDefinition()) {
14684       // Don't suggest fix-its for redefinitions.
14685       return true;
14686     }
14687 
14688     bool previousMismatch = false;
14689     for (const TagDecl *I : Previous->redecls()) {
14690       if (I->getTagKind() != NewTag) {
14691         // Ignore previous declarations for which the warning was disabled.
14692         if (IsIgnored(I))
14693           continue;
14694 
14695         if (!previousMismatch) {
14696           previousMismatch = true;
14697           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14698             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14699             << getRedeclDiagFromTagKind(I->getTagKind());
14700         }
14701         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14702           << getRedeclDiagFromTagKind(NewTag)
14703           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14704                TypeWithKeyword::getTagTypeKindName(NewTag));
14705       }
14706     }
14707     return true;
14708   }
14709 
14710   // Identify the prevailing tag kind: this is the kind of the definition (if
14711   // there is a non-ignored definition), or otherwise the kind of the prior
14712   // (non-ignored) declaration.
14713   const TagDecl *PrevDef = Previous->getDefinition();
14714   if (PrevDef && IsIgnored(PrevDef))
14715     PrevDef = nullptr;
14716   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14717   if (Redecl->getTagKind() != NewTag) {
14718     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14719       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14720       << getRedeclDiagFromTagKind(OldTag);
14721     Diag(Redecl->getLocation(), diag::note_previous_use);
14722 
14723     // If there is a previous definition, suggest a fix-it.
14724     if (PrevDef) {
14725       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14726         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14727         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14728              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14729     }
14730   }
14731 
14732   return true;
14733 }
14734 
14735 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14736 /// from an outer enclosing namespace or file scope inside a friend declaration.
14737 /// This should provide the commented out code in the following snippet:
14738 ///   namespace N {
14739 ///     struct X;
14740 ///     namespace M {
14741 ///       struct Y { friend struct /*N::*/ X; };
14742 ///     }
14743 ///   }
14744 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14745                                          SourceLocation NameLoc) {
14746   // While the decl is in a namespace, do repeated lookup of that name and see
14747   // if we get the same namespace back.  If we do not, continue until
14748   // translation unit scope, at which point we have a fully qualified NNS.
14749   SmallVector<IdentifierInfo *, 4> Namespaces;
14750   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14751   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14752     // This tag should be declared in a namespace, which can only be enclosed by
14753     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14754     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14755     if (!Namespace || Namespace->isAnonymousNamespace())
14756       return FixItHint();
14757     IdentifierInfo *II = Namespace->getIdentifier();
14758     Namespaces.push_back(II);
14759     NamedDecl *Lookup = SemaRef.LookupSingleName(
14760         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14761     if (Lookup == Namespace)
14762       break;
14763   }
14764 
14765   // Once we have all the namespaces, reverse them to go outermost first, and
14766   // build an NNS.
14767   SmallString<64> Insertion;
14768   llvm::raw_svector_ostream OS(Insertion);
14769   if (DC->isTranslationUnit())
14770     OS << "::";
14771   std::reverse(Namespaces.begin(), Namespaces.end());
14772   for (auto *II : Namespaces)
14773     OS << II->getName() << "::";
14774   return FixItHint::CreateInsertion(NameLoc, Insertion);
14775 }
14776 
14777 /// Determine whether a tag originally declared in context \p OldDC can
14778 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14779 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14780 /// using-declaration).
14781 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14782                                          DeclContext *NewDC) {
14783   OldDC = OldDC->getRedeclContext();
14784   NewDC = NewDC->getRedeclContext();
14785 
14786   if (OldDC->Equals(NewDC))
14787     return true;
14788 
14789   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14790   // encloses the other).
14791   if (S.getLangOpts().MSVCCompat &&
14792       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14793     return true;
14794 
14795   return false;
14796 }
14797 
14798 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14799 /// former case, Name will be non-null.  In the later case, Name will be null.
14800 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14801 /// reference/declaration/definition of a tag.
14802 ///
14803 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14804 /// trailing-type-specifier) other than one in an alias-declaration.
14805 ///
14806 /// \param SkipBody If non-null, will be set to indicate if the caller should
14807 /// skip the definition of this tag and treat it as if it were a declaration.
14808 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14809                      SourceLocation KWLoc, CXXScopeSpec &SS,
14810                      IdentifierInfo *Name, SourceLocation NameLoc,
14811                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14812                      SourceLocation ModulePrivateLoc,
14813                      MultiTemplateParamsArg TemplateParameterLists,
14814                      bool &OwnedDecl, bool &IsDependent,
14815                      SourceLocation ScopedEnumKWLoc,
14816                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14817                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14818                      SkipBodyInfo *SkipBody) {
14819   // If this is not a definition, it must have a name.
14820   IdentifierInfo *OrigName = Name;
14821   assert((Name != nullptr || TUK == TUK_Definition) &&
14822          "Nameless record must be a definition!");
14823   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14824 
14825   OwnedDecl = false;
14826   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14827   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14828 
14829   // FIXME: Check member specializations more carefully.
14830   bool isMemberSpecialization = false;
14831   bool Invalid = false;
14832 
14833   // We only need to do this matching if we have template parameters
14834   // or a scope specifier, which also conveniently avoids this work
14835   // for non-C++ cases.
14836   if (TemplateParameterLists.size() > 0 ||
14837       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14838     if (TemplateParameterList *TemplateParams =
14839             MatchTemplateParametersToScopeSpecifier(
14840                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14841                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14842       if (Kind == TTK_Enum) {
14843         Diag(KWLoc, diag::err_enum_template);
14844         return nullptr;
14845       }
14846 
14847       if (TemplateParams->size() > 0) {
14848         // This is a declaration or definition of a class template (which may
14849         // be a member of another template).
14850 
14851         if (Invalid)
14852           return nullptr;
14853 
14854         OwnedDecl = false;
14855         DeclResult Result = CheckClassTemplate(
14856             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14857             AS, ModulePrivateLoc,
14858             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14859             TemplateParameterLists.data(), SkipBody);
14860         return Result.get();
14861       } else {
14862         // The "template<>" header is extraneous.
14863         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14864           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14865         isMemberSpecialization = true;
14866       }
14867     }
14868   }
14869 
14870   // Figure out the underlying type if this a enum declaration. We need to do
14871   // this early, because it's needed to detect if this is an incompatible
14872   // redeclaration.
14873   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14874   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14875 
14876   if (Kind == TTK_Enum) {
14877     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14878       // No underlying type explicitly specified, or we failed to parse the
14879       // type, default to int.
14880       EnumUnderlying = Context.IntTy.getTypePtr();
14881     } else if (UnderlyingType.get()) {
14882       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14883       // integral type; any cv-qualification is ignored.
14884       TypeSourceInfo *TI = nullptr;
14885       GetTypeFromParser(UnderlyingType.get(), &TI);
14886       EnumUnderlying = TI;
14887 
14888       if (CheckEnumUnderlyingType(TI))
14889         // Recover by falling back to int.
14890         EnumUnderlying = Context.IntTy.getTypePtr();
14891 
14892       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14893                                           UPPC_FixedUnderlyingType))
14894         EnumUnderlying = Context.IntTy.getTypePtr();
14895 
14896     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14897       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14898       // of 'int'. However, if this is an unfixed forward declaration, don't set
14899       // the underlying type unless the user enables -fms-compatibility. This
14900       // makes unfixed forward declared enums incomplete and is more conforming.
14901       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14902         EnumUnderlying = Context.IntTy.getTypePtr();
14903     }
14904   }
14905 
14906   DeclContext *SearchDC = CurContext;
14907   DeclContext *DC = CurContext;
14908   bool isStdBadAlloc = false;
14909   bool isStdAlignValT = false;
14910 
14911   RedeclarationKind Redecl = forRedeclarationInCurContext();
14912   if (TUK == TUK_Friend || TUK == TUK_Reference)
14913     Redecl = NotForRedeclaration;
14914 
14915   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14916   /// implemented asks for structural equivalence checking, the returned decl
14917   /// here is passed back to the parser, allowing the tag body to be parsed.
14918   auto createTagFromNewDecl = [&]() -> TagDecl * {
14919     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14920     // If there is an identifier, use the location of the identifier as the
14921     // location of the decl, otherwise use the location of the struct/union
14922     // keyword.
14923     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14924     TagDecl *New = nullptr;
14925 
14926     if (Kind == TTK_Enum) {
14927       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14928                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14929       // If this is an undefined enum, bail.
14930       if (TUK != TUK_Definition && !Invalid)
14931         return nullptr;
14932       if (EnumUnderlying) {
14933         EnumDecl *ED = cast<EnumDecl>(New);
14934         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14935           ED->setIntegerTypeSourceInfo(TI);
14936         else
14937           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14938         ED->setPromotionType(ED->getIntegerType());
14939       }
14940     } else { // struct/union
14941       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14942                                nullptr);
14943     }
14944 
14945     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14946       // Add alignment attributes if necessary; these attributes are checked
14947       // when the ASTContext lays out the structure.
14948       //
14949       // It is important for implementing the correct semantics that this
14950       // happen here (in ActOnTag). The #pragma pack stack is
14951       // maintained as a result of parser callbacks which can occur at
14952       // many points during the parsing of a struct declaration (because
14953       // the #pragma tokens are effectively skipped over during the
14954       // parsing of the struct).
14955       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14956         AddAlignmentAttributesForRecord(RD);
14957         AddMsStructLayoutForRecord(RD);
14958       }
14959     }
14960     New->setLexicalDeclContext(CurContext);
14961     return New;
14962   };
14963 
14964   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14965   if (Name && SS.isNotEmpty()) {
14966     // We have a nested-name tag ('struct foo::bar').
14967 
14968     // Check for invalid 'foo::'.
14969     if (SS.isInvalid()) {
14970       Name = nullptr;
14971       goto CreateNewDecl;
14972     }
14973 
14974     // If this is a friend or a reference to a class in a dependent
14975     // context, don't try to make a decl for it.
14976     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14977       DC = computeDeclContext(SS, false);
14978       if (!DC) {
14979         IsDependent = true;
14980         return nullptr;
14981       }
14982     } else {
14983       DC = computeDeclContext(SS, true);
14984       if (!DC) {
14985         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14986           << SS.getRange();
14987         return nullptr;
14988       }
14989     }
14990 
14991     if (RequireCompleteDeclContext(SS, DC))
14992       return nullptr;
14993 
14994     SearchDC = DC;
14995     // Look-up name inside 'foo::'.
14996     LookupQualifiedName(Previous, DC);
14997 
14998     if (Previous.isAmbiguous())
14999       return nullptr;
15000 
15001     if (Previous.empty()) {
15002       // Name lookup did not find anything. However, if the
15003       // nested-name-specifier refers to the current instantiation,
15004       // and that current instantiation has any dependent base
15005       // classes, we might find something at instantiation time: treat
15006       // this as a dependent elaborated-type-specifier.
15007       // But this only makes any sense for reference-like lookups.
15008       if (Previous.wasNotFoundInCurrentInstantiation() &&
15009           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15010         IsDependent = true;
15011         return nullptr;
15012       }
15013 
15014       // A tag 'foo::bar' must already exist.
15015       Diag(NameLoc, diag::err_not_tag_in_scope)
15016         << Kind << Name << DC << SS.getRange();
15017       Name = nullptr;
15018       Invalid = true;
15019       goto CreateNewDecl;
15020     }
15021   } else if (Name) {
15022     // C++14 [class.mem]p14:
15023     //   If T is the name of a class, then each of the following shall have a
15024     //   name different from T:
15025     //    -- every member of class T that is itself a type
15026     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15027         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15028       return nullptr;
15029 
15030     // If this is a named struct, check to see if there was a previous forward
15031     // declaration or definition.
15032     // FIXME: We're looking into outer scopes here, even when we
15033     // shouldn't be. Doing so can result in ambiguities that we
15034     // shouldn't be diagnosing.
15035     LookupName(Previous, S);
15036 
15037     // When declaring or defining a tag, ignore ambiguities introduced
15038     // by types using'ed into this scope.
15039     if (Previous.isAmbiguous() &&
15040         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15041       LookupResult::Filter F = Previous.makeFilter();
15042       while (F.hasNext()) {
15043         NamedDecl *ND = F.next();
15044         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15045                 SearchDC->getRedeclContext()))
15046           F.erase();
15047       }
15048       F.done();
15049     }
15050 
15051     // C++11 [namespace.memdef]p3:
15052     //   If the name in a friend declaration is neither qualified nor
15053     //   a template-id and the declaration is a function or an
15054     //   elaborated-type-specifier, the lookup to determine whether
15055     //   the entity has been previously declared shall not consider
15056     //   any scopes outside the innermost enclosing namespace.
15057     //
15058     // MSVC doesn't implement the above rule for types, so a friend tag
15059     // declaration may be a redeclaration of a type declared in an enclosing
15060     // scope.  They do implement this rule for friend functions.
15061     //
15062     // Does it matter that this should be by scope instead of by
15063     // semantic context?
15064     if (!Previous.empty() && TUK == TUK_Friend) {
15065       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15066       LookupResult::Filter F = Previous.makeFilter();
15067       bool FriendSawTagOutsideEnclosingNamespace = false;
15068       while (F.hasNext()) {
15069         NamedDecl *ND = F.next();
15070         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15071         if (DC->isFileContext() &&
15072             !EnclosingNS->Encloses(ND->getDeclContext())) {
15073           if (getLangOpts().MSVCCompat)
15074             FriendSawTagOutsideEnclosingNamespace = true;
15075           else
15076             F.erase();
15077         }
15078       }
15079       F.done();
15080 
15081       // Diagnose this MSVC extension in the easy case where lookup would have
15082       // unambiguously found something outside the enclosing namespace.
15083       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15084         NamedDecl *ND = Previous.getFoundDecl();
15085         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15086             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15087       }
15088     }
15089 
15090     // Note:  there used to be some attempt at recovery here.
15091     if (Previous.isAmbiguous())
15092       return nullptr;
15093 
15094     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15095       // FIXME: This makes sure that we ignore the contexts associated
15096       // with C structs, unions, and enums when looking for a matching
15097       // tag declaration or definition. See the similar lookup tweak
15098       // in Sema::LookupName; is there a better way to deal with this?
15099       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15100         SearchDC = SearchDC->getParent();
15101     }
15102   }
15103 
15104   if (Previous.isSingleResult() &&
15105       Previous.getFoundDecl()->isTemplateParameter()) {
15106     // Maybe we will complain about the shadowed template parameter.
15107     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15108     // Just pretend that we didn't see the previous declaration.
15109     Previous.clear();
15110   }
15111 
15112   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15113       DC->Equals(getStdNamespace())) {
15114     if (Name->isStr("bad_alloc")) {
15115       // This is a declaration of or a reference to "std::bad_alloc".
15116       isStdBadAlloc = true;
15117 
15118       // If std::bad_alloc has been implicitly declared (but made invisible to
15119       // name lookup), fill in this implicit declaration as the previous
15120       // declaration, so that the declarations get chained appropriately.
15121       if (Previous.empty() && StdBadAlloc)
15122         Previous.addDecl(getStdBadAlloc());
15123     } else if (Name->isStr("align_val_t")) {
15124       isStdAlignValT = true;
15125       if (Previous.empty() && StdAlignValT)
15126         Previous.addDecl(getStdAlignValT());
15127     }
15128   }
15129 
15130   // If we didn't find a previous declaration, and this is a reference
15131   // (or friend reference), move to the correct scope.  In C++, we
15132   // also need to do a redeclaration lookup there, just in case
15133   // there's a shadow friend decl.
15134   if (Name && Previous.empty() &&
15135       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15136     if (Invalid) goto CreateNewDecl;
15137     assert(SS.isEmpty());
15138 
15139     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15140       // C++ [basic.scope.pdecl]p5:
15141       //   -- for an elaborated-type-specifier of the form
15142       //
15143       //          class-key identifier
15144       //
15145       //      if the elaborated-type-specifier is used in the
15146       //      decl-specifier-seq or parameter-declaration-clause of a
15147       //      function defined in namespace scope, the identifier is
15148       //      declared as a class-name in the namespace that contains
15149       //      the declaration; otherwise, except as a friend
15150       //      declaration, the identifier is declared in the smallest
15151       //      non-class, non-function-prototype scope that contains the
15152       //      declaration.
15153       //
15154       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15155       // C structs and unions.
15156       //
15157       // It is an error in C++ to declare (rather than define) an enum
15158       // type, including via an elaborated type specifier.  We'll
15159       // diagnose that later; for now, declare the enum in the same
15160       // scope as we would have picked for any other tag type.
15161       //
15162       // GNU C also supports this behavior as part of its incomplete
15163       // enum types extension, while GNU C++ does not.
15164       //
15165       // Find the context where we'll be declaring the tag.
15166       // FIXME: We would like to maintain the current DeclContext as the
15167       // lexical context,
15168       SearchDC = getTagInjectionContext(SearchDC);
15169 
15170       // Find the scope where we'll be declaring the tag.
15171       S = getTagInjectionScope(S, getLangOpts());
15172     } else {
15173       assert(TUK == TUK_Friend);
15174       // C++ [namespace.memdef]p3:
15175       //   If a friend declaration in a non-local class first declares a
15176       //   class or function, the friend class or function is a member of
15177       //   the innermost enclosing namespace.
15178       SearchDC = SearchDC->getEnclosingNamespaceContext();
15179     }
15180 
15181     // In C++, we need to do a redeclaration lookup to properly
15182     // diagnose some problems.
15183     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15184     // hidden declaration so that we don't get ambiguity errors when using a
15185     // type declared by an elaborated-type-specifier.  In C that is not correct
15186     // and we should instead merge compatible types found by lookup.
15187     if (getLangOpts().CPlusPlus) {
15188       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15189       LookupQualifiedName(Previous, SearchDC);
15190     } else {
15191       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15192       LookupName(Previous, S);
15193     }
15194   }
15195 
15196   // If we have a known previous declaration to use, then use it.
15197   if (Previous.empty() && SkipBody && SkipBody->Previous)
15198     Previous.addDecl(SkipBody->Previous);
15199 
15200   if (!Previous.empty()) {
15201     NamedDecl *PrevDecl = Previous.getFoundDecl();
15202     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15203 
15204     // It's okay to have a tag decl in the same scope as a typedef
15205     // which hides a tag decl in the same scope.  Finding this
15206     // insanity with a redeclaration lookup can only actually happen
15207     // in C++.
15208     //
15209     // This is also okay for elaborated-type-specifiers, which is
15210     // technically forbidden by the current standard but which is
15211     // okay according to the likely resolution of an open issue;
15212     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15213     if (getLangOpts().CPlusPlus) {
15214       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15215         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15216           TagDecl *Tag = TT->getDecl();
15217           if (Tag->getDeclName() == Name &&
15218               Tag->getDeclContext()->getRedeclContext()
15219                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15220             PrevDecl = Tag;
15221             Previous.clear();
15222             Previous.addDecl(Tag);
15223             Previous.resolveKind();
15224           }
15225         }
15226       }
15227     }
15228 
15229     // If this is a redeclaration of a using shadow declaration, it must
15230     // declare a tag in the same context. In MSVC mode, we allow a
15231     // redefinition if either context is within the other.
15232     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15233       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15234       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15235           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15236           !(OldTag && isAcceptableTagRedeclContext(
15237                           *this, OldTag->getDeclContext(), SearchDC))) {
15238         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15239         Diag(Shadow->getTargetDecl()->getLocation(),
15240              diag::note_using_decl_target);
15241         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15242             << 0;
15243         // Recover by ignoring the old declaration.
15244         Previous.clear();
15245         goto CreateNewDecl;
15246       }
15247     }
15248 
15249     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15250       // If this is a use of a previous tag, or if the tag is already declared
15251       // in the same scope (so that the definition/declaration completes or
15252       // rementions the tag), reuse the decl.
15253       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15254           isDeclInScope(DirectPrevDecl, SearchDC, S,
15255                         SS.isNotEmpty() || isMemberSpecialization)) {
15256         // Make sure that this wasn't declared as an enum and now used as a
15257         // struct or something similar.
15258         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15259                                           TUK == TUK_Definition, KWLoc,
15260                                           Name)) {
15261           bool SafeToContinue
15262             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15263                Kind != TTK_Enum);
15264           if (SafeToContinue)
15265             Diag(KWLoc, diag::err_use_with_wrong_tag)
15266               << Name
15267               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15268                                               PrevTagDecl->getKindName());
15269           else
15270             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15271           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15272 
15273           if (SafeToContinue)
15274             Kind = PrevTagDecl->getTagKind();
15275           else {
15276             // Recover by making this an anonymous redefinition.
15277             Name = nullptr;
15278             Previous.clear();
15279             Invalid = true;
15280           }
15281         }
15282 
15283         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15284           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15285 
15286           // If this is an elaborated-type-specifier for a scoped enumeration,
15287           // the 'class' keyword is not necessary and not permitted.
15288           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15289             if (ScopedEnum)
15290               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15291                 << PrevEnum->isScoped()
15292                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15293             return PrevTagDecl;
15294           }
15295 
15296           QualType EnumUnderlyingTy;
15297           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15298             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15299           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15300             EnumUnderlyingTy = QualType(T, 0);
15301 
15302           // All conflicts with previous declarations are recovered by
15303           // returning the previous declaration, unless this is a definition,
15304           // in which case we want the caller to bail out.
15305           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15306                                      ScopedEnum, EnumUnderlyingTy,
15307                                      IsFixed, PrevEnum))
15308             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15309         }
15310 
15311         // C++11 [class.mem]p1:
15312         //   A member shall not be declared twice in the member-specification,
15313         //   except that a nested class or member class template can be declared
15314         //   and then later defined.
15315         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15316             S->isDeclScope(PrevDecl)) {
15317           Diag(NameLoc, diag::ext_member_redeclared);
15318           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15319         }
15320 
15321         if (!Invalid) {
15322           // If this is a use, just return the declaration we found, unless
15323           // we have attributes.
15324           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15325             if (!Attrs.empty()) {
15326               // FIXME: Diagnose these attributes. For now, we create a new
15327               // declaration to hold them.
15328             } else if (TUK == TUK_Reference &&
15329                        (PrevTagDecl->getFriendObjectKind() ==
15330                             Decl::FOK_Undeclared ||
15331                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15332                        SS.isEmpty()) {
15333               // This declaration is a reference to an existing entity, but
15334               // has different visibility from that entity: it either makes
15335               // a friend visible or it makes a type visible in a new module.
15336               // In either case, create a new declaration. We only do this if
15337               // the declaration would have meant the same thing if no prior
15338               // declaration were found, that is, if it was found in the same
15339               // scope where we would have injected a declaration.
15340               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15341                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15342                 return PrevTagDecl;
15343               // This is in the injected scope, create a new declaration in
15344               // that scope.
15345               S = getTagInjectionScope(S, getLangOpts());
15346             } else {
15347               return PrevTagDecl;
15348             }
15349           }
15350 
15351           // Diagnose attempts to redefine a tag.
15352           if (TUK == TUK_Definition) {
15353             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15354               // If we're defining a specialization and the previous definition
15355               // is from an implicit instantiation, don't emit an error
15356               // here; we'll catch this in the general case below.
15357               bool IsExplicitSpecializationAfterInstantiation = false;
15358               if (isMemberSpecialization) {
15359                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15360                   IsExplicitSpecializationAfterInstantiation =
15361                     RD->getTemplateSpecializationKind() !=
15362                     TSK_ExplicitSpecialization;
15363                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15364                   IsExplicitSpecializationAfterInstantiation =
15365                     ED->getTemplateSpecializationKind() !=
15366                     TSK_ExplicitSpecialization;
15367               }
15368 
15369               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15370               // not keep more that one definition around (merge them). However,
15371               // ensure the decl passes the structural compatibility check in
15372               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15373               NamedDecl *Hidden = nullptr;
15374               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15375                 // There is a definition of this tag, but it is not visible. We
15376                 // explicitly make use of C++'s one definition rule here, and
15377                 // assume that this definition is identical to the hidden one
15378                 // we already have. Make the existing definition visible and
15379                 // use it in place of this one.
15380                 if (!getLangOpts().CPlusPlus) {
15381                   // Postpone making the old definition visible until after we
15382                   // complete parsing the new one and do the structural
15383                   // comparison.
15384                   SkipBody->CheckSameAsPrevious = true;
15385                   SkipBody->New = createTagFromNewDecl();
15386                   SkipBody->Previous = Def;
15387                   return Def;
15388                 } else {
15389                   SkipBody->ShouldSkip = true;
15390                   SkipBody->Previous = Def;
15391                   makeMergedDefinitionVisible(Hidden);
15392                   // Carry on and handle it like a normal definition. We'll
15393                   // skip starting the definitiion later.
15394                 }
15395               } else if (!IsExplicitSpecializationAfterInstantiation) {
15396                 // A redeclaration in function prototype scope in C isn't
15397                 // visible elsewhere, so merely issue a warning.
15398                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15399                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15400                 else
15401                   Diag(NameLoc, diag::err_redefinition) << Name;
15402                 notePreviousDefinition(Def,
15403                                        NameLoc.isValid() ? NameLoc : KWLoc);
15404                 // If this is a redefinition, recover by making this
15405                 // struct be anonymous, which will make any later
15406                 // references get the previous definition.
15407                 Name = nullptr;
15408                 Previous.clear();
15409                 Invalid = true;
15410               }
15411             } else {
15412               // If the type is currently being defined, complain
15413               // about a nested redefinition.
15414               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15415               if (TD->isBeingDefined()) {
15416                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15417                 Diag(PrevTagDecl->getLocation(),
15418                      diag::note_previous_definition);
15419                 Name = nullptr;
15420                 Previous.clear();
15421                 Invalid = true;
15422               }
15423             }
15424 
15425             // Okay, this is definition of a previously declared or referenced
15426             // tag. We're going to create a new Decl for it.
15427           }
15428 
15429           // Okay, we're going to make a redeclaration.  If this is some kind
15430           // of reference, make sure we build the redeclaration in the same DC
15431           // as the original, and ignore the current access specifier.
15432           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15433             SearchDC = PrevTagDecl->getDeclContext();
15434             AS = AS_none;
15435           }
15436         }
15437         // If we get here we have (another) forward declaration or we
15438         // have a definition.  Just create a new decl.
15439 
15440       } else {
15441         // If we get here, this is a definition of a new tag type in a nested
15442         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15443         // new decl/type.  We set PrevDecl to NULL so that the entities
15444         // have distinct types.
15445         Previous.clear();
15446       }
15447       // If we get here, we're going to create a new Decl. If PrevDecl
15448       // is non-NULL, it's a definition of the tag declared by
15449       // PrevDecl. If it's NULL, we have a new definition.
15450 
15451     // Otherwise, PrevDecl is not a tag, but was found with tag
15452     // lookup.  This is only actually possible in C++, where a few
15453     // things like templates still live in the tag namespace.
15454     } else {
15455       // Use a better diagnostic if an elaborated-type-specifier
15456       // found the wrong kind of type on the first
15457       // (non-redeclaration) lookup.
15458       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15459           !Previous.isForRedeclaration()) {
15460         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15461         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15462                                                        << Kind;
15463         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15464         Invalid = true;
15465 
15466       // Otherwise, only diagnose if the declaration is in scope.
15467       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15468                                 SS.isNotEmpty() || isMemberSpecialization)) {
15469         // do nothing
15470 
15471       // Diagnose implicit declarations introduced by elaborated types.
15472       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15473         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15474         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15475         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15476         Invalid = true;
15477 
15478       // Otherwise it's a declaration.  Call out a particularly common
15479       // case here.
15480       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15481         unsigned Kind = 0;
15482         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15483         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15484           << Name << Kind << TND->getUnderlyingType();
15485         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15486         Invalid = true;
15487 
15488       // Otherwise, diagnose.
15489       } else {
15490         // The tag name clashes with something else in the target scope,
15491         // issue an error and recover by making this tag be anonymous.
15492         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15493         notePreviousDefinition(PrevDecl, NameLoc);
15494         Name = nullptr;
15495         Invalid = true;
15496       }
15497 
15498       // The existing declaration isn't relevant to us; we're in a
15499       // new scope, so clear out the previous declaration.
15500       Previous.clear();
15501     }
15502   }
15503 
15504 CreateNewDecl:
15505 
15506   TagDecl *PrevDecl = nullptr;
15507   if (Previous.isSingleResult())
15508     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15509 
15510   // If there is an identifier, use the location of the identifier as the
15511   // location of the decl, otherwise use the location of the struct/union
15512   // keyword.
15513   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15514 
15515   // Otherwise, create a new declaration. If there is a previous
15516   // declaration of the same entity, the two will be linked via
15517   // PrevDecl.
15518   TagDecl *New;
15519 
15520   if (Kind == TTK_Enum) {
15521     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15522     // enum X { A, B, C } D;    D should chain to X.
15523     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15524                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15525                            ScopedEnumUsesClassTag, IsFixed);
15526 
15527     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15528       StdAlignValT = cast<EnumDecl>(New);
15529 
15530     // If this is an undefined enum, warn.
15531     if (TUK != TUK_Definition && !Invalid) {
15532       TagDecl *Def;
15533       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15534         // C++0x: 7.2p2: opaque-enum-declaration.
15535         // Conflicts are diagnosed above. Do nothing.
15536       }
15537       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15538         Diag(Loc, diag::ext_forward_ref_enum_def)
15539           << New;
15540         Diag(Def->getLocation(), diag::note_previous_definition);
15541       } else {
15542         unsigned DiagID = diag::ext_forward_ref_enum;
15543         if (getLangOpts().MSVCCompat)
15544           DiagID = diag::ext_ms_forward_ref_enum;
15545         else if (getLangOpts().CPlusPlus)
15546           DiagID = diag::err_forward_ref_enum;
15547         Diag(Loc, DiagID);
15548       }
15549     }
15550 
15551     if (EnumUnderlying) {
15552       EnumDecl *ED = cast<EnumDecl>(New);
15553       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15554         ED->setIntegerTypeSourceInfo(TI);
15555       else
15556         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15557       ED->setPromotionType(ED->getIntegerType());
15558       assert(ED->isComplete() && "enum with type should be complete");
15559     }
15560   } else {
15561     // struct/union/class
15562 
15563     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15564     // struct X { int A; } D;    D should chain to X.
15565     if (getLangOpts().CPlusPlus) {
15566       // FIXME: Look for a way to use RecordDecl for simple structs.
15567       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15568                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15569 
15570       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15571         StdBadAlloc = cast<CXXRecordDecl>(New);
15572     } else
15573       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15574                                cast_or_null<RecordDecl>(PrevDecl));
15575   }
15576 
15577   // C++11 [dcl.type]p3:
15578   //   A type-specifier-seq shall not define a class or enumeration [...].
15579   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15580       TUK == TUK_Definition) {
15581     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15582       << Context.getTagDeclType(New);
15583     Invalid = true;
15584   }
15585 
15586   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15587       DC->getDeclKind() == Decl::Enum) {
15588     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15589       << Context.getTagDeclType(New);
15590     Invalid = true;
15591   }
15592 
15593   // Maybe add qualifier info.
15594   if (SS.isNotEmpty()) {
15595     if (SS.isSet()) {
15596       // If this is either a declaration or a definition, check the
15597       // nested-name-specifier against the current context.
15598       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15599           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15600                                        isMemberSpecialization))
15601         Invalid = true;
15602 
15603       New->setQualifierInfo(SS.getWithLocInContext(Context));
15604       if (TemplateParameterLists.size() > 0) {
15605         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15606       }
15607     }
15608     else
15609       Invalid = true;
15610   }
15611 
15612   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15613     // Add alignment attributes if necessary; these attributes are checked when
15614     // the ASTContext lays out the structure.
15615     //
15616     // It is important for implementing the correct semantics that this
15617     // happen here (in ActOnTag). The #pragma pack stack is
15618     // maintained as a result of parser callbacks which can occur at
15619     // many points during the parsing of a struct declaration (because
15620     // the #pragma tokens are effectively skipped over during the
15621     // parsing of the struct).
15622     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15623       AddAlignmentAttributesForRecord(RD);
15624       AddMsStructLayoutForRecord(RD);
15625     }
15626   }
15627 
15628   if (ModulePrivateLoc.isValid()) {
15629     if (isMemberSpecialization)
15630       Diag(New->getLocation(), diag::err_module_private_specialization)
15631         << 2
15632         << FixItHint::CreateRemoval(ModulePrivateLoc);
15633     // __module_private__ does not apply to local classes. However, we only
15634     // diagnose this as an error when the declaration specifiers are
15635     // freestanding. Here, we just ignore the __module_private__.
15636     else if (!SearchDC->isFunctionOrMethod())
15637       New->setModulePrivate();
15638   }
15639 
15640   // If this is a specialization of a member class (of a class template),
15641   // check the specialization.
15642   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15643     Invalid = true;
15644 
15645   // If we're declaring or defining a tag in function prototype scope in C,
15646   // note that this type can only be used within the function and add it to
15647   // the list of decls to inject into the function definition scope.
15648   if ((Name || Kind == TTK_Enum) &&
15649       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15650     if (getLangOpts().CPlusPlus) {
15651       // C++ [dcl.fct]p6:
15652       //   Types shall not be defined in return or parameter types.
15653       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15654         Diag(Loc, diag::err_type_defined_in_param_type)
15655             << Name;
15656         Invalid = true;
15657       }
15658     } else if (!PrevDecl) {
15659       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15660     }
15661   }
15662 
15663   if (Invalid)
15664     New->setInvalidDecl();
15665 
15666   // Set the lexical context. If the tag has a C++ scope specifier, the
15667   // lexical context will be different from the semantic context.
15668   New->setLexicalDeclContext(CurContext);
15669 
15670   // Mark this as a friend decl if applicable.
15671   // In Microsoft mode, a friend declaration also acts as a forward
15672   // declaration so we always pass true to setObjectOfFriendDecl to make
15673   // the tag name visible.
15674   if (TUK == TUK_Friend)
15675     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15676 
15677   // Set the access specifier.
15678   if (!Invalid && SearchDC->isRecord())
15679     SetMemberAccessSpecifier(New, PrevDecl, AS);
15680 
15681   if (PrevDecl)
15682     CheckRedeclarationModuleOwnership(New, PrevDecl);
15683 
15684   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15685     New->startDefinition();
15686 
15687   ProcessDeclAttributeList(S, New, Attrs);
15688   AddPragmaAttributes(S, New);
15689 
15690   // If this has an identifier, add it to the scope stack.
15691   if (TUK == TUK_Friend) {
15692     // We might be replacing an existing declaration in the lookup tables;
15693     // if so, borrow its access specifier.
15694     if (PrevDecl)
15695       New->setAccess(PrevDecl->getAccess());
15696 
15697     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15698     DC->makeDeclVisibleInContext(New);
15699     if (Name) // can be null along some error paths
15700       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15701         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15702   } else if (Name) {
15703     S = getNonFieldDeclScope(S);
15704     PushOnScopeChains(New, S, true);
15705   } else {
15706     CurContext->addDecl(New);
15707   }
15708 
15709   // If this is the C FILE type, notify the AST context.
15710   if (IdentifierInfo *II = New->getIdentifier())
15711     if (!New->isInvalidDecl() &&
15712         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15713         II->isStr("FILE"))
15714       Context.setFILEDecl(New);
15715 
15716   if (PrevDecl)
15717     mergeDeclAttributes(New, PrevDecl);
15718 
15719   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15720     inferGslOwnerPointerAttribute(CXXRD);
15721 
15722   // If there's a #pragma GCC visibility in scope, set the visibility of this
15723   // record.
15724   AddPushedVisibilityAttribute(New);
15725 
15726   if (isMemberSpecialization && !New->isInvalidDecl())
15727     CompleteMemberSpecialization(New, Previous);
15728 
15729   OwnedDecl = true;
15730   // In C++, don't return an invalid declaration. We can't recover well from
15731   // the cases where we make the type anonymous.
15732   if (Invalid && getLangOpts().CPlusPlus) {
15733     if (New->isBeingDefined())
15734       if (auto RD = dyn_cast<RecordDecl>(New))
15735         RD->completeDefinition();
15736     return nullptr;
15737   } else if (SkipBody && SkipBody->ShouldSkip) {
15738     return SkipBody->Previous;
15739   } else {
15740     return New;
15741   }
15742 }
15743 
15744 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15745   AdjustDeclIfTemplate(TagD);
15746   TagDecl *Tag = cast<TagDecl>(TagD);
15747 
15748   // Enter the tag context.
15749   PushDeclContext(S, Tag);
15750 
15751   ActOnDocumentableDecl(TagD);
15752 
15753   // If there's a #pragma GCC visibility in scope, set the visibility of this
15754   // record.
15755   AddPushedVisibilityAttribute(Tag);
15756 }
15757 
15758 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15759                                     SkipBodyInfo &SkipBody) {
15760   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15761     return false;
15762 
15763   // Make the previous decl visible.
15764   makeMergedDefinitionVisible(SkipBody.Previous);
15765   return true;
15766 }
15767 
15768 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15769   assert(isa<ObjCContainerDecl>(IDecl) &&
15770          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15771   DeclContext *OCD = cast<DeclContext>(IDecl);
15772   assert(getContainingDC(OCD) == CurContext &&
15773       "The next DeclContext should be lexically contained in the current one.");
15774   CurContext = OCD;
15775   return IDecl;
15776 }
15777 
15778 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15779                                            SourceLocation FinalLoc,
15780                                            bool IsFinalSpelledSealed,
15781                                            SourceLocation LBraceLoc) {
15782   AdjustDeclIfTemplate(TagD);
15783   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15784 
15785   FieldCollector->StartClass();
15786 
15787   if (!Record->getIdentifier())
15788     return;
15789 
15790   if (FinalLoc.isValid())
15791     Record->addAttr(FinalAttr::Create(
15792         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15793         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15794 
15795   // C++ [class]p2:
15796   //   [...] The class-name is also inserted into the scope of the
15797   //   class itself; this is known as the injected-class-name. For
15798   //   purposes of access checking, the injected-class-name is treated
15799   //   as if it were a public member name.
15800   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15801       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15802       Record->getLocation(), Record->getIdentifier(),
15803       /*PrevDecl=*/nullptr,
15804       /*DelayTypeCreation=*/true);
15805   Context.getTypeDeclType(InjectedClassName, Record);
15806   InjectedClassName->setImplicit();
15807   InjectedClassName->setAccess(AS_public);
15808   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15809       InjectedClassName->setDescribedClassTemplate(Template);
15810   PushOnScopeChains(InjectedClassName, S);
15811   assert(InjectedClassName->isInjectedClassName() &&
15812          "Broken injected-class-name");
15813 }
15814 
15815 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15816                                     SourceRange BraceRange) {
15817   AdjustDeclIfTemplate(TagD);
15818   TagDecl *Tag = cast<TagDecl>(TagD);
15819   Tag->setBraceRange(BraceRange);
15820 
15821   // Make sure we "complete" the definition even it is invalid.
15822   if (Tag->isBeingDefined()) {
15823     assert(Tag->isInvalidDecl() && "We should already have completed it");
15824     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15825       RD->completeDefinition();
15826   }
15827 
15828   if (isa<CXXRecordDecl>(Tag)) {
15829     FieldCollector->FinishClass();
15830   }
15831 
15832   // Exit this scope of this tag's definition.
15833   PopDeclContext();
15834 
15835   if (getCurLexicalContext()->isObjCContainer() &&
15836       Tag->getDeclContext()->isFileContext())
15837     Tag->setTopLevelDeclInObjCContainer();
15838 
15839   // Notify the consumer that we've defined a tag.
15840   if (!Tag->isInvalidDecl())
15841     Consumer.HandleTagDeclDefinition(Tag);
15842 }
15843 
15844 void Sema::ActOnObjCContainerFinishDefinition() {
15845   // Exit this scope of this interface definition.
15846   PopDeclContext();
15847 }
15848 
15849 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15850   assert(DC == CurContext && "Mismatch of container contexts");
15851   OriginalLexicalContext = DC;
15852   ActOnObjCContainerFinishDefinition();
15853 }
15854 
15855 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15856   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15857   OriginalLexicalContext = nullptr;
15858 }
15859 
15860 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15861   AdjustDeclIfTemplate(TagD);
15862   TagDecl *Tag = cast<TagDecl>(TagD);
15863   Tag->setInvalidDecl();
15864 
15865   // Make sure we "complete" the definition even it is invalid.
15866   if (Tag->isBeingDefined()) {
15867     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15868       RD->completeDefinition();
15869   }
15870 
15871   // We're undoing ActOnTagStartDefinition here, not
15872   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15873   // the FieldCollector.
15874 
15875   PopDeclContext();
15876 }
15877 
15878 // Note that FieldName may be null for anonymous bitfields.
15879 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15880                                 IdentifierInfo *FieldName,
15881                                 QualType FieldTy, bool IsMsStruct,
15882                                 Expr *BitWidth, bool *ZeroWidth) {
15883   // Default to true; that shouldn't confuse checks for emptiness
15884   if (ZeroWidth)
15885     *ZeroWidth = true;
15886 
15887   // C99 6.7.2.1p4 - verify the field type.
15888   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15889   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15890     // Handle incomplete types with specific error.
15891     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15892       return ExprError();
15893     if (FieldName)
15894       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15895         << FieldName << FieldTy << BitWidth->getSourceRange();
15896     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15897       << FieldTy << BitWidth->getSourceRange();
15898   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15899                                              UPPC_BitFieldWidth))
15900     return ExprError();
15901 
15902   // If the bit-width is type- or value-dependent, don't try to check
15903   // it now.
15904   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15905     return BitWidth;
15906 
15907   llvm::APSInt Value;
15908   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15909   if (ICE.isInvalid())
15910     return ICE;
15911   BitWidth = ICE.get();
15912 
15913   if (Value != 0 && ZeroWidth)
15914     *ZeroWidth = false;
15915 
15916   // Zero-width bitfield is ok for anonymous field.
15917   if (Value == 0 && FieldName)
15918     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15919 
15920   if (Value.isSigned() && Value.isNegative()) {
15921     if (FieldName)
15922       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15923                << FieldName << Value.toString(10);
15924     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15925       << Value.toString(10);
15926   }
15927 
15928   if (!FieldTy->isDependentType()) {
15929     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15930     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15931     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15932 
15933     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15934     // ABI.
15935     bool CStdConstraintViolation =
15936         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15937     bool MSBitfieldViolation =
15938         Value.ugt(TypeStorageSize) &&
15939         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15940     if (CStdConstraintViolation || MSBitfieldViolation) {
15941       unsigned DiagWidth =
15942           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15943       if (FieldName)
15944         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15945                << FieldName << (unsigned)Value.getZExtValue()
15946                << !CStdConstraintViolation << DiagWidth;
15947 
15948       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15949              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15950              << DiagWidth;
15951     }
15952 
15953     // Warn on types where the user might conceivably expect to get all
15954     // specified bits as value bits: that's all integral types other than
15955     // 'bool'.
15956     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15957       if (FieldName)
15958         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15959             << FieldName << (unsigned)Value.getZExtValue()
15960             << (unsigned)TypeWidth;
15961       else
15962         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15963             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15964     }
15965   }
15966 
15967   return BitWidth;
15968 }
15969 
15970 /// ActOnField - Each field of a C struct/union is passed into this in order
15971 /// to create a FieldDecl object for it.
15972 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15973                        Declarator &D, Expr *BitfieldWidth) {
15974   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15975                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15976                                /*InitStyle=*/ICIS_NoInit, AS_public);
15977   return Res;
15978 }
15979 
15980 /// HandleField - Analyze a field of a C struct or a C++ data member.
15981 ///
15982 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15983                              SourceLocation DeclStart,
15984                              Declarator &D, Expr *BitWidth,
15985                              InClassInitStyle InitStyle,
15986                              AccessSpecifier AS) {
15987   if (D.isDecompositionDeclarator()) {
15988     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15989     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15990       << Decomp.getSourceRange();
15991     return nullptr;
15992   }
15993 
15994   IdentifierInfo *II = D.getIdentifier();
15995   SourceLocation Loc = DeclStart;
15996   if (II) Loc = D.getIdentifierLoc();
15997 
15998   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15999   QualType T = TInfo->getType();
16000   if (getLangOpts().CPlusPlus) {
16001     CheckExtraCXXDefaultArguments(D);
16002 
16003     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16004                                         UPPC_DataMemberType)) {
16005       D.setInvalidType();
16006       T = Context.IntTy;
16007       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16008     }
16009   }
16010 
16011   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16012 
16013   if (D.getDeclSpec().isInlineSpecified())
16014     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16015         << getLangOpts().CPlusPlus17;
16016   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16017     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16018          diag::err_invalid_thread)
16019       << DeclSpec::getSpecifierName(TSCS);
16020 
16021   // Check to see if this name was declared as a member previously
16022   NamedDecl *PrevDecl = nullptr;
16023   LookupResult Previous(*this, II, Loc, LookupMemberName,
16024                         ForVisibleRedeclaration);
16025   LookupName(Previous, S);
16026   switch (Previous.getResultKind()) {
16027     case LookupResult::Found:
16028     case LookupResult::FoundUnresolvedValue:
16029       PrevDecl = Previous.getAsSingle<NamedDecl>();
16030       break;
16031 
16032     case LookupResult::FoundOverloaded:
16033       PrevDecl = Previous.getRepresentativeDecl();
16034       break;
16035 
16036     case LookupResult::NotFound:
16037     case LookupResult::NotFoundInCurrentInstantiation:
16038     case LookupResult::Ambiguous:
16039       break;
16040   }
16041   Previous.suppressDiagnostics();
16042 
16043   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16044     // Maybe we will complain about the shadowed template parameter.
16045     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16046     // Just pretend that we didn't see the previous declaration.
16047     PrevDecl = nullptr;
16048   }
16049 
16050   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16051     PrevDecl = nullptr;
16052 
16053   bool Mutable
16054     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16055   SourceLocation TSSL = D.getBeginLoc();
16056   FieldDecl *NewFD
16057     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16058                      TSSL, AS, PrevDecl, &D);
16059 
16060   if (NewFD->isInvalidDecl())
16061     Record->setInvalidDecl();
16062 
16063   if (D.getDeclSpec().isModulePrivateSpecified())
16064     NewFD->setModulePrivate();
16065 
16066   if (NewFD->isInvalidDecl() && PrevDecl) {
16067     // Don't introduce NewFD into scope; there's already something
16068     // with the same name in the same scope.
16069   } else if (II) {
16070     PushOnScopeChains(NewFD, S);
16071   } else
16072     Record->addDecl(NewFD);
16073 
16074   return NewFD;
16075 }
16076 
16077 /// Build a new FieldDecl and check its well-formedness.
16078 ///
16079 /// This routine builds a new FieldDecl given the fields name, type,
16080 /// record, etc. \p PrevDecl should refer to any previous declaration
16081 /// with the same name and in the same scope as the field to be
16082 /// created.
16083 ///
16084 /// \returns a new FieldDecl.
16085 ///
16086 /// \todo The Declarator argument is a hack. It will be removed once
16087 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16088                                 TypeSourceInfo *TInfo,
16089                                 RecordDecl *Record, SourceLocation Loc,
16090                                 bool Mutable, Expr *BitWidth,
16091                                 InClassInitStyle InitStyle,
16092                                 SourceLocation TSSL,
16093                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16094                                 Declarator *D) {
16095   IdentifierInfo *II = Name.getAsIdentifierInfo();
16096   bool InvalidDecl = false;
16097   if (D) InvalidDecl = D->isInvalidType();
16098 
16099   // If we receive a broken type, recover by assuming 'int' and
16100   // marking this declaration as invalid.
16101   if (T.isNull()) {
16102     InvalidDecl = true;
16103     T = Context.IntTy;
16104   }
16105 
16106   QualType EltTy = Context.getBaseElementType(T);
16107   if (!EltTy->isDependentType()) {
16108     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16109       // Fields of incomplete type force their record to be invalid.
16110       Record->setInvalidDecl();
16111       InvalidDecl = true;
16112     } else {
16113       NamedDecl *Def;
16114       EltTy->isIncompleteType(&Def);
16115       if (Def && Def->isInvalidDecl()) {
16116         Record->setInvalidDecl();
16117         InvalidDecl = true;
16118       }
16119     }
16120   }
16121 
16122   // TR 18037 does not allow fields to be declared with address space
16123   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16124       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16125     Diag(Loc, diag::err_field_with_address_space);
16126     Record->setInvalidDecl();
16127     InvalidDecl = true;
16128   }
16129 
16130   if (LangOpts.OpenCL) {
16131     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16132     // used as structure or union field: image, sampler, event or block types.
16133     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16134         T->isBlockPointerType()) {
16135       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16136       Record->setInvalidDecl();
16137       InvalidDecl = true;
16138     }
16139     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16140     if (BitWidth) {
16141       Diag(Loc, diag::err_opencl_bitfields);
16142       InvalidDecl = true;
16143     }
16144   }
16145 
16146   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16147   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16148       T.hasQualifiers()) {
16149     InvalidDecl = true;
16150     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16151   }
16152 
16153   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16154   // than a variably modified type.
16155   if (!InvalidDecl && T->isVariablyModifiedType()) {
16156     bool SizeIsNegative;
16157     llvm::APSInt Oversized;
16158 
16159     TypeSourceInfo *FixedTInfo =
16160       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16161                                                     SizeIsNegative,
16162                                                     Oversized);
16163     if (FixedTInfo) {
16164       Diag(Loc, diag::warn_illegal_constant_array_size);
16165       TInfo = FixedTInfo;
16166       T = FixedTInfo->getType();
16167     } else {
16168       if (SizeIsNegative)
16169         Diag(Loc, diag::err_typecheck_negative_array_size);
16170       else if (Oversized.getBoolValue())
16171         Diag(Loc, diag::err_array_too_large)
16172           << Oversized.toString(10);
16173       else
16174         Diag(Loc, diag::err_typecheck_field_variable_size);
16175       InvalidDecl = true;
16176     }
16177   }
16178 
16179   // Fields can not have abstract class types
16180   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16181                                              diag::err_abstract_type_in_decl,
16182                                              AbstractFieldType))
16183     InvalidDecl = true;
16184 
16185   bool ZeroWidth = false;
16186   if (InvalidDecl)
16187     BitWidth = nullptr;
16188   // If this is declared as a bit-field, check the bit-field.
16189   if (BitWidth) {
16190     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16191                               &ZeroWidth).get();
16192     if (!BitWidth) {
16193       InvalidDecl = true;
16194       BitWidth = nullptr;
16195       ZeroWidth = false;
16196     }
16197   }
16198 
16199   // Check that 'mutable' is consistent with the type of the declaration.
16200   if (!InvalidDecl && Mutable) {
16201     unsigned DiagID = 0;
16202     if (T->isReferenceType())
16203       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16204                                         : diag::err_mutable_reference;
16205     else if (T.isConstQualified())
16206       DiagID = diag::err_mutable_const;
16207 
16208     if (DiagID) {
16209       SourceLocation ErrLoc = Loc;
16210       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16211         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16212       Diag(ErrLoc, DiagID);
16213       if (DiagID != diag::ext_mutable_reference) {
16214         Mutable = false;
16215         InvalidDecl = true;
16216       }
16217     }
16218   }
16219 
16220   // C++11 [class.union]p8 (DR1460):
16221   //   At most one variant member of a union may have a
16222   //   brace-or-equal-initializer.
16223   if (InitStyle != ICIS_NoInit)
16224     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16225 
16226   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16227                                        BitWidth, Mutable, InitStyle);
16228   if (InvalidDecl)
16229     NewFD->setInvalidDecl();
16230 
16231   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16232     Diag(Loc, diag::err_duplicate_member) << II;
16233     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16234     NewFD->setInvalidDecl();
16235   }
16236 
16237   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16238     if (Record->isUnion()) {
16239       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16240         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16241         if (RDecl->getDefinition()) {
16242           // C++ [class.union]p1: An object of a class with a non-trivial
16243           // constructor, a non-trivial copy constructor, a non-trivial
16244           // destructor, or a non-trivial copy assignment operator
16245           // cannot be a member of a union, nor can an array of such
16246           // objects.
16247           if (CheckNontrivialField(NewFD))
16248             NewFD->setInvalidDecl();
16249         }
16250       }
16251 
16252       // C++ [class.union]p1: If a union contains a member of reference type,
16253       // the program is ill-formed, except when compiling with MSVC extensions
16254       // enabled.
16255       if (EltTy->isReferenceType()) {
16256         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16257                                     diag::ext_union_member_of_reference_type :
16258                                     diag::err_union_member_of_reference_type)
16259           << NewFD->getDeclName() << EltTy;
16260         if (!getLangOpts().MicrosoftExt)
16261           NewFD->setInvalidDecl();
16262       }
16263     }
16264   }
16265 
16266   // FIXME: We need to pass in the attributes given an AST
16267   // representation, not a parser representation.
16268   if (D) {
16269     // FIXME: The current scope is almost... but not entirely... correct here.
16270     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16271 
16272     if (NewFD->hasAttrs())
16273       CheckAlignasUnderalignment(NewFD);
16274   }
16275 
16276   // In auto-retain/release, infer strong retension for fields of
16277   // retainable type.
16278   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16279     NewFD->setInvalidDecl();
16280 
16281   if (T.isObjCGCWeak())
16282     Diag(Loc, diag::warn_attribute_weak_on_field);
16283 
16284   NewFD->setAccess(AS);
16285   return NewFD;
16286 }
16287 
16288 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16289   assert(FD);
16290   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16291 
16292   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16293     return false;
16294 
16295   QualType EltTy = Context.getBaseElementType(FD->getType());
16296   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16297     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16298     if (RDecl->getDefinition()) {
16299       // We check for copy constructors before constructors
16300       // because otherwise we'll never get complaints about
16301       // copy constructors.
16302 
16303       CXXSpecialMember member = CXXInvalid;
16304       // We're required to check for any non-trivial constructors. Since the
16305       // implicit default constructor is suppressed if there are any
16306       // user-declared constructors, we just need to check that there is a
16307       // trivial default constructor and a trivial copy constructor. (We don't
16308       // worry about move constructors here, since this is a C++98 check.)
16309       if (RDecl->hasNonTrivialCopyConstructor())
16310         member = CXXCopyConstructor;
16311       else if (!RDecl->hasTrivialDefaultConstructor())
16312         member = CXXDefaultConstructor;
16313       else if (RDecl->hasNonTrivialCopyAssignment())
16314         member = CXXCopyAssignment;
16315       else if (RDecl->hasNonTrivialDestructor())
16316         member = CXXDestructor;
16317 
16318       if (member != CXXInvalid) {
16319         if (!getLangOpts().CPlusPlus11 &&
16320             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16321           // Objective-C++ ARC: it is an error to have a non-trivial field of
16322           // a union. However, system headers in Objective-C programs
16323           // occasionally have Objective-C lifetime objects within unions,
16324           // and rather than cause the program to fail, we make those
16325           // members unavailable.
16326           SourceLocation Loc = FD->getLocation();
16327           if (getSourceManager().isInSystemHeader(Loc)) {
16328             if (!FD->hasAttr<UnavailableAttr>())
16329               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16330                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16331             return false;
16332           }
16333         }
16334 
16335         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16336                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16337                diag::err_illegal_union_or_anon_struct_member)
16338           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16339         DiagnoseNontrivial(RDecl, member);
16340         return !getLangOpts().CPlusPlus11;
16341       }
16342     }
16343   }
16344 
16345   return false;
16346 }
16347 
16348 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16349 ///  AST enum value.
16350 static ObjCIvarDecl::AccessControl
16351 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16352   switch (ivarVisibility) {
16353   default: llvm_unreachable("Unknown visitibility kind");
16354   case tok::objc_private: return ObjCIvarDecl::Private;
16355   case tok::objc_public: return ObjCIvarDecl::Public;
16356   case tok::objc_protected: return ObjCIvarDecl::Protected;
16357   case tok::objc_package: return ObjCIvarDecl::Package;
16358   }
16359 }
16360 
16361 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16362 /// in order to create an IvarDecl object for it.
16363 Decl *Sema::ActOnIvar(Scope *S,
16364                                 SourceLocation DeclStart,
16365                                 Declarator &D, Expr *BitfieldWidth,
16366                                 tok::ObjCKeywordKind Visibility) {
16367 
16368   IdentifierInfo *II = D.getIdentifier();
16369   Expr *BitWidth = (Expr*)BitfieldWidth;
16370   SourceLocation Loc = DeclStart;
16371   if (II) Loc = D.getIdentifierLoc();
16372 
16373   // FIXME: Unnamed fields can be handled in various different ways, for
16374   // example, unnamed unions inject all members into the struct namespace!
16375 
16376   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16377   QualType T = TInfo->getType();
16378 
16379   if (BitWidth) {
16380     // 6.7.2.1p3, 6.7.2.1p4
16381     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16382     if (!BitWidth)
16383       D.setInvalidType();
16384   } else {
16385     // Not a bitfield.
16386 
16387     // validate II.
16388 
16389   }
16390   if (T->isReferenceType()) {
16391     Diag(Loc, diag::err_ivar_reference_type);
16392     D.setInvalidType();
16393   }
16394   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16395   // than a variably modified type.
16396   else if (T->isVariablyModifiedType()) {
16397     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16398     D.setInvalidType();
16399   }
16400 
16401   // Get the visibility (access control) for this ivar.
16402   ObjCIvarDecl::AccessControl ac =
16403     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16404                                         : ObjCIvarDecl::None;
16405   // Must set ivar's DeclContext to its enclosing interface.
16406   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16407   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16408     return nullptr;
16409   ObjCContainerDecl *EnclosingContext;
16410   if (ObjCImplementationDecl *IMPDecl =
16411       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16412     if (LangOpts.ObjCRuntime.isFragile()) {
16413     // Case of ivar declared in an implementation. Context is that of its class.
16414       EnclosingContext = IMPDecl->getClassInterface();
16415       assert(EnclosingContext && "Implementation has no class interface!");
16416     }
16417     else
16418       EnclosingContext = EnclosingDecl;
16419   } else {
16420     if (ObjCCategoryDecl *CDecl =
16421         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16422       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16423         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16424         return nullptr;
16425       }
16426     }
16427     EnclosingContext = EnclosingDecl;
16428   }
16429 
16430   // Construct the decl.
16431   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16432                                              DeclStart, Loc, II, T,
16433                                              TInfo, ac, (Expr *)BitfieldWidth);
16434 
16435   if (II) {
16436     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16437                                            ForVisibleRedeclaration);
16438     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16439         && !isa<TagDecl>(PrevDecl)) {
16440       Diag(Loc, diag::err_duplicate_member) << II;
16441       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16442       NewID->setInvalidDecl();
16443     }
16444   }
16445 
16446   // Process attributes attached to the ivar.
16447   ProcessDeclAttributes(S, NewID, D);
16448 
16449   if (D.isInvalidType())
16450     NewID->setInvalidDecl();
16451 
16452   // In ARC, infer 'retaining' for ivars of retainable type.
16453   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16454     NewID->setInvalidDecl();
16455 
16456   if (D.getDeclSpec().isModulePrivateSpecified())
16457     NewID->setModulePrivate();
16458 
16459   if (II) {
16460     // FIXME: When interfaces are DeclContexts, we'll need to add
16461     // these to the interface.
16462     S->AddDecl(NewID);
16463     IdResolver.AddDecl(NewID);
16464   }
16465 
16466   if (LangOpts.ObjCRuntime.isNonFragile() &&
16467       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16468     Diag(Loc, diag::warn_ivars_in_interface);
16469 
16470   return NewID;
16471 }
16472 
16473 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16474 /// class and class extensions. For every class \@interface and class
16475 /// extension \@interface, if the last ivar is a bitfield of any type,
16476 /// then add an implicit `char :0` ivar to the end of that interface.
16477 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16478                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16479   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16480     return;
16481 
16482   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16483   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16484 
16485   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16486     return;
16487   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16488   if (!ID) {
16489     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16490       if (!CD->IsClassExtension())
16491         return;
16492     }
16493     // No need to add this to end of @implementation.
16494     else
16495       return;
16496   }
16497   // All conditions are met. Add a new bitfield to the tail end of ivars.
16498   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16499   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16500 
16501   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16502                               DeclLoc, DeclLoc, nullptr,
16503                               Context.CharTy,
16504                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16505                                                                DeclLoc),
16506                               ObjCIvarDecl::Private, BW,
16507                               true);
16508   AllIvarDecls.push_back(Ivar);
16509 }
16510 
16511 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16512                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16513                        SourceLocation RBrac,
16514                        const ParsedAttributesView &Attrs) {
16515   assert(EnclosingDecl && "missing record or interface decl");
16516 
16517   // If this is an Objective-C @implementation or category and we have
16518   // new fields here we should reset the layout of the interface since
16519   // it will now change.
16520   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16521     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16522     switch (DC->getKind()) {
16523     default: break;
16524     case Decl::ObjCCategory:
16525       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16526       break;
16527     case Decl::ObjCImplementation:
16528       Context.
16529         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16530       break;
16531     }
16532   }
16533 
16534   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16535   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16536 
16537   // Start counting up the number of named members; make sure to include
16538   // members of anonymous structs and unions in the total.
16539   unsigned NumNamedMembers = 0;
16540   if (Record) {
16541     for (const auto *I : Record->decls()) {
16542       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16543         if (IFD->getDeclName())
16544           ++NumNamedMembers;
16545     }
16546   }
16547 
16548   // Verify that all the fields are okay.
16549   SmallVector<FieldDecl*, 32> RecFields;
16550 
16551   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16552        i != end; ++i) {
16553     FieldDecl *FD = cast<FieldDecl>(*i);
16554 
16555     // Get the type for the field.
16556     const Type *FDTy = FD->getType().getTypePtr();
16557 
16558     if (!FD->isAnonymousStructOrUnion()) {
16559       // Remember all fields written by the user.
16560       RecFields.push_back(FD);
16561     }
16562 
16563     // If the field is already invalid for some reason, don't emit more
16564     // diagnostics about it.
16565     if (FD->isInvalidDecl()) {
16566       EnclosingDecl->setInvalidDecl();
16567       continue;
16568     }
16569 
16570     // C99 6.7.2.1p2:
16571     //   A structure or union shall not contain a member with
16572     //   incomplete or function type (hence, a structure shall not
16573     //   contain an instance of itself, but may contain a pointer to
16574     //   an instance of itself), except that the last member of a
16575     //   structure with more than one named member may have incomplete
16576     //   array type; such a structure (and any union containing,
16577     //   possibly recursively, a member that is such a structure)
16578     //   shall not be a member of a structure or an element of an
16579     //   array.
16580     bool IsLastField = (i + 1 == Fields.end());
16581     if (FDTy->isFunctionType()) {
16582       // Field declared as a function.
16583       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16584         << FD->getDeclName();
16585       FD->setInvalidDecl();
16586       EnclosingDecl->setInvalidDecl();
16587       continue;
16588     } else if (FDTy->isIncompleteArrayType() &&
16589                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16590       if (Record) {
16591         // Flexible array member.
16592         // Microsoft and g++ is more permissive regarding flexible array.
16593         // It will accept flexible array in union and also
16594         // as the sole element of a struct/class.
16595         unsigned DiagID = 0;
16596         if (!Record->isUnion() && !IsLastField) {
16597           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16598             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16599           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16600           FD->setInvalidDecl();
16601           EnclosingDecl->setInvalidDecl();
16602           continue;
16603         } else if (Record->isUnion())
16604           DiagID = getLangOpts().MicrosoftExt
16605                        ? diag::ext_flexible_array_union_ms
16606                        : getLangOpts().CPlusPlus
16607                              ? diag::ext_flexible_array_union_gnu
16608                              : diag::err_flexible_array_union;
16609         else if (NumNamedMembers < 1)
16610           DiagID = getLangOpts().MicrosoftExt
16611                        ? diag::ext_flexible_array_empty_aggregate_ms
16612                        : getLangOpts().CPlusPlus
16613                              ? diag::ext_flexible_array_empty_aggregate_gnu
16614                              : diag::err_flexible_array_empty_aggregate;
16615 
16616         if (DiagID)
16617           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16618                                           << Record->getTagKind();
16619         // While the layout of types that contain virtual bases is not specified
16620         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16621         // virtual bases after the derived members.  This would make a flexible
16622         // array member declared at the end of an object not adjacent to the end
16623         // of the type.
16624         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16625           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16626               << FD->getDeclName() << Record->getTagKind();
16627         if (!getLangOpts().C99)
16628           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16629             << FD->getDeclName() << Record->getTagKind();
16630 
16631         // If the element type has a non-trivial destructor, we would not
16632         // implicitly destroy the elements, so disallow it for now.
16633         //
16634         // FIXME: GCC allows this. We should probably either implicitly delete
16635         // the destructor of the containing class, or just allow this.
16636         QualType BaseElem = Context.getBaseElementType(FD->getType());
16637         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16638           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16639             << FD->getDeclName() << FD->getType();
16640           FD->setInvalidDecl();
16641           EnclosingDecl->setInvalidDecl();
16642           continue;
16643         }
16644         // Okay, we have a legal flexible array member at the end of the struct.
16645         Record->setHasFlexibleArrayMember(true);
16646       } else {
16647         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16648         // unless they are followed by another ivar. That check is done
16649         // elsewhere, after synthesized ivars are known.
16650       }
16651     } else if (!FDTy->isDependentType() &&
16652                RequireCompleteType(FD->getLocation(), FD->getType(),
16653                                    diag::err_field_incomplete)) {
16654       // Incomplete type
16655       FD->setInvalidDecl();
16656       EnclosingDecl->setInvalidDecl();
16657       continue;
16658     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16659       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16660         // A type which contains a flexible array member is considered to be a
16661         // flexible array member.
16662         Record->setHasFlexibleArrayMember(true);
16663         if (!Record->isUnion()) {
16664           // If this is a struct/class and this is not the last element, reject
16665           // it.  Note that GCC supports variable sized arrays in the middle of
16666           // structures.
16667           if (!IsLastField)
16668             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16669               << FD->getDeclName() << FD->getType();
16670           else {
16671             // We support flexible arrays at the end of structs in
16672             // other structs as an extension.
16673             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16674               << FD->getDeclName();
16675           }
16676         }
16677       }
16678       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16679           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16680                                  diag::err_abstract_type_in_decl,
16681                                  AbstractIvarType)) {
16682         // Ivars can not have abstract class types
16683         FD->setInvalidDecl();
16684       }
16685       if (Record && FDTTy->getDecl()->hasObjectMember())
16686         Record->setHasObjectMember(true);
16687       if (Record && FDTTy->getDecl()->hasVolatileMember())
16688         Record->setHasVolatileMember(true);
16689     } else if (FDTy->isObjCObjectType()) {
16690       /// A field cannot be an Objective-c object
16691       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16692         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16693       QualType T = Context.getObjCObjectPointerType(FD->getType());
16694       FD->setType(T);
16695     } else if (Record && Record->isUnion() &&
16696                FD->getType().hasNonTrivialObjCLifetime() &&
16697                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16698                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16699                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16700                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16701       // For backward compatibility, fields of C unions declared in system
16702       // headers that have non-trivial ObjC ownership qualifications are marked
16703       // as unavailable unless the qualifier is explicit and __strong. This can
16704       // break ABI compatibility between programs compiled with ARC and MRR, but
16705       // is a better option than rejecting programs using those unions under
16706       // ARC.
16707       FD->addAttr(UnavailableAttr::CreateImplicit(
16708           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16709           FD->getLocation()));
16710     } else if (getLangOpts().ObjC &&
16711                getLangOpts().getGC() != LangOptions::NonGC &&
16712                Record && !Record->hasObjectMember()) {
16713       if (FD->getType()->isObjCObjectPointerType() ||
16714           FD->getType().isObjCGCStrong())
16715         Record->setHasObjectMember(true);
16716       else if (Context.getAsArrayType(FD->getType())) {
16717         QualType BaseType = Context.getBaseElementType(FD->getType());
16718         if (BaseType->isRecordType() &&
16719             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16720           Record->setHasObjectMember(true);
16721         else if (BaseType->isObjCObjectPointerType() ||
16722                  BaseType.isObjCGCStrong())
16723                Record->setHasObjectMember(true);
16724       }
16725     }
16726 
16727     if (Record && !getLangOpts().CPlusPlus &&
16728         !shouldIgnoreForRecordTriviality(FD)) {
16729       QualType FT = FD->getType();
16730       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16731         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16732         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16733             Record->isUnion())
16734           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16735       }
16736       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16737       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16738         Record->setNonTrivialToPrimitiveCopy(true);
16739         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16740           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16741       }
16742       if (FT.isDestructedType()) {
16743         Record->setNonTrivialToPrimitiveDestroy(true);
16744         Record->setParamDestroyedInCallee(true);
16745         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16746           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16747       }
16748 
16749       if (const auto *RT = FT->getAs<RecordType>()) {
16750         if (RT->getDecl()->getArgPassingRestrictions() ==
16751             RecordDecl::APK_CanNeverPassInRegs)
16752           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16753       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16754         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16755     }
16756 
16757     if (Record && FD->getType().isVolatileQualified())
16758       Record->setHasVolatileMember(true);
16759     // Keep track of the number of named members.
16760     if (FD->getIdentifier())
16761       ++NumNamedMembers;
16762   }
16763 
16764   // Okay, we successfully defined 'Record'.
16765   if (Record) {
16766     bool Completed = false;
16767     if (CXXRecord) {
16768       if (!CXXRecord->isInvalidDecl()) {
16769         // Set access bits correctly on the directly-declared conversions.
16770         for (CXXRecordDecl::conversion_iterator
16771                I = CXXRecord->conversion_begin(),
16772                E = CXXRecord->conversion_end(); I != E; ++I)
16773           I.setAccess((*I)->getAccess());
16774       }
16775 
16776       if (!CXXRecord->isDependentType()) {
16777         // Add any implicitly-declared members to this class.
16778         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16779 
16780         if (!CXXRecord->isInvalidDecl()) {
16781           // If we have virtual base classes, we may end up finding multiple
16782           // final overriders for a given virtual function. Check for this
16783           // problem now.
16784           if (CXXRecord->getNumVBases()) {
16785             CXXFinalOverriderMap FinalOverriders;
16786             CXXRecord->getFinalOverriders(FinalOverriders);
16787 
16788             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16789                                              MEnd = FinalOverriders.end();
16790                  M != MEnd; ++M) {
16791               for (OverridingMethods::iterator SO = M->second.begin(),
16792                                             SOEnd = M->second.end();
16793                    SO != SOEnd; ++SO) {
16794                 assert(SO->second.size() > 0 &&
16795                        "Virtual function without overriding functions?");
16796                 if (SO->second.size() == 1)
16797                   continue;
16798 
16799                 // C++ [class.virtual]p2:
16800                 //   In a derived class, if a virtual member function of a base
16801                 //   class subobject has more than one final overrider the
16802                 //   program is ill-formed.
16803                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16804                   << (const NamedDecl *)M->first << Record;
16805                 Diag(M->first->getLocation(),
16806                      diag::note_overridden_virtual_function);
16807                 for (OverridingMethods::overriding_iterator
16808                           OM = SO->second.begin(),
16809                        OMEnd = SO->second.end();
16810                      OM != OMEnd; ++OM)
16811                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16812                     << (const NamedDecl *)M->first << OM->Method->getParent();
16813 
16814                 Record->setInvalidDecl();
16815               }
16816             }
16817             CXXRecord->completeDefinition(&FinalOverriders);
16818             Completed = true;
16819           }
16820         }
16821       }
16822     }
16823 
16824     if (!Completed)
16825       Record->completeDefinition();
16826 
16827     // Handle attributes before checking the layout.
16828     ProcessDeclAttributeList(S, Record, Attrs);
16829 
16830     // We may have deferred checking for a deleted destructor. Check now.
16831     if (CXXRecord) {
16832       auto *Dtor = CXXRecord->getDestructor();
16833       if (Dtor && Dtor->isImplicit() &&
16834           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16835         CXXRecord->setImplicitDestructorIsDeleted();
16836         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16837       }
16838     }
16839 
16840     if (Record->hasAttrs()) {
16841       CheckAlignasUnderalignment(Record);
16842 
16843       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16844         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16845                                            IA->getRange(), IA->getBestCase(),
16846                                            IA->getInheritanceModel());
16847     }
16848 
16849     // Check if the structure/union declaration is a type that can have zero
16850     // size in C. For C this is a language extension, for C++ it may cause
16851     // compatibility problems.
16852     bool CheckForZeroSize;
16853     if (!getLangOpts().CPlusPlus) {
16854       CheckForZeroSize = true;
16855     } else {
16856       // For C++ filter out types that cannot be referenced in C code.
16857       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16858       CheckForZeroSize =
16859           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16860           !CXXRecord->isDependentType() &&
16861           CXXRecord->isCLike();
16862     }
16863     if (CheckForZeroSize) {
16864       bool ZeroSize = true;
16865       bool IsEmpty = true;
16866       unsigned NonBitFields = 0;
16867       for (RecordDecl::field_iterator I = Record->field_begin(),
16868                                       E = Record->field_end();
16869            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16870         IsEmpty = false;
16871         if (I->isUnnamedBitfield()) {
16872           if (!I->isZeroLengthBitField(Context))
16873             ZeroSize = false;
16874         } else {
16875           ++NonBitFields;
16876           QualType FieldType = I->getType();
16877           if (FieldType->isIncompleteType() ||
16878               !Context.getTypeSizeInChars(FieldType).isZero())
16879             ZeroSize = false;
16880         }
16881       }
16882 
16883       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16884       // allowed in C++, but warn if its declaration is inside
16885       // extern "C" block.
16886       if (ZeroSize) {
16887         Diag(RecLoc, getLangOpts().CPlusPlus ?
16888                          diag::warn_zero_size_struct_union_in_extern_c :
16889                          diag::warn_zero_size_struct_union_compat)
16890           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16891       }
16892 
16893       // Structs without named members are extension in C (C99 6.7.2.1p7),
16894       // but are accepted by GCC.
16895       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16896         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16897                                diag::ext_no_named_members_in_struct_union)
16898           << Record->isUnion();
16899       }
16900     }
16901   } else {
16902     ObjCIvarDecl **ClsFields =
16903       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16904     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16905       ID->setEndOfDefinitionLoc(RBrac);
16906       // Add ivar's to class's DeclContext.
16907       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16908         ClsFields[i]->setLexicalDeclContext(ID);
16909         ID->addDecl(ClsFields[i]);
16910       }
16911       // Must enforce the rule that ivars in the base classes may not be
16912       // duplicates.
16913       if (ID->getSuperClass())
16914         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16915     } else if (ObjCImplementationDecl *IMPDecl =
16916                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16917       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16918       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16919         // Ivar declared in @implementation never belongs to the implementation.
16920         // Only it is in implementation's lexical context.
16921         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16922       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16923       IMPDecl->setIvarLBraceLoc(LBrac);
16924       IMPDecl->setIvarRBraceLoc(RBrac);
16925     } else if (ObjCCategoryDecl *CDecl =
16926                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16927       // case of ivars in class extension; all other cases have been
16928       // reported as errors elsewhere.
16929       // FIXME. Class extension does not have a LocEnd field.
16930       // CDecl->setLocEnd(RBrac);
16931       // Add ivar's to class extension's DeclContext.
16932       // Diagnose redeclaration of private ivars.
16933       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16934       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16935         if (IDecl) {
16936           if (const ObjCIvarDecl *ClsIvar =
16937               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16938             Diag(ClsFields[i]->getLocation(),
16939                  diag::err_duplicate_ivar_declaration);
16940             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16941             continue;
16942           }
16943           for (const auto *Ext : IDecl->known_extensions()) {
16944             if (const ObjCIvarDecl *ClsExtIvar
16945                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16946               Diag(ClsFields[i]->getLocation(),
16947                    diag::err_duplicate_ivar_declaration);
16948               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16949               continue;
16950             }
16951           }
16952         }
16953         ClsFields[i]->setLexicalDeclContext(CDecl);
16954         CDecl->addDecl(ClsFields[i]);
16955       }
16956       CDecl->setIvarLBraceLoc(LBrac);
16957       CDecl->setIvarRBraceLoc(RBrac);
16958     }
16959   }
16960 }
16961 
16962 /// Determine whether the given integral value is representable within
16963 /// the given type T.
16964 static bool isRepresentableIntegerValue(ASTContext &Context,
16965                                         llvm::APSInt &Value,
16966                                         QualType T) {
16967   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16968          "Integral type required!");
16969   unsigned BitWidth = Context.getIntWidth(T);
16970 
16971   if (Value.isUnsigned() || Value.isNonNegative()) {
16972     if (T->isSignedIntegerOrEnumerationType())
16973       --BitWidth;
16974     return Value.getActiveBits() <= BitWidth;
16975   }
16976   return Value.getMinSignedBits() <= BitWidth;
16977 }
16978 
16979 // Given an integral type, return the next larger integral type
16980 // (or a NULL type of no such type exists).
16981 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16982   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16983   // enum checking below.
16984   assert((T->isIntegralType(Context) ||
16985          T->isEnumeralType()) && "Integral type required!");
16986   const unsigned NumTypes = 4;
16987   QualType SignedIntegralTypes[NumTypes] = {
16988     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16989   };
16990   QualType UnsignedIntegralTypes[NumTypes] = {
16991     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16992     Context.UnsignedLongLongTy
16993   };
16994 
16995   unsigned BitWidth = Context.getTypeSize(T);
16996   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16997                                                         : UnsignedIntegralTypes;
16998   for (unsigned I = 0; I != NumTypes; ++I)
16999     if (Context.getTypeSize(Types[I]) > BitWidth)
17000       return Types[I];
17001 
17002   return QualType();
17003 }
17004 
17005 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17006                                           EnumConstantDecl *LastEnumConst,
17007                                           SourceLocation IdLoc,
17008                                           IdentifierInfo *Id,
17009                                           Expr *Val) {
17010   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17011   llvm::APSInt EnumVal(IntWidth);
17012   QualType EltTy;
17013 
17014   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17015     Val = nullptr;
17016 
17017   if (Val)
17018     Val = DefaultLvalueConversion(Val).get();
17019 
17020   if (Val) {
17021     if (Enum->isDependentType() || Val->isTypeDependent())
17022       EltTy = Context.DependentTy;
17023     else {
17024       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17025         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17026         // constant-expression in the enumerator-definition shall be a converted
17027         // constant expression of the underlying type.
17028         EltTy = Enum->getIntegerType();
17029         ExprResult Converted =
17030           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17031                                            CCEK_Enumerator);
17032         if (Converted.isInvalid())
17033           Val = nullptr;
17034         else
17035           Val = Converted.get();
17036       } else if (!Val->isValueDependent() &&
17037                  !(Val = VerifyIntegerConstantExpression(Val,
17038                                                          &EnumVal).get())) {
17039         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17040       } else {
17041         if (Enum->isComplete()) {
17042           EltTy = Enum->getIntegerType();
17043 
17044           // In Obj-C and Microsoft mode, require the enumeration value to be
17045           // representable in the underlying type of the enumeration. In C++11,
17046           // we perform a non-narrowing conversion as part of converted constant
17047           // expression checking.
17048           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17049             if (Context.getTargetInfo()
17050                     .getTriple()
17051                     .isWindowsMSVCEnvironment()) {
17052               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17053             } else {
17054               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17055             }
17056           }
17057 
17058           // Cast to the underlying type.
17059           Val = ImpCastExprToType(Val, EltTy,
17060                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17061                                                          : CK_IntegralCast)
17062                     .get();
17063         } else if (getLangOpts().CPlusPlus) {
17064           // C++11 [dcl.enum]p5:
17065           //   If the underlying type is not fixed, the type of each enumerator
17066           //   is the type of its initializing value:
17067           //     - If an initializer is specified for an enumerator, the
17068           //       initializing value has the same type as the expression.
17069           EltTy = Val->getType();
17070         } else {
17071           // C99 6.7.2.2p2:
17072           //   The expression that defines the value of an enumeration constant
17073           //   shall be an integer constant expression that has a value
17074           //   representable as an int.
17075 
17076           // Complain if the value is not representable in an int.
17077           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17078             Diag(IdLoc, diag::ext_enum_value_not_int)
17079               << EnumVal.toString(10) << Val->getSourceRange()
17080               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17081           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17082             // Force the type of the expression to 'int'.
17083             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17084           }
17085           EltTy = Val->getType();
17086         }
17087       }
17088     }
17089   }
17090 
17091   if (!Val) {
17092     if (Enum->isDependentType())
17093       EltTy = Context.DependentTy;
17094     else if (!LastEnumConst) {
17095       // C++0x [dcl.enum]p5:
17096       //   If the underlying type is not fixed, the type of each enumerator
17097       //   is the type of its initializing value:
17098       //     - If no initializer is specified for the first enumerator, the
17099       //       initializing value has an unspecified integral type.
17100       //
17101       // GCC uses 'int' for its unspecified integral type, as does
17102       // C99 6.7.2.2p3.
17103       if (Enum->isFixed()) {
17104         EltTy = Enum->getIntegerType();
17105       }
17106       else {
17107         EltTy = Context.IntTy;
17108       }
17109     } else {
17110       // Assign the last value + 1.
17111       EnumVal = LastEnumConst->getInitVal();
17112       ++EnumVal;
17113       EltTy = LastEnumConst->getType();
17114 
17115       // Check for overflow on increment.
17116       if (EnumVal < LastEnumConst->getInitVal()) {
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         //
17121         //     - Otherwise the type of the initializing value is the same as
17122         //       the type of the initializing value of the preceding enumerator
17123         //       unless the incremented value is not representable in that type,
17124         //       in which case the type is an unspecified integral type
17125         //       sufficient to contain the incremented value. If no such type
17126         //       exists, the program is ill-formed.
17127         QualType T = getNextLargerIntegralType(Context, EltTy);
17128         if (T.isNull() || Enum->isFixed()) {
17129           // There is no integral type larger enough to represent this
17130           // value. Complain, then allow the value to wrap around.
17131           EnumVal = LastEnumConst->getInitVal();
17132           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17133           ++EnumVal;
17134           if (Enum->isFixed())
17135             // When the underlying type is fixed, this is ill-formed.
17136             Diag(IdLoc, diag::err_enumerator_wrapped)
17137               << EnumVal.toString(10)
17138               << EltTy;
17139           else
17140             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17141               << EnumVal.toString(10);
17142         } else {
17143           EltTy = T;
17144         }
17145 
17146         // Retrieve the last enumerator's value, extent that type to the
17147         // type that is supposed to be large enough to represent the incremented
17148         // value, then increment.
17149         EnumVal = LastEnumConst->getInitVal();
17150         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17151         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17152         ++EnumVal;
17153 
17154         // If we're not in C++, diagnose the overflow of enumerator values,
17155         // which in C99 means that the enumerator value is not representable in
17156         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17157         // permits enumerator values that are representable in some larger
17158         // integral type.
17159         if (!getLangOpts().CPlusPlus && !T.isNull())
17160           Diag(IdLoc, diag::warn_enum_value_overflow);
17161       } else if (!getLangOpts().CPlusPlus &&
17162                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17163         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17164         Diag(IdLoc, diag::ext_enum_value_not_int)
17165           << EnumVal.toString(10) << 1;
17166       }
17167     }
17168   }
17169 
17170   if (!EltTy->isDependentType()) {
17171     // Make the enumerator value match the signedness and size of the
17172     // enumerator's type.
17173     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17174     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17175   }
17176 
17177   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17178                                   Val, EnumVal);
17179 }
17180 
17181 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17182                                                 SourceLocation IILoc) {
17183   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17184       !getLangOpts().CPlusPlus)
17185     return SkipBodyInfo();
17186 
17187   // We have an anonymous enum definition. Look up the first enumerator to
17188   // determine if we should merge the definition with an existing one and
17189   // skip the body.
17190   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17191                                          forRedeclarationInCurContext());
17192   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17193   if (!PrevECD)
17194     return SkipBodyInfo();
17195 
17196   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17197   NamedDecl *Hidden;
17198   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17199     SkipBodyInfo Skip;
17200     Skip.Previous = Hidden;
17201     return Skip;
17202   }
17203 
17204   return SkipBodyInfo();
17205 }
17206 
17207 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17208                               SourceLocation IdLoc, IdentifierInfo *Id,
17209                               const ParsedAttributesView &Attrs,
17210                               SourceLocation EqualLoc, Expr *Val) {
17211   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17212   EnumConstantDecl *LastEnumConst =
17213     cast_or_null<EnumConstantDecl>(lastEnumConst);
17214 
17215   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17216   // we find one that is.
17217   S = getNonFieldDeclScope(S);
17218 
17219   // Verify that there isn't already something declared with this name in this
17220   // scope.
17221   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17222   LookupName(R, S);
17223   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17224 
17225   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17226     // Maybe we will complain about the shadowed template parameter.
17227     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17228     // Just pretend that we didn't see the previous declaration.
17229     PrevDecl = nullptr;
17230   }
17231 
17232   // C++ [class.mem]p15:
17233   // If T is the name of a class, then each of the following shall have a name
17234   // different from T:
17235   // - every enumerator of every member of class T that is an unscoped
17236   // enumerated type
17237   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17238     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17239                             DeclarationNameInfo(Id, IdLoc));
17240 
17241   EnumConstantDecl *New =
17242     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17243   if (!New)
17244     return nullptr;
17245 
17246   if (PrevDecl) {
17247     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17248       // Check for other kinds of shadowing not already handled.
17249       CheckShadow(New, PrevDecl, R);
17250     }
17251 
17252     // When in C++, we may get a TagDecl with the same name; in this case the
17253     // enum constant will 'hide' the tag.
17254     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17255            "Received TagDecl when not in C++!");
17256     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17257       if (isa<EnumConstantDecl>(PrevDecl))
17258         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17259       else
17260         Diag(IdLoc, diag::err_redefinition) << Id;
17261       notePreviousDefinition(PrevDecl, IdLoc);
17262       return nullptr;
17263     }
17264   }
17265 
17266   // Process attributes.
17267   ProcessDeclAttributeList(S, New, Attrs);
17268   AddPragmaAttributes(S, New);
17269 
17270   // Register this decl in the current scope stack.
17271   New->setAccess(TheEnumDecl->getAccess());
17272   PushOnScopeChains(New, S);
17273 
17274   ActOnDocumentableDecl(New);
17275 
17276   return New;
17277 }
17278 
17279 // Returns true when the enum initial expression does not trigger the
17280 // duplicate enum warning.  A few common cases are exempted as follows:
17281 // Element2 = Element1
17282 // Element2 = Element1 + 1
17283 // Element2 = Element1 - 1
17284 // Where Element2 and Element1 are from the same enum.
17285 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17286   Expr *InitExpr = ECD->getInitExpr();
17287   if (!InitExpr)
17288     return true;
17289   InitExpr = InitExpr->IgnoreImpCasts();
17290 
17291   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17292     if (!BO->isAdditiveOp())
17293       return true;
17294     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17295     if (!IL)
17296       return true;
17297     if (IL->getValue() != 1)
17298       return true;
17299 
17300     InitExpr = BO->getLHS();
17301   }
17302 
17303   // This checks if the elements are from the same enum.
17304   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17305   if (!DRE)
17306     return true;
17307 
17308   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17309   if (!EnumConstant)
17310     return true;
17311 
17312   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17313       Enum)
17314     return true;
17315 
17316   return false;
17317 }
17318 
17319 // Emits a warning when an element is implicitly set a value that
17320 // a previous element has already been set to.
17321 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17322                                         EnumDecl *Enum, QualType EnumType) {
17323   // Avoid anonymous enums
17324   if (!Enum->getIdentifier())
17325     return;
17326 
17327   // Only check for small enums.
17328   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17329     return;
17330 
17331   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17332     return;
17333 
17334   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17335   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17336 
17337   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17338   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17339 
17340   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17341   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17342     llvm::APSInt Val = D->getInitVal();
17343     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17344   };
17345 
17346   DuplicatesVector DupVector;
17347   ValueToVectorMap EnumMap;
17348 
17349   // Populate the EnumMap with all values represented by enum constants without
17350   // an initializer.
17351   for (auto *Element : Elements) {
17352     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17353 
17354     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17355     // this constant.  Skip this enum since it may be ill-formed.
17356     if (!ECD) {
17357       return;
17358     }
17359 
17360     // Constants with initalizers are handled in the next loop.
17361     if (ECD->getInitExpr())
17362       continue;
17363 
17364     // Duplicate values are handled in the next loop.
17365     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17366   }
17367 
17368   if (EnumMap.size() == 0)
17369     return;
17370 
17371   // Create vectors for any values that has duplicates.
17372   for (auto *Element : Elements) {
17373     // The last loop returned if any constant was null.
17374     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17375     if (!ValidDuplicateEnum(ECD, Enum))
17376       continue;
17377 
17378     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17379     if (Iter == EnumMap.end())
17380       continue;
17381 
17382     DeclOrVector& Entry = Iter->second;
17383     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17384       // Ensure constants are different.
17385       if (D == ECD)
17386         continue;
17387 
17388       // Create new vector and push values onto it.
17389       auto Vec = std::make_unique<ECDVector>();
17390       Vec->push_back(D);
17391       Vec->push_back(ECD);
17392 
17393       // Update entry to point to the duplicates vector.
17394       Entry = Vec.get();
17395 
17396       // Store the vector somewhere we can consult later for quick emission of
17397       // diagnostics.
17398       DupVector.emplace_back(std::move(Vec));
17399       continue;
17400     }
17401 
17402     ECDVector *Vec = Entry.get<ECDVector*>();
17403     // Make sure constants are not added more than once.
17404     if (*Vec->begin() == ECD)
17405       continue;
17406 
17407     Vec->push_back(ECD);
17408   }
17409 
17410   // Emit diagnostics.
17411   for (const auto &Vec : DupVector) {
17412     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17413 
17414     // Emit warning for one enum constant.
17415     auto *FirstECD = Vec->front();
17416     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17417       << FirstECD << FirstECD->getInitVal().toString(10)
17418       << FirstECD->getSourceRange();
17419 
17420     // Emit one note for each of the remaining enum constants with
17421     // the same value.
17422     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17423       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17424         << ECD << ECD->getInitVal().toString(10)
17425         << ECD->getSourceRange();
17426   }
17427 }
17428 
17429 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17430                              bool AllowMask) const {
17431   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17432   assert(ED->isCompleteDefinition() && "expected enum definition");
17433 
17434   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17435   llvm::APInt &FlagBits = R.first->second;
17436 
17437   if (R.second) {
17438     for (auto *E : ED->enumerators()) {
17439       const auto &EVal = E->getInitVal();
17440       // Only single-bit enumerators introduce new flag values.
17441       if (EVal.isPowerOf2())
17442         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17443     }
17444   }
17445 
17446   // A value is in a flag enum if either its bits are a subset of the enum's
17447   // flag bits (the first condition) or we are allowing masks and the same is
17448   // true of its complement (the second condition). When masks are allowed, we
17449   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17450   //
17451   // While it's true that any value could be used as a mask, the assumption is
17452   // that a mask will have all of the insignificant bits set. Anything else is
17453   // likely a logic error.
17454   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17455   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17456 }
17457 
17458 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17459                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17460                          const ParsedAttributesView &Attrs) {
17461   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17462   QualType EnumType = Context.getTypeDeclType(Enum);
17463 
17464   ProcessDeclAttributeList(S, Enum, Attrs);
17465 
17466   if (Enum->isDependentType()) {
17467     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17468       EnumConstantDecl *ECD =
17469         cast_or_null<EnumConstantDecl>(Elements[i]);
17470       if (!ECD) continue;
17471 
17472       ECD->setType(EnumType);
17473     }
17474 
17475     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17476     return;
17477   }
17478 
17479   // TODO: If the result value doesn't fit in an int, it must be a long or long
17480   // long value.  ISO C does not support this, but GCC does as an extension,
17481   // emit a warning.
17482   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17483   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17484   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17485 
17486   // Verify that all the values are okay, compute the size of the values, and
17487   // reverse the list.
17488   unsigned NumNegativeBits = 0;
17489   unsigned NumPositiveBits = 0;
17490 
17491   // Keep track of whether all elements have type int.
17492   bool AllElementsInt = true;
17493 
17494   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17495     EnumConstantDecl *ECD =
17496       cast_or_null<EnumConstantDecl>(Elements[i]);
17497     if (!ECD) continue;  // Already issued a diagnostic.
17498 
17499     const llvm::APSInt &InitVal = ECD->getInitVal();
17500 
17501     // Keep track of the size of positive and negative values.
17502     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17503       NumPositiveBits = std::max(NumPositiveBits,
17504                                  (unsigned)InitVal.getActiveBits());
17505     else
17506       NumNegativeBits = std::max(NumNegativeBits,
17507                                  (unsigned)InitVal.getMinSignedBits());
17508 
17509     // Keep track of whether every enum element has type int (very common).
17510     if (AllElementsInt)
17511       AllElementsInt = ECD->getType() == Context.IntTy;
17512   }
17513 
17514   // Figure out the type that should be used for this enum.
17515   QualType BestType;
17516   unsigned BestWidth;
17517 
17518   // C++0x N3000 [conv.prom]p3:
17519   //   An rvalue of an unscoped enumeration type whose underlying
17520   //   type is not fixed can be converted to an rvalue of the first
17521   //   of the following types that can represent all the values of
17522   //   the enumeration: int, unsigned int, long int, unsigned long
17523   //   int, long long int, or unsigned long long int.
17524   // C99 6.4.4.3p2:
17525   //   An identifier declared as an enumeration constant has type int.
17526   // The C99 rule is modified by a gcc extension
17527   QualType BestPromotionType;
17528 
17529   bool Packed = Enum->hasAttr<PackedAttr>();
17530   // -fshort-enums is the equivalent to specifying the packed attribute on all
17531   // enum definitions.
17532   if (LangOpts.ShortEnums)
17533     Packed = true;
17534 
17535   // If the enum already has a type because it is fixed or dictated by the
17536   // target, promote that type instead of analyzing the enumerators.
17537   if (Enum->isComplete()) {
17538     BestType = Enum->getIntegerType();
17539     if (BestType->isPromotableIntegerType())
17540       BestPromotionType = Context.getPromotedIntegerType(BestType);
17541     else
17542       BestPromotionType = BestType;
17543 
17544     BestWidth = Context.getIntWidth(BestType);
17545   }
17546   else if (NumNegativeBits) {
17547     // If there is a negative value, figure out the smallest integer type (of
17548     // int/long/longlong) that fits.
17549     // If it's packed, check also if it fits a char or a short.
17550     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17551       BestType = Context.SignedCharTy;
17552       BestWidth = CharWidth;
17553     } else if (Packed && NumNegativeBits <= ShortWidth &&
17554                NumPositiveBits < ShortWidth) {
17555       BestType = Context.ShortTy;
17556       BestWidth = ShortWidth;
17557     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17558       BestType = Context.IntTy;
17559       BestWidth = IntWidth;
17560     } else {
17561       BestWidth = Context.getTargetInfo().getLongWidth();
17562 
17563       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17564         BestType = Context.LongTy;
17565       } else {
17566         BestWidth = Context.getTargetInfo().getLongLongWidth();
17567 
17568         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17569           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17570         BestType = Context.LongLongTy;
17571       }
17572     }
17573     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17574   } else {
17575     // If there is no negative value, figure out the smallest type that fits
17576     // all of the enumerator values.
17577     // If it's packed, check also if it fits a char or a short.
17578     if (Packed && NumPositiveBits <= CharWidth) {
17579       BestType = Context.UnsignedCharTy;
17580       BestPromotionType = Context.IntTy;
17581       BestWidth = CharWidth;
17582     } else if (Packed && NumPositiveBits <= ShortWidth) {
17583       BestType = Context.UnsignedShortTy;
17584       BestPromotionType = Context.IntTy;
17585       BestWidth = ShortWidth;
17586     } else if (NumPositiveBits <= IntWidth) {
17587       BestType = Context.UnsignedIntTy;
17588       BestWidth = IntWidth;
17589       BestPromotionType
17590         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17591                            ? Context.UnsignedIntTy : Context.IntTy;
17592     } else if (NumPositiveBits <=
17593                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17594       BestType = Context.UnsignedLongTy;
17595       BestPromotionType
17596         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17597                            ? Context.UnsignedLongTy : Context.LongTy;
17598     } else {
17599       BestWidth = Context.getTargetInfo().getLongLongWidth();
17600       assert(NumPositiveBits <= BestWidth &&
17601              "How could an initializer get larger than ULL?");
17602       BestType = Context.UnsignedLongLongTy;
17603       BestPromotionType
17604         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17605                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17606     }
17607   }
17608 
17609   // Loop over all of the enumerator constants, changing their types to match
17610   // the type of the enum if needed.
17611   for (auto *D : Elements) {
17612     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17613     if (!ECD) continue;  // Already issued a diagnostic.
17614 
17615     // Standard C says the enumerators have int type, but we allow, as an
17616     // extension, the enumerators to be larger than int size.  If each
17617     // enumerator value fits in an int, type it as an int, otherwise type it the
17618     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17619     // that X has type 'int', not 'unsigned'.
17620 
17621     // Determine whether the value fits into an int.
17622     llvm::APSInt InitVal = ECD->getInitVal();
17623 
17624     // If it fits into an integer type, force it.  Otherwise force it to match
17625     // the enum decl type.
17626     QualType NewTy;
17627     unsigned NewWidth;
17628     bool NewSign;
17629     if (!getLangOpts().CPlusPlus &&
17630         !Enum->isFixed() &&
17631         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17632       NewTy = Context.IntTy;
17633       NewWidth = IntWidth;
17634       NewSign = true;
17635     } else if (ECD->getType() == BestType) {
17636       // Already the right type!
17637       if (getLangOpts().CPlusPlus)
17638         // C++ [dcl.enum]p4: Following the closing brace of an
17639         // enum-specifier, each enumerator has the type of its
17640         // enumeration.
17641         ECD->setType(EnumType);
17642       continue;
17643     } else {
17644       NewTy = BestType;
17645       NewWidth = BestWidth;
17646       NewSign = BestType->isSignedIntegerOrEnumerationType();
17647     }
17648 
17649     // Adjust the APSInt value.
17650     InitVal = InitVal.extOrTrunc(NewWidth);
17651     InitVal.setIsSigned(NewSign);
17652     ECD->setInitVal(InitVal);
17653 
17654     // Adjust the Expr initializer and type.
17655     if (ECD->getInitExpr() &&
17656         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17657       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17658                                                 CK_IntegralCast,
17659                                                 ECD->getInitExpr(),
17660                                                 /*base paths*/ nullptr,
17661                                                 VK_RValue));
17662     if (getLangOpts().CPlusPlus)
17663       // C++ [dcl.enum]p4: Following the closing brace of an
17664       // enum-specifier, each enumerator has the type of its
17665       // enumeration.
17666       ECD->setType(EnumType);
17667     else
17668       ECD->setType(NewTy);
17669   }
17670 
17671   Enum->completeDefinition(BestType, BestPromotionType,
17672                            NumPositiveBits, NumNegativeBits);
17673 
17674   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17675 
17676   if (Enum->isClosedFlag()) {
17677     for (Decl *D : Elements) {
17678       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17679       if (!ECD) continue;  // Already issued a diagnostic.
17680 
17681       llvm::APSInt InitVal = ECD->getInitVal();
17682       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17683           !IsValueInFlagEnum(Enum, InitVal, true))
17684         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17685           << ECD << Enum;
17686     }
17687   }
17688 
17689   // Now that the enum type is defined, ensure it's not been underaligned.
17690   if (Enum->hasAttrs())
17691     CheckAlignasUnderalignment(Enum);
17692 }
17693 
17694 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17695                                   SourceLocation StartLoc,
17696                                   SourceLocation EndLoc) {
17697   StringLiteral *AsmString = cast<StringLiteral>(expr);
17698 
17699   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17700                                                    AsmString, StartLoc,
17701                                                    EndLoc);
17702   CurContext->addDecl(New);
17703   return New;
17704 }
17705 
17706 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17707                                       IdentifierInfo* AliasName,
17708                                       SourceLocation PragmaLoc,
17709                                       SourceLocation NameLoc,
17710                                       SourceLocation AliasNameLoc) {
17711   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17712                                          LookupOrdinaryName);
17713   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17714                            AttributeCommonInfo::AS_Pragma);
17715   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17716       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17717 
17718   // If a declaration that:
17719   // 1) declares a function or a variable
17720   // 2) has external linkage
17721   // already exists, add a label attribute to it.
17722   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17723     if (isDeclExternC(PrevDecl))
17724       PrevDecl->addAttr(Attr);
17725     else
17726       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17727           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17728   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17729   } else
17730     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17731 }
17732 
17733 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17734                              SourceLocation PragmaLoc,
17735                              SourceLocation NameLoc) {
17736   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17737 
17738   if (PrevDecl) {
17739     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17740   } else {
17741     (void)WeakUndeclaredIdentifiers.insert(
17742       std::pair<IdentifierInfo*,WeakInfo>
17743         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17744   }
17745 }
17746 
17747 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17748                                 IdentifierInfo* AliasName,
17749                                 SourceLocation PragmaLoc,
17750                                 SourceLocation NameLoc,
17751                                 SourceLocation AliasNameLoc) {
17752   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17753                                     LookupOrdinaryName);
17754   WeakInfo W = WeakInfo(Name, NameLoc);
17755 
17756   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17757     if (!PrevDecl->hasAttr<AliasAttr>())
17758       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17759         DeclApplyPragmaWeak(TUScope, ND, W);
17760   } else {
17761     (void)WeakUndeclaredIdentifiers.insert(
17762       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17763   }
17764 }
17765 
17766 Decl *Sema::getObjCDeclContext() const {
17767   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17768 }
17769 
17770 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17771   // Templates are emitted when they're instantiated.
17772   if (FD->isDependentContext())
17773     return FunctionEmissionStatus::TemplateDiscarded;
17774 
17775   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17776   if (LangOpts.OpenMPIsDevice) {
17777     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17778         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17779     if (DevTy.hasValue()) {
17780       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17781         OMPES = FunctionEmissionStatus::OMPDiscarded;
17782       else if (DeviceKnownEmittedFns.count(FD) > 0)
17783         OMPES = FunctionEmissionStatus::Emitted;
17784     }
17785   } else if (LangOpts.OpenMP) {
17786     // In OpenMP 4.5 all the functions are host functions.
17787     if (LangOpts.OpenMP <= 45) {
17788       OMPES = FunctionEmissionStatus::Emitted;
17789     } else {
17790       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17791           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17792       // In OpenMP 5.0 or above, DevTy may be changed later by
17793       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17794       // having no value does not imply host. The emission status will be
17795       // checked again at the end of compilation unit.
17796       if (DevTy.hasValue()) {
17797         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17798           OMPES = FunctionEmissionStatus::OMPDiscarded;
17799         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17800           OMPES = FunctionEmissionStatus::Emitted;
17801         }
17802       }
17803     }
17804   }
17805   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17806       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17807     return OMPES;
17808 
17809   if (LangOpts.CUDA) {
17810     // When compiling for device, host functions are never emitted.  Similarly,
17811     // when compiling for host, device and global functions are never emitted.
17812     // (Technically, we do emit a host-side stub for global functions, but this
17813     // doesn't count for our purposes here.)
17814     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17815     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17816       return FunctionEmissionStatus::CUDADiscarded;
17817     if (!LangOpts.CUDAIsDevice &&
17818         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17819       return FunctionEmissionStatus::CUDADiscarded;
17820 
17821     // Check whether this function is externally visible -- if so, it's
17822     // known-emitted.
17823     //
17824     // We have to check the GVA linkage of the function's *definition* -- if we
17825     // only have a declaration, we don't know whether or not the function will
17826     // be emitted, because (say) the definition could include "inline".
17827     FunctionDecl *Def = FD->getDefinition();
17828 
17829     if (Def &&
17830         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17831         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17832       return FunctionEmissionStatus::Emitted;
17833   }
17834 
17835   // Otherwise, the function is known-emitted if it's in our set of
17836   // known-emitted functions.
17837   return (DeviceKnownEmittedFns.count(FD) > 0)
17838              ? FunctionEmissionStatus::Emitted
17839              : FunctionEmissionStatus::Unknown;
17840 }
17841 
17842 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17843   // Host-side references to a __global__ function refer to the stub, so the
17844   // function itself is never emitted and therefore should not be marked.
17845   // If we have host fn calls kernel fn calls host+device, the HD function
17846   // does not get instantiated on the host. We model this by omitting at the
17847   // call to the kernel from the callgraph. This ensures that, when compiling
17848   // for host, only HD functions actually called from the host get marked as
17849   // known-emitted.
17850   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17851          IdentifyCUDATarget(Callee) == CFT_Global;
17852 }
17853